examples_compile.c 15 KB

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