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