builder.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. flags.push.apply(flags, ctx.config.cflags);
  388. flags.push.apply(flags, ctx.builder.fileCflags[cFile] || []);
  389. if (includeDirs) {
  390. for (let i = 0; i < ctx.config.includeDirs.length; i++) {
  391. if (flags[flags.indexOf(ctx.config.includeDirs[i])-1] === '-I') {
  392. continue;
  393. }
  394. flags.push('-I');
  395. flags.push(ctx.config.includeDirs[i]);
  396. }
  397. }
  398. return flags;
  399. };
  400. const preprocessFile = function (cFile, ctx, callback)
  401. {
  402. if (ctx.state.cFiles[cFile]) {
  403. return void callback();
  404. }
  405. const state = ctx.state;
  406. //debug(' preprocessing ' + cFile);
  407. //debug('\x1b[2;32mCompiling ' + cFile + '\x1b[0m');
  408. const fileObj = mkFile();
  409. let fileContent = '';
  410. const cflags = getFlags(ctx, cFile, true);
  411. fileObj.cflags = getFlags(ctx, cFile, false);
  412. nThen((w) => {
  413. //debug("CPP");
  414. cc(ctx, ['-E', ...cflags, cFile], w(function (err, output) {
  415. if (err) { throw err; }
  416. fileContent = output;
  417. return false;
  418. }), '');
  419. // Stat the C file
  420. Fs.stat(cFile, w(function (err, st) {
  421. if (err) { throw err; }
  422. fileObj.mtime = st.mtime.getTime();
  423. }));
  424. }).nThen((w) => {
  425. //debug("Preprocess");
  426. preprocess(fileContent, ctx, fileObj, cFile, w(function (err, output) {
  427. if (err) { throw err; }
  428. Fs.writeFile(getIFile(ctx, cFile), output, w(function (err) {
  429. if (err) { throw err; }
  430. }));
  431. }));
  432. // Also snatch the local includes
  433. const includes = fileContent.match(/# [0-9]+ "\.\/[^"]*"/g) || [];
  434. const uniqIncl = {};
  435. for (const incl of includes) {
  436. uniqIncl[incl.replace(/^.* "\.\//, '').slice(0,-1)] = 1;
  437. }
  438. fileObj.includes = Object.keys(uniqIncl);
  439. fileObj.includes.forEach((incl) => {
  440. if (ctx.state.hFiles[incl]) { return; }
  441. Fs.stat(incl, w((err, st) => {
  442. if (err) { throw err; }
  443. ctx.state.hFiles[incl] = {
  444. mtime: st.mtime.getTime()
  445. };
  446. }));
  447. });
  448. }).nThen(function (_) {
  449. debug('\x1b[2;36mPreprocessing ' + cFile + ' complete\x1b[0m');
  450. state.cFiles[cFile] = fileObj;
  451. ctx.toCompile[cFile] = fileObj;
  452. callback();
  453. });
  454. };
  455. const preprocessFiles = function (ctx, files, callback) {
  456. const added = {};
  457. for (const f of files) { added[f] = 1; }
  458. const doMore = () => {
  459. if (files.length === 0) {
  460. return void callback();
  461. }
  462. const filez = files;
  463. files = [];
  464. nThen((w) => {
  465. filez.forEach((file) => {
  466. preprocessFile(file, ctx, w(() => {
  467. ctx.state.cFiles[file].links.forEach(function (link) {
  468. if (link === file || added[link]) {
  469. return;
  470. }
  471. added[link] = 1;
  472. files.push(link);
  473. });
  474. }));
  475. });
  476. }).nThen((w) => {
  477. doMore();
  478. });
  479. };
  480. doMore();
  481. };
  482. const getLinkOrder = function (cFile, files) /*:string[]*/ {
  483. const completeFiles = [];
  484. const getFile = function (name) {
  485. const f = files[name];
  486. //debug('Resolving links for ' + name);
  487. for (let i = 0; i < f.links.length; i++) {
  488. if (f.links[i] === name) {
  489. continue;
  490. }
  491. if (completeFiles.indexOf(f.links[i]) > -1) {
  492. continue;
  493. }
  494. getFile(f.links[i]);
  495. }
  496. completeFiles.push(name);
  497. };
  498. getFile(cFile);
  499. return completeFiles;
  500. };
  501. // Called on the .c file with a main() function which corrisponds to
  502. // an executable.
  503. // We kick the file entries right out of the state object when they
  504. // or an #include get dirty, so we just need to traverse links to
  505. // make sure everything is present.
  506. const needsToLink = function (ctx, cFile) {
  507. const nlCache = {};
  508. const nll = [];
  509. const nl = (cFile) => {
  510. if (nlCache[cFile]) { return false; }
  511. if (nll.indexOf(cFile) > -1) {
  512. throw new Error(`File ${cFile} is self-referencial:\n${nll.join('\n')}\n\n`);
  513. }
  514. nll.push(cFile);
  515. const out = (() => {
  516. //debug(' ' + cFile);
  517. if (typeof(ctx.state.cFiles[cFile]) !== 'object') {
  518. return true;
  519. }
  520. for (const l of ctx.state.cFiles[cFile].links) {
  521. if (l !== cFile && nl(l)) {
  522. return true;
  523. }
  524. }
  525. nlCache[cFile] = true;
  526. return false;
  527. })();
  528. if (nll.pop() !== cFile) { throw new Error(); }
  529. return out;
  530. };
  531. return nl(cFile);
  532. };
  533. const makeTime = function () {
  534. let time = 0;
  535. return function () {
  536. const oldTime = time;
  537. time = new Date().getTime();
  538. return time - oldTime;
  539. };
  540. };
  541. const link = function (cFile, callback, ctx /*:Builder_Ctx_t*/) {
  542. const state = ctx.state;
  543. const temp = getTempExe(ctx, cFile);
  544. nThen((waitFor) => {
  545. const linkOrder = getLinkOrder(cFile, state.cFiles);
  546. for (let i = 0; i < linkOrder.length; i++) {
  547. linkOrder[i] = getOFile(ctx, linkOrder[i]);
  548. }
  549. const fileObj = state.cFiles[cFile];
  550. const ldArgs = []
  551. .concat(ctx.config.ldflags)
  552. .concat(fileObj.ldflags)
  553. .concat(['-o', temp])
  554. .concat(linkOrder)
  555. .concat(ctx.config.libs);
  556. debug('\x1b[1;31mLinking C executable ' + cFile + '\x1b[0m');
  557. cc(ctx, ldArgs, waitFor(function (err, ret) {
  558. if (err) { throw err; }
  559. return false;
  560. }), '');
  561. }).nThen((_) => callback());
  562. };
  563. const compile = function (ctx, cFile, done) {
  564. //debug("CC");
  565. const file = ctx.state.cFiles[cFile];
  566. const oFile = getOFile(ctx, cFile);
  567. const iFile = getIFile(ctx, cFile);
  568. cc(ctx, ['-c', '-x', 'cpp-output', '-o', oFile, ...file.cflags, iFile], (err) => {
  569. done(err);
  570. return typeof(err) !== 'undefined';
  571. }, '');
  572. };
  573. /**
  574. * Get a copy of process.env with a few entries which are constantly changing removed.
  575. * This prevents isStaleState from returning true every time one builds in a different
  576. * window.
  577. */
  578. const normalizedProcessEnv = function () {
  579. const out = process.env;
  580. delete out.WINDOWID;
  581. delete out.OLDPWD;
  582. return out;
  583. };
  584. const getRebuildIfChangesHash = function (rebuildIfChanges, callback) {
  585. const hash = Crypto.createHash('sha256');
  586. const rebIfChg = [];
  587. nThen(function (waitFor) {
  588. rebuildIfChanges.forEach(function (fileName, i) {
  589. Fs.readFile(fileName, waitFor(function (err, ret) {
  590. if (err) { throw err; }
  591. rebIfChg[i] = ret;
  592. }));
  593. });
  594. hash.update(JSON.stringify(normalizedProcessEnv()));
  595. }).nThen(function (waitFor) {
  596. rebIfChg.forEach(function (data) {
  597. hash.update(data);
  598. });
  599. callback(hash.digest('hex'));
  600. });
  601. };
  602. const probeCompiler = function (ctx /*:Builder_Ctx_t*/, callback) {
  603. nThen(function (waitFor) {
  604. const compilerType = ctx.state.compilerType = {
  605. isLLVM: false,
  606. isClang: false,
  607. isGCC: false,
  608. version: ''
  609. };
  610. compiler(ctx, ['-v'], waitFor(function (ret, out, err) {
  611. // TODO(cjd): afl-clang-fast errors when called with -v
  612. //if (ret !== 0) { throw new Error("Failed to probe compiler ret[" + ret + "]\n" + err); }
  613. if (/Apple LLVM version /.test(err)) {
  614. compilerType.isLLVM = true;
  615. if (/clang/.test(err)) {
  616. // Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
  617. // Target: x86_64-apple-darwin14.4.0
  618. // Thread model: posix
  619. compilerType.isClang = true;
  620. compilerType.version = err.match(/Apple LLVM version ([^ ]+) /)[1];
  621. } else if (/gcc version /.test(err)) {
  622. // Using built-in specs.
  623. // Target: i686-apple-darwin11
  624. // Configured with: /private/const/tmp/llvmgcc42/llvmgcc42.......
  625. // Thread model: posix
  626. // gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
  627. compilerType.isGCC = true;
  628. compilerType.version = err.match(/gcc version ([^ ]+) /)[1];
  629. }
  630. } else if (/clang version /.test(err)) {
  631. // FreeBSD clang version 3.0 (tags/RELEASE_30/final 145349) 20111210
  632. // Target: x86_64-unknown-freebsd10.0
  633. // Thread model: posix
  634. // clang version 3.2 (trunk)
  635. // Target: x86_64-unknown-linux-gnu
  636. // Thread model: posix
  637. compilerType.isLLVM = true;
  638. compilerType.isClang = true;
  639. compilerType.version = err.match(/clang version ([^ ]+) /)[1];
  640. } else if (/gcc version /.test(err)) {
  641. compilerType.isGCC = true;
  642. compilerType.version = err.match(/gcc version ([^ ]+) /)[1];
  643. }
  644. //console.log(JSON.stringify(compilerType));
  645. }), '');
  646. }).nThen(callback);
  647. };
  648. process.on('exit', function () {
  649. console.log("Total build time: " + Math.floor(process.uptime() * 1000) + "ms.");
  650. });
  651. const deepFreeze = (obj) => {
  652. Object.freeze(obj);
  653. for (const k in obj) {
  654. if (typeof(obj[k]) === 'object') { deepFreeze(obj[k]); }
  655. }
  656. };
  657. const sweep = (path, done) => {
  658. let files = [];
  659. nThen((w) => {
  660. Fs.readdir(path, w((err, fls) => {
  661. if (err) { throw err; }
  662. files = fls;
  663. }));
  664. }).nThen((w) => {
  665. files.forEach((f) => {
  666. const file = path + '/' + f;
  667. Fs.stat(file, w((err, st) => {
  668. if (err) { throw err; }
  669. if (st.isDirectory()) {
  670. sweep(file, w(() => {
  671. Fs.rmdir(file, w((err) => {
  672. if (err) { throw err; }
  673. }));
  674. }));
  675. } else {
  676. Fs.unlink(file, w((err) => {
  677. if (err) { throw err; }
  678. }));
  679. }
  680. }));
  681. });
  682. }).nThen((_) => done());
  683. };
  684. module.exports.configure = function (
  685. params /*:Builder_BaseConfig_t*/,
  686. configFunc /*:(Builder_t, Nthen_WaitFor_t)=>void*/
  687. ) /*:Builder_Pub_t*/ {
  688. // Track time taken for various steps
  689. const time = makeTime();
  690. time();
  691. const systemName = params.systemName || process.platform;
  692. const buildDir = params.buildDir || 'build_' + systemName;
  693. let gcc;
  694. if (params.gcc) {
  695. gcc = params.gcc;
  696. } else if (systemName === 'openbsd') {
  697. gcc = 'egcc';
  698. } else if (systemName === 'freebsd') {
  699. gcc = 'clang';
  700. } else {
  701. gcc = 'gcc';
  702. }
  703. // Since many of the compile operations are short, the best
  704. // performance seems to be when running 1.25x the number of jobs as
  705. // cpu cores. On BSD and iphone systems, os.cpus() is not reliable so
  706. // if it returns undefined let's just assume 1
  707. // workaround, nodejs seems to be broken on openbsd (undefined result after second call)
  708. const cpus = Os.cpus();
  709. const jobs = Math.floor((typeof cpus === 'undefined' ? 1 : cpus.length) * 1.25);
  710. const pctx /*:Builder_PreCtx_t*/ = {
  711. buildStage: (_x,_y)=>{},
  712. testStage: (_x,_y)=>{},
  713. packStage: (_x,_y)=>{},
  714. failureStage: (_x,_y)=>{},
  715. successStage: (_x,_y)=>{},
  716. completeStage: (_x,_y)=>{},
  717. failure: false,
  718. linters: [],
  719. executables: [],
  720. tests: [],
  721. toCompile: {},
  722. sema: Saferphore.create(1),
  723. config: {
  724. buildDir,
  725. gcc,
  726. systemName,
  727. version: '',
  728. includeDirs: ['.'],
  729. cflags: [],
  730. ldflags: [],
  731. libs: [],
  732. jobs,
  733. },
  734. };
  735. let state = getStatePrototype();
  736. let ctx;
  737. let hasState = false;
  738. nThen(function (waitFor) {
  739. // make the build directory
  740. Fs.exists(buildDir, waitFor(function (exists) {
  741. if (exists) { return; }
  742. Fs.mkdir(buildDir, {}, waitFor(function (err) {
  743. if (err) { throw err; }
  744. }));
  745. }));
  746. }).nThen(function (waitFor) {
  747. Fs.exists(buildDir + '/tmp', waitFor(function (exists) {
  748. if (exists) {
  749. sweep(buildDir + '/tmp', waitFor());
  750. } else {
  751. Fs.mkdir(buildDir + '/tmp', {}, waitFor(function (err) {
  752. if (err) { throw err; }
  753. }));
  754. }
  755. }));
  756. }).nThen(function (waitFor) {
  757. if (process.env['CJDNS_FULL_REBUILD']) {
  758. debug("CJDNS_FULL_REBUILD set, non-incremental build");
  759. return;
  760. }
  761. // read out the state if it exists
  762. Fs.exists(buildDir + '/state.json', waitFor(function (exists) {
  763. if (!exists) { return; }
  764. Fs.readFile(buildDir + '/state.json', waitFor(function (err, ret) {
  765. if (err) { throw err; }
  766. state = ( JSON.parse(ret) /*:Builder_State_t*/ );
  767. hasState = true;
  768. debug("Loaded state file");
  769. }));
  770. }));
  771. }).nThen(function (waitFor) {
  772. debug("Initialize " + time() + "ms");
  773. // Do the configuration step
  774. if (hasState) {
  775. ctx = finalizeCtx(state, pctx);
  776. return;
  777. }
  778. state = getStatePrototype();
  779. ctx = finalizeCtx(state, pctx);
  780. probeCompiler(ctx, waitFor());
  781. }).nThen(function (waitFor) {
  782. //if (!ctx.builder) { throw new Error(); }
  783. configFunc(ctx.builder, waitFor);
  784. }).nThen(function (_) {
  785. ctx.sema = Saferphore.create(ctx.config.jobs);
  786. if (ctx.config.systemName !== systemName) {
  787. throw new Error("systemName cannot be changed in configure phase " +
  788. "it must be specified in the initial configuration " +
  789. `initial systemName = ${systemName}, changed to ${ctx.config.systemName}`);
  790. }
  791. if (ctx.config.gcc !== gcc) {
  792. throw new Error("gcc cannot be changed in configure phase " +
  793. "it must be specified in the initial configuration " +
  794. `initial gcc = ${gcc}, changed to ${ctx.config.gcc}`);
  795. }
  796. deepFreeze(ctx.config);
  797. debug("Configure " + time() + "ms");
  798. if (!ctx) { throw new Error(); }
  799. postConfigure(ctx, time);
  800. });
  801. const out = Object.freeze({
  802. build: function (x /*:Builder_Stage_t*/) { pctx.buildStage = x; return out; },
  803. test: function (x /*:Builder_Stage_t*/) { pctx.testStage = x; return out; },
  804. pack: function (x /*:Builder_Stage_t*/) { pctx.packStage = x; return out; },
  805. failure: function (x /*:Builder_Stage_t*/) { pctx.failureStage = x; return out; },
  806. success: function (x /*:Builder_Stage_t*/) { pctx.successStage = x; return out; },
  807. complete: function (x /*:Builder_Stage_t*/) { pctx.completeStage = x; return out; },
  808. });
  809. return out;
  810. };
  811. const checkFileMtime = (fileName, done) => {
  812. Fs.stat(fileName, function (err, stat) {
  813. if (err) {
  814. if (err.code === 'ENOENT') {
  815. done(-1);
  816. } else {
  817. throw err;
  818. }
  819. } else {
  820. done(stat.mtime.getTime());
  821. }
  822. });
  823. };
  824. const removeStaleFiles = (ctx, done) => {
  825. const stales = {};
  826. // Transient dependencies are provided by gcc -MM so there's no need to resolve them
  827. const dependents = {};
  828. nThen((w) => {
  829. Object.keys(ctx.state.cFiles).forEach(function (cFile) {
  830. const file = ctx.state.cFiles[cFile];
  831. for (const incl of file.includes) {
  832. if (!ctx.state.hFiles[incl]) {
  833. // Missing the header entirely, definitely stale
  834. debug(`\x1b[1;34m${cFile} stale (header ${incl} deleted)\x1b[0m`);
  835. stales[cFile] = 1;
  836. return;
  837. }
  838. (dependents[incl] = dependents[incl] || []).push(cFile);
  839. }
  840. const cflags = getFlags(ctx, cFile, false);
  841. if (JSON.stringify(cflags) !== JSON.stringify(file.cflags)) {
  842. debug(`\x1b[1;34m${cFile} stale (change of cflags)\x1b[0m`);
  843. stales[cFile] = 1;
  844. return;
  845. }
  846. checkFileMtime(cFile, w((mtime) => {
  847. if (mtime !== file.mtime) {
  848. debug(`\x1b[1;34m${cFile} stale\x1b[0m`);
  849. stales[cFile] = 1;
  850. } else {
  851. Fs.access(getOFile(ctx, cFile), Fs.constants.F_OK, w((err) => {
  852. if (err && err.code !== 'ENOENT') {
  853. throw err;
  854. } else if (err) {
  855. // Not stale but needs to be compiled
  856. ctx.toCompile[cFile] = file;
  857. }
  858. }));
  859. }
  860. }));
  861. });
  862. }).nThen((w) => {
  863. Object.keys(ctx.state.hFiles).forEach(function (hFile) {
  864. const file = ctx.state.hFiles[hFile];
  865. checkFileMtime(hFile, w((mtime) => {
  866. if (mtime === file.mtime) {
  867. return;
  868. } else if (mtime === -1) {
  869. debug(`\x1b[1;34m${hFile} stale (deleted)\x1b[0m`);
  870. delete ctx.state.hFiles[hFile];
  871. } else {
  872. debug(`\x1b[1;34m${hFile} stale\x1b[0m`);
  873. file.mtime = mtime;
  874. }
  875. for (const cFile of (dependents[hFile] || [])) {
  876. debug(`\x1b[1;34m${cFile} stale (includes ${hFile})\x1b[0m`);
  877. stales[cFile] = 1;
  878. }
  879. }));
  880. });
  881. }).nThen((w) => {
  882. Object.keys(stales).forEach((cFile) => {
  883. const file = ctx.state.cFiles[cFile];
  884. if (typeof(file) === 'undefined') { return; }
  885. delete ctx.state.cFiles[cFile];
  886. // Sweep up relevant files
  887. [getIFile(ctx, cFile), getOFile(ctx, cFile)].forEach((deleteMe) => {
  888. if (!deleteMe) { return; }
  889. Fs.unlink(deleteMe, w(function (err) {
  890. if (err && err.code !== 'ENOENT') {
  891. throw err;
  892. }
  893. }));
  894. });
  895. });
  896. }).nThen((w) => {
  897. done();
  898. });
  899. };
  900. const postConfigure = (ctx /*:Builder_Ctx_t*/, time) => {
  901. const state = ctx.state;
  902. nThen((waitFor) => {
  903. removeStaleFiles(ctx, waitFor());
  904. }).nThen(function (waitFor) {
  905. debug("Scan for out of date files " + time() + "ms");
  906. ctx.buildStage(ctx.builder, waitFor);
  907. }).nThen(function (waitFor) {
  908. ctx.executables = ctx.executables.filter((exe) => {
  909. if (!needsToLink(ctx, exe.cFile)) {
  910. debug(`\x1b[1;31m${getExeFile(ctx, exe)} up to date\x1b[0m`);
  911. return false;
  912. }
  913. return true;
  914. });
  915. preprocessFiles(ctx, ctx.executables.map(exe => exe.cFile), waitFor());
  916. }).nThen(function (w) {
  917. debug("Preprocess " + time() + "ms");
  918. // save state
  919. const stateJson = JSON.stringify(state, null, '\t');
  920. Fs.writeFile(ctx.config.buildDir + '/state.json', stateJson, w(function (err) {
  921. if (err) { throw err; }
  922. //debug("Saved state " + time() + "ms");
  923. deepFreeze(state);
  924. }));
  925. }).nThen(function (w) {
  926. Object.keys(ctx.toCompile).forEach((cFile) => {
  927. compile(ctx, cFile, w((err) => {
  928. if (err) {
  929. throw err;
  930. }
  931. debug('\x1b[2;32mCompiling ' + cFile + ' complete\x1b[0m');
  932. }));
  933. });
  934. }).nThen(function (waitFor) {
  935. debug("Compile " + time() + "ms");
  936. for (const exe of ctx.executables) {
  937. if (exe.type === 'exe') {
  938. link(exe.cFile, waitFor(), ctx);
  939. }
  940. }
  941. }).nThen((w) => {
  942. debug("Link " + time() + "ms");
  943. ctx.tests.forEach(function (test) {
  944. test(w(function (output, failure) {
  945. debug(output);
  946. if (failure) {
  947. ctx.failure = true;
  948. }
  949. }));
  950. });
  951. }).nThen(function (waitFor) {
  952. if (ctx.linters.length === 0) {
  953. return;
  954. }
  955. debug("Checking codestyle");
  956. const sema = Saferphore.create(64);
  957. Object.keys(ctx.toCompile).forEach(function (cFile) {
  958. sema.take(waitFor(function (returnAfter) {
  959. Fs.readFile(cFile, waitFor(function (err, ret) {
  960. if (err) { throw err; }
  961. ret = ret.toString('utf8');
  962. nThen(function (waitFor) {
  963. ctx.linters.forEach(function (linter) {
  964. linter(cFile, ret, waitFor(function (out, isErr) {
  965. if (isErr) {
  966. debug("\x1b[1;31m" + out + "\x1b[0m");
  967. ctx.failure = true;
  968. }
  969. }));
  970. });
  971. }).nThen(returnAfter(waitFor()));
  972. }));
  973. }));
  974. });
  975. }).nThen(function (waitFor) {
  976. ctx.testStage(ctx.builder, waitFor);
  977. }).nThen(function (waitFor) {
  978. if (ctx.failure) { return; }
  979. debug("Test " + time() + "ms");
  980. ctx.executables.forEach(function (exe) {
  981. const temp = getTempExe(ctx, exe.cFile);
  982. if (exe.outputFile === temp) { return; }
  983. const outputFile = getExeFile(ctx, exe);
  984. Fs.rename(temp, outputFile, waitFor(function (err) {
  985. // TODO(cjd): It would be better to know in advance whether to expect the file.
  986. if (err && err.code !== 'ENOENT') {
  987. throw err;
  988. }
  989. }));
  990. });
  991. }).nThen(function (waitFor) {
  992. if (ctx.failure) { return; }
  993. ctx.packStage(ctx.builder, waitFor);
  994. }).nThen(function (waitFor) {
  995. if (ctx.failure) { return; }
  996. debug("Pack " + time() + "ms");
  997. }).nThen(function (waitFor) {
  998. if (ctx.failure) { return; }
  999. ctx.successStage(ctx.builder, waitFor);
  1000. }).nThen(function (waitFor) {
  1001. if (!ctx.failure) { return; }
  1002. ctx.failureStage(ctx.builder, waitFor);
  1003. }).nThen(function (waitFor) {
  1004. ctx.completeStage(ctx.builder, waitFor);
  1005. sweep(ctx.config.buildDir + '/tmp', waitFor());
  1006. });
  1007. };