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