examples_compile.c 15 KB

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