examples_compile.c 15 KB

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