examples_compile.c 16 KB

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