examples_compile.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. #include <tools/ccanlint/ccanlint.h>
  2. #include <tools/tools.h>
  3. #include <ccan/talloc/talloc.h>
  4. #include <ccan/cast/cast.h>
  5. #include <ccan/str/str.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <stdint.h>
  10. #include <string.h>
  11. #include <unistd.h>
  12. #include <ctype.h>
  13. #include <assert.h>
  14. #include <err.h>
  15. #include "build.h"
  16. static const char *can_run(struct manifest *m)
  17. {
  18. if (safe_mode)
  19. return "Safe mode enabled";
  20. if (list_empty(&m->examples))
  21. return "No examples to compile";
  22. return NULL;
  23. }
  24. static void add_mod(struct manifest ***deps, struct manifest *m)
  25. {
  26. unsigned int num = talloc_get_size(*deps) / sizeof(*deps);
  27. *deps = talloc_realloc(NULL, *deps, struct manifest *, num + 1);
  28. (*deps)[num] = m;
  29. }
  30. static bool have_mod(struct manifest *deps[], const char *basename)
  31. {
  32. unsigned int i;
  33. for (i = 0; i < talloc_get_size(deps) / sizeof(*deps); i++)
  34. if (strcmp(deps[i]->basename, basename) == 0)
  35. return true;
  36. return false;
  37. }
  38. static void add_dep(struct manifest ***deps, const char *basename)
  39. {
  40. unsigned int i;
  41. struct manifest *m;
  42. char *errstr;
  43. if (have_mod(*deps, basename))
  44. return;
  45. m = get_manifest(*deps, talloc_asprintf(*deps, "%s/ccan/%s",
  46. ccan_dir, basename));
  47. errstr = build_submodule(m, cflags, COMPILE_NORMAL);
  48. if (errstr)
  49. errx(1, "%s", errstr);
  50. add_mod(deps, m);
  51. /* Get that modules depends as well... */
  52. assert(!safe_mode);
  53. if (m->info_file) {
  54. char **infodeps;
  55. infodeps = get_deps(m, m->dir, false,
  56. &m->info_file->compiled[COMPILE_NORMAL]);
  57. for (i = 0; infodeps[i]; i++) {
  58. if (strstarts(infodeps[i], "ccan/"))
  59. add_dep(deps, infodeps[i] + strlen("ccan/"));
  60. }
  61. }
  62. }
  63. static char *example_obj_list(struct manifest *m, struct ccan_file *f)
  64. {
  65. struct manifest **deps = talloc_array(f, struct manifest *, 0);
  66. char **lines, *list;
  67. unsigned int i;
  68. /* This one for a start. */
  69. add_dep(&deps, m->basename);
  70. /* Other modules implied by includes. */
  71. for (lines = get_ccan_file_lines(f); *lines; lines++) {
  72. unsigned preflen = strspn(*lines, " \t");
  73. if (strstarts(*lines + preflen, "#include <ccan/")) {
  74. char *modname;
  75. modname = talloc_strdup(f, *lines + preflen
  76. + strlen("#include <ccan/"));
  77. modname[strcspn(modname, "/")] = '\0';
  78. if (!have_mod(deps, modname))
  79. add_dep(&deps, modname);
  80. }
  81. }
  82. list = talloc_strdup(f, "");
  83. for (i = 0; i < talloc_get_size(deps) / sizeof(*deps); i++) {
  84. if (deps[i]->compiled[COMPILE_NORMAL])
  85. list = talloc_asprintf_append(list, " %s",
  86. deps[i]->compiled
  87. [COMPILE_NORMAL]);
  88. }
  89. return list;
  90. }
  91. /* FIXME: Test with reduced features! */
  92. static char *lib_list(const struct manifest *m)
  93. {
  94. unsigned int i, num;
  95. char **libs;
  96. char *ret = talloc_strdup(m, "");
  97. libs = get_libs(m, m->dir, &num,
  98. &m->info_file->compiled[COMPILE_NORMAL]);
  99. for (i = 0; i < num; i++)
  100. ret = talloc_asprintf_append(ret, "-l%s ", libs[i]);
  101. return ret;
  102. }
  103. static bool compile(const void *ctx,
  104. struct manifest *m,
  105. struct ccan_file *file,
  106. bool keep, char **output)
  107. {
  108. file->compiled[COMPILE_NORMAL]
  109. = maybe_temp_file(ctx, "", keep, file->fullname);
  110. if (!compile_and_link(ctx, file->fullname, ccan_dir,
  111. example_obj_list(m, file),
  112. compiler, cflags,
  113. lib_list(m), file->compiled[COMPILE_NORMAL],
  114. output)) {
  115. /* Don't keep failures. */
  116. if (keep)
  117. unlink(file->compiled[COMPILE_NORMAL]);
  118. talloc_free(file->compiled[COMPILE_NORMAL]);
  119. file->compiled[COMPILE_NORMAL] = NULL;
  120. return false;
  121. }
  122. return true;
  123. }
  124. static char *start_main(char *ret, const char *why)
  125. {
  126. return talloc_asprintf_append(ret,
  127. "/* The example %s, so fake function wrapper inserted */\n"
  128. "int main(int argc, char *argv[])\n"
  129. "{\n", why);
  130. }
  131. /* We only handle simple function definitions here. */
  132. static char *add_func(char *others, const char *line)
  133. {
  134. const char *p, *end = strchr(line, '(') - 1;
  135. while (cisspace(*end)) {
  136. end--;
  137. if (end == line)
  138. return others;
  139. }
  140. for (p = end; cisalnum(*p) || *p == '_'; p--) {
  141. if (p == line)
  142. return others;
  143. }
  144. return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
  145. (unsigned)(end - p), p+1);
  146. }
  147. static void strip_leading_whitespace(char **lines)
  148. {
  149. unsigned int i, min_span = -1U;
  150. for (i = 0; lines[i]; i++) {
  151. unsigned int span = strspn(lines[i], " \t");
  152. /* All whitespace? Ignore */
  153. if (!lines[i][span])
  154. continue;
  155. if (span < min_span)
  156. min_span = span;
  157. }
  158. for (i = 0; lines[i]; i++)
  159. if (strlen(lines[i]) >= min_span)
  160. lines[i] += min_span;
  161. }
  162. static bool looks_internal(char **lines, char **why)
  163. {
  164. unsigned int i;
  165. bool last_ended = true; /* Did last line finish a statement? */
  166. for (i = 0; lines[i]; i++) {
  167. /* Skip leading whitespace. */
  168. const char *line = lines[i] + strspn(lines[i], " \t");
  169. unsigned len = strspn(line, IDENT_CHARS);
  170. if (!line[0] || cisspace(line[0]) || strstarts(line, "//"))
  171. continue;
  172. assert(line[strlen(line)-1] != '\n');
  173. /* The winners. */
  174. if (strstarts(line, "if") && len == 2) {
  175. *why = cast_const(char *, "starts with if");
  176. return true;
  177. }
  178. if (strstarts(line, "for") && len == 3) {
  179. *why = cast_const(char *, "starts with for");
  180. return true;
  181. }
  182. if (strstarts(line, "while") && len == 5) {
  183. *why = cast_const(char *, "starts with while");
  184. return true;
  185. }
  186. if (strstarts(line, "do") && len == 2) {
  187. *why = cast_const(char *, "starts with do");
  188. return true;
  189. }
  190. /* The losers. */
  191. if (strstarts(line, "#include")) {
  192. *why = cast_const(char *, "starts with #include");
  193. return false;
  194. }
  195. if (last_ended && strchr(line, '(')) {
  196. if (strstarts(line, "static")) {
  197. *why = cast_const(char *,
  198. "starts with static"
  199. " and contains (");
  200. return false;
  201. }
  202. if (strends(line, ")")) {
  203. *why = cast_const(char *,
  204. "contains ( and ends with )");
  205. return false;
  206. }
  207. }
  208. /* Previously prepended. */
  209. if (strstr(line, "didn't seem to belong inside a function")) {
  210. *why = cast_const(char *, "Comment said so");
  211. return false;
  212. }
  213. /* Single identifier then operator == inside function. */
  214. if (last_ended && len
  215. && cispunct(line[len+strspn(line+len, " ")])) {
  216. *why = cast_const(char *, "starts with identifier"
  217. " then punctuation");
  218. return true;
  219. }
  220. last_ended = (strends(line, "}")
  221. || strends(line, ";")
  222. || strends(line, "*/")
  223. || streq(line, "..."));
  224. }
  225. /* No idea... Say yes? */
  226. *why = cast_const(char *, "gave no clues");
  227. return true;
  228. }
  229. /* Examples will often build on prior ones. Try combining them. */
  230. static char **combine(const void *ctx, char **lines, char **prev)
  231. {
  232. unsigned int i, lines_total, prev_total, count;
  233. char **ret;
  234. const char *reasoning;
  235. char *why = NULL;
  236. if (!prev)
  237. return NULL;
  238. /* If it looks internal, put prev at start. */
  239. if (looks_internal(lines, &why)) {
  240. count = 0;
  241. reasoning = "seemed to belong inside a function";
  242. } else {
  243. /* Try inserting in first elided position */
  244. for (count = 0; lines[count]; count++) {
  245. if (strcmp(lines[count], "...") == 0)
  246. break;
  247. }
  248. if (!lines[count]) {
  249. /* Try at start anyway? */
  250. count = 0;
  251. reasoning = "didn't seem to belong inside"
  252. " a function, so we prepended the previous"
  253. " example";
  254. } else {
  255. reasoning = "didn't seem to belong inside"
  256. " a function, so we put the previous example"
  257. " at the first ...";
  258. count++;
  259. }
  260. }
  261. for (i = 0; lines[i]; i++);
  262. lines_total = i;
  263. for (i = 0; prev[i]; i++);
  264. prev_total = i;
  265. ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
  266. ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */",
  267. why, reasoning);
  268. memcpy(ret+1, lines, count * sizeof(ret[0]));
  269. memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
  270. memcpy(ret+1 + count + prev_total, lines + count,
  271. (lines_total - count + 1) * sizeof(ret[0]));
  272. return ret;
  273. }
  274. /* Only handles very simple comments. */
  275. static char *strip_comment(const void *ctx, const char *orig_line)
  276. {
  277. char *p, *ret = talloc_strdup(ctx, orig_line);
  278. p = strstr(ret, "/*");
  279. if (!p)
  280. p = strstr(ret, "//");
  281. if (p)
  282. *p = '\0';
  283. return ret;
  284. }
  285. static char *mangle(struct manifest *m, char **lines)
  286. {
  287. char *ret, *use_funcs = NULL, *why;
  288. bool in_function = false, fake_function = false, has_main = false;
  289. unsigned int i;
  290. ret = talloc_asprintf(m,
  291. "/* Include header from module. */\n"
  292. "#include <ccan/%s/%s.h>\n"
  293. "/* Prepend a heap of headers. */\n"
  294. "#include <assert.h>\n"
  295. "#include <err.h>\n"
  296. "#include <errno.h>\n"
  297. "#include <fcntl.h>\n"
  298. "#include <limits.h>\n"
  299. "#include <stdbool.h>\n"
  300. "#include <stdint.h>\n"
  301. "#include <stdio.h>\n"
  302. "#include <stdlib.h>\n"
  303. "#include <string.h>\n"
  304. "#include <sys/stat.h>\n"
  305. "#include <sys/types.h>\n"
  306. "#include <unistd.h>\n",
  307. m->basename, m->basename);
  308. ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
  309. "extern int somefunc(void);\n"
  310. "int somefunc(void) { return 0; }\n"
  311. "extern char somestring[];\n"
  312. "char somestring[] = \"hello world\";\n");
  313. if (looks_internal(lines, &why)) {
  314. /* Wrap it all in main(). */
  315. ret = start_main(ret, why);
  316. fake_function = true;
  317. in_function = true;
  318. has_main = true;
  319. } else
  320. ret = talloc_asprintf_append(ret,
  321. "/* The example %s, so didn't wrap in main() */\n",
  322. why);
  323. /* Primitive, very primitive. */
  324. for (i = 0; lines[i]; i++) {
  325. char *line = strip_comment(ret, lines[i]);
  326. /* } at start of line ends a function. */
  327. if (in_function) {
  328. if (line[0] == '}')
  329. in_function = false;
  330. } else {
  331. /* Character at start of line, with ( and no ;
  332. * == function start. Ignore comments. */
  333. if (!cisspace(line[0])
  334. && strchr(line, '(')
  335. && !strchr(line, ';')
  336. && !strstr(line, "//")) {
  337. in_function = true;
  338. if (strncmp(line, "int main", 8) == 0)
  339. has_main = true;
  340. if (strncmp(line, "static", 6) == 0) {
  341. use_funcs = add_func(use_funcs,
  342. line);
  343. }
  344. }
  345. }
  346. /* ... means elided code. */
  347. if (strcmp(line, "...") == 0) {
  348. if (!in_function && !has_main
  349. && looks_internal(lines + i + 1, &why)) {
  350. /* This implies we start a function here. */
  351. ret = start_main(ret, why);
  352. has_main = true;
  353. fake_function = true;
  354. in_function = true;
  355. }
  356. ret = talloc_asprintf_append(ret,
  357. "/* ... removed */\n");
  358. continue;
  359. }
  360. ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
  361. }
  362. if (!has_main) {
  363. ret = talloc_asprintf_append(ret,
  364. "/* Need a main to link successfully. */\n"
  365. "int main(void)\n{\n");
  366. fake_function = true;
  367. }
  368. if (use_funcs) {
  369. ret = talloc_asprintf_append(ret,
  370. "/* Get rid of unused warnings"
  371. " by printing addresses of"
  372. " static funcs. */\n");
  373. if (!fake_function) {
  374. ret = talloc_asprintf_append(ret,
  375. "int use_funcs(void);\n"
  376. "int use_funcs(void) {\n");
  377. fake_function = true;
  378. }
  379. ret = talloc_asprintf_append(ret, " %s\n", use_funcs);
  380. }
  381. if (fake_function)
  382. ret = talloc_asprintf_append(ret, "return 0;\n"
  383. "}\n");
  384. return ret;
  385. }
  386. static struct ccan_file *mangle_example(struct manifest *m,
  387. struct ccan_file *example,
  388. char **lines,
  389. bool keep)
  390. {
  391. char *name, *contents;
  392. int fd;
  393. struct ccan_file *f;
  394. name = maybe_temp_file(example, ".c", keep,
  395. talloc_asprintf(m, "%s/mangled-%s",
  396. m->dir, example->name));
  397. f = new_ccan_file(example,
  398. talloc_dirname(example, name),
  399. talloc_basename(example, name));
  400. talloc_steal(f, name);
  401. fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
  402. if (fd < 0)
  403. return NULL;
  404. contents = mangle(m, lines);
  405. if (write(fd, contents, strlen(contents)) != strlen(contents)) {
  406. close(fd);
  407. return NULL;
  408. }
  409. close(fd);
  410. f->contents = talloc_steal(f, contents);
  411. list_add(&m->mangled_examples, &f->list);
  412. return f;
  413. }
  414. /* If an example has expected output, it's complete and should not be
  415. * included in future examples. */
  416. static bool has_expected_output(char **lines)
  417. {
  418. unsigned int i;
  419. for (i = 0; lines[i]; i++) {
  420. char *p = lines[i] + strspn(lines[i], " \t");
  421. if (!strstarts(p, "//"))
  422. continue;
  423. p += strspn(p, "/ ");
  424. if (strncasecmp(p, "given", strlen("given")) == 0)
  425. return true;
  426. }
  427. return false;
  428. }
  429. static unsigned int try_compiling(struct manifest *m,
  430. struct ccan_file *i,
  431. char **prev,
  432. bool keep,
  433. struct ccan_file *mangled[3],
  434. bool res[3],
  435. char *err[3],
  436. char **lines[3])
  437. {
  438. unsigned int num;
  439. /* Try standalone. */
  440. mangled[0] = i;
  441. res[0] = compile(i, m, mangled[0], keep, &err[0]);
  442. lines[0] = get_ccan_file_lines(i);
  443. if (res[0] && streq(err[0], ""))
  444. return 1;
  445. if (prev) {
  446. lines[1] = combine(i, get_ccan_file_lines(i), prev);
  447. mangled[1] = mangle_example(m, i, lines[1], keep);
  448. res[1] = compile(i, m, mangled[1], keep, &err[1]);
  449. if (res[1] && streq(err[1], "")) {
  450. return 2;
  451. }
  452. num = 2;
  453. } else
  454. num = 1;
  455. /* Try standalone. */
  456. lines[num] = get_ccan_file_lines(i);
  457. mangled[num] = mangle_example(m, i, lines[num], keep);
  458. res[num] = compile(i, m, mangled[num], keep, &err[num]);
  459. return num+1;
  460. }
  461. static void build_examples(struct manifest *m, bool keep,
  462. unsigned int *timeleft, struct score *score)
  463. {
  464. struct ccan_file *i;
  465. char **prev = NULL;
  466. bool warnings = false;
  467. score->total = 0;
  468. score->pass = true;
  469. list_for_each(&m->examples, i, list) {
  470. char *err[3];
  471. struct ccan_file *file[3] = { NULL, NULL, NULL };
  472. bool res[3];
  473. unsigned num, j;
  474. char **lines[3];
  475. const char *error;
  476. score->total++;
  477. /* Simplify our dumb parsing. */
  478. strip_leading_whitespace(get_ccan_file_lines(i));
  479. num = try_compiling(m, i, prev, keep, file, res, err, lines);
  480. /* First look for a compile without any warnings. */
  481. for (j = 0; j < num; j++) {
  482. if (res[j] && streq(err[j], "")) {
  483. if (!has_expected_output(lines[j]))
  484. prev = lines[j];
  485. score->score++;
  486. goto next;
  487. }
  488. }
  489. /* Now accept anything which succeeded. */
  490. for (j = 0; j < num; j++) {
  491. if (res[j]) {
  492. if (!has_expected_output(lines[j]))
  493. prev = lines[j];
  494. score->score++;
  495. warnings = true;
  496. score_file_error(score, file[j], 0,
  497. "Compiling extracted example"
  498. " gave warnings:\n"
  499. "Example:\n"
  500. "%s\n"
  501. "Compiler:\n"
  502. "%s",
  503. get_ccan_file_contents(file[j]),
  504. err[j]);
  505. goto next;
  506. }
  507. }
  508. score->pass = false;
  509. if (!verbose) {
  510. if (num == 3)
  511. error = "Compiling standalone, adding headers, "
  512. "and including previous "
  513. "example all failed";
  514. else
  515. error = "Standalone compile and"
  516. " adding headers both failed";
  517. } else {
  518. if (num == 3) {
  519. error = talloc_asprintf(score,
  520. "Standalone example:\n"
  521. "%s\n"
  522. "Errors: %s\n\n"
  523. "Combining with previous example:\n"
  524. "%s\n"
  525. "Errors: %s\n\n"
  526. "Adding headers, wrappers:\n"
  527. "%s\n"
  528. "Errors: %s\n\n",
  529. get_ccan_file_contents(file[0]),
  530. err[0],
  531. get_ccan_file_contents(file[1]),
  532. err[1],
  533. get_ccan_file_contents(file[2]),
  534. err[2]);
  535. } else {
  536. error = talloc_asprintf(score,
  537. "Standalone example:\n"
  538. "%s\n"
  539. "Errors: %s\n\n"
  540. "Adding headers, wrappers:\n"
  541. "%s\n"
  542. "Errors: %s\n\n",
  543. get_ccan_file_contents(file[0]),
  544. err[0],
  545. get_ccan_file_contents(file[1]),
  546. err[1]);
  547. }
  548. }
  549. score_file_error(score, i, 0, "%s", error);
  550. /* This didn't work, so not a candidate for combining. */
  551. prev = NULL;
  552. next:
  553. ;
  554. }
  555. /* An extra point if they all compiled without warnings. */
  556. if (!list_empty(&m->examples)) {
  557. score->total++;
  558. if (!warnings)
  559. score->score++;
  560. }
  561. }
  562. struct ccanlint examples_compile = {
  563. .key = "examples_compile",
  564. .name = "Module examples compile",
  565. .check = build_examples,
  566. .can_run = can_run,
  567. .needs = "examples_exist module_builds"
  568. };
  569. REGISTER_TEST(examples_compile);