examples_compile.c 16 KB

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