examples_compile.c 15 KB

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