examples_compile.c 15 KB

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