namespacize.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /* Code to move a ccan module into the ccan_ namespace. */
  2. #include <err.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <stdbool.h>
  6. #include <ctype.h>
  7. #include <sys/types.h>
  8. #include <dirent.h>
  9. #include <unistd.h>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <fcntl.h>
  13. #include "talloc/talloc.h"
  14. #include "tools.h"
  15. #define IDENT_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
  16. "abcdefghijklmnopqrstuvwxyz" \
  17. "01234567889_"
  18. static bool verbose = false;
  19. static int indent = 0;
  20. #define verbose(args...) \
  21. do { if (verbose) { \
  22. unsigned int _i; \
  23. for (_i = 0; _i < indent; _i++) printf(" "); \
  24. printf(args); \
  25. } \
  26. } while(0)
  27. #define verbose_indent() (indent += 2)
  28. #define verbose_unindent() (indent -= 2)
  29. #define strstarts(str,prefix) (strncmp((str),(prefix),strlen(prefix)) == 0)
  30. static inline bool strends(const char *str, const char *postfix)
  31. {
  32. if (strlen(str) < strlen(postfix))
  33. return false;
  34. return streq(str + strlen(str) - strlen(postfix), postfix);
  35. }
  36. static int unlink_no_errno(const char *filename)
  37. {
  38. int ret = 0, serrno = errno;
  39. if (unlink(filename) < 0)
  40. ret = errno;
  41. errno = serrno;
  42. return ret;
  43. }
  44. static char **get_dir(const char *dir)
  45. {
  46. DIR *d;
  47. struct dirent *ent;
  48. char **names = NULL;
  49. unsigned int size = 0;
  50. d = opendir(dir);
  51. if (!d)
  52. return NULL;
  53. while ((ent = readdir(d)) != NULL) {
  54. names = talloc_realloc(dir, names, char *, size + 2);
  55. names[size++]
  56. = talloc_asprintf(names, "%s/%s", dir, ent->d_name);
  57. }
  58. names[size++] = NULL;
  59. closedir(d);
  60. return names;
  61. }
  62. struct replace
  63. {
  64. struct replace *next;
  65. char *string;
  66. };
  67. static void __attribute__((noreturn)) usage(void)
  68. {
  69. errx(1, "Usage:\n"
  70. "namespacize [--verbose] <dir>\n"
  71. "namespacize [--verbose] --adjust <dir>...\n"
  72. "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
  73. "then adjusts any other ccan directories at the same level which\n"
  74. "are effected.\n"
  75. "--adjust does an adjustment for each directory, in case a\n"
  76. "dependency has been namespacized\n");
  77. }
  78. static void add_replace(struct replace **repl, const char *str)
  79. {
  80. struct replace *new, *i;
  81. /* Avoid duplicates. */
  82. for (i = *repl; i; i = i->next)
  83. if (streq(i->string, str))
  84. return;
  85. new = talloc(*repl, struct replace);
  86. new->next = *repl;
  87. new->string = talloc_strdup(new, str);
  88. *repl = new;
  89. }
  90. static void add_replace_tok(struct replace **repl, const char *s)
  91. {
  92. struct replace *new;
  93. unsigned int len = strspn(s, IDENT_CHARS);
  94. new = talloc(*repl, struct replace);
  95. new->next = *repl;
  96. new->string = talloc_strndup(new, s, len);
  97. *repl = new;
  98. }
  99. static char *basename(const void *ctx, const char *dir)
  100. {
  101. char *p = strrchr(dir, '/');
  102. if (!p)
  103. return (char *)dir;
  104. return talloc_strdup(ctx, p+1);
  105. }
  106. static void look_for_macros(char *contents, struct replace **repl)
  107. {
  108. char *p;
  109. enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
  110. /* Look for lines of form #define X */
  111. for (p = contents; *p; p++) {
  112. if (*p == '\n')
  113. state = LINESTART;
  114. else if (!isspace(*p)) {
  115. if (state == LINESTART && *p == '#')
  116. state = HASH;
  117. else if (state==HASH && !strncmp(p, "define", 6)) {
  118. state = DEFINE;
  119. p += 5;
  120. } else if (state == DEFINE) {
  121. unsigned int len;
  122. len = strspn(p, IDENT_CHARS);
  123. if (len) {
  124. char *s;
  125. s = talloc_strndup(contents, p, len);
  126. /* Don't wrap idempotent wrappers */
  127. if (!strstarts(s, "CCAN_")) {
  128. verbose("Found %s\n", s);
  129. add_replace(repl, s);
  130. }
  131. }
  132. state = NONE;
  133. } else
  134. state = NONE;
  135. }
  136. }
  137. }
  138. /* Blank out preprocessor lines, and eliminate \ */
  139. static void preprocess(char *p)
  140. {
  141. char *s;
  142. /* We assume backslashes are only used for macros. */
  143. while ((s = strstr(p, "\\\n")) != NULL)
  144. s[0] = s[1] = ' ';
  145. /* Now eliminate # lines. */
  146. if (p[0] == '#') {
  147. unsigned int i;
  148. for (i = 0; p[i] != '\n'; i++)
  149. p[i] = ' ';
  150. }
  151. while ((s = strstr(p, "\n#")) != NULL) {
  152. unsigned int i;
  153. for (i = 1; s[i] != '\n'; i++)
  154. s[i] = ' ';
  155. }
  156. }
  157. static char *get_statement(const void *ctx, char **p)
  158. {
  159. unsigned brackets = 0;
  160. bool seen_brackets = false;
  161. char *answer = talloc_strdup(ctx, "");
  162. for (;;) {
  163. if ((*p)[0] == '/' && (*p)[1] == '/')
  164. *p += strcspn(*p, "\n");
  165. else if ((*p)[0] == '/' && (*p)[1] == '*')
  166. *p = strstr(*p, "*/") + 1;
  167. else {
  168. char c = **p;
  169. if (c == ';' && !brackets) {
  170. (*p)++;
  171. return answer;
  172. }
  173. /* Compress whitespace into a single ' ' */
  174. if (isspace(c)) {
  175. c = ' ';
  176. while (isspace((*p)[1]))
  177. (*p)++;
  178. } else if (c == '{' || c == '(' || c == '[') {
  179. if (c == '(')
  180. seen_brackets = true;
  181. brackets++;
  182. } else if (c == '}' || c == ')' || c == ']')
  183. brackets--;
  184. if (answer[0] != '\0' || c != ' ') {
  185. answer = talloc_realloc(NULL, answer, char,
  186. strlen(answer) + 2);
  187. answer[strlen(answer)+1] = '\0';
  188. answer[strlen(answer)] = c;
  189. }
  190. if (c == '}' && seen_brackets && brackets == 0) {
  191. (*p)++;
  192. return answer;
  193. }
  194. }
  195. (*p)++;
  196. if (**p == '\0')
  197. return NULL;
  198. }
  199. }
  200. /* This hack should handle well-formatted code. */
  201. static void look_for_definitions(char *contents, struct replace **repl)
  202. {
  203. char *stmt, *p = contents;
  204. preprocess(contents);
  205. while ((stmt = get_statement(contents, &p)) != NULL) {
  206. int i, len;
  207. /* Definition of struct/union? */
  208. if ((strncmp(stmt, "struct", 5) == 0
  209. || strncmp(stmt, "union", 5) == 0)
  210. && strchr(stmt, '{') && stmt[7] != '{')
  211. add_replace_tok(repl, stmt+7);
  212. /* Definition of var or typedef? */
  213. for (i = strlen(stmt)-1; i >= 0; i--)
  214. if (strspn(stmt+i, IDENT_CHARS) == 0)
  215. break;
  216. if (i != strlen(stmt)-1) {
  217. add_replace_tok(repl, stmt+i+1);
  218. continue;
  219. }
  220. /* function or array declaration? */
  221. len = strspn(stmt, IDENT_CHARS "* ");
  222. if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
  223. if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
  224. for (i = len-1; i >= 0; i--)
  225. if (strspn(stmt+i, IDENT_CHARS) == 0)
  226. break;
  227. if (i != len-1) {
  228. add_replace_tok(repl, stmt+i+1);
  229. continue;
  230. }
  231. } else {
  232. /* Pointer to function? */
  233. len++;
  234. len += strspn(stmt + len, " *");
  235. i = strspn(stmt + len, IDENT_CHARS);
  236. if (i > 0 && stmt[len + i] == ')')
  237. add_replace_tok(repl, stmt+len);
  238. }
  239. }
  240. }
  241. }
  242. /* FIXME: Only does main header, should chase local includes. */
  243. static void analyze_headers(const char *dir, struct replace **repl)
  244. {
  245. char *hdr, *contents;
  246. /* Get hold of header, assume that's it. */
  247. hdr = talloc_asprintf(dir, "%s/%s.h", dir, basename(dir, dir));
  248. contents = grab_file(dir, hdr);
  249. if (!contents)
  250. err(1, "Reading %s", hdr);
  251. verbose("Looking in %s for macros\n", hdr);
  252. verbose_indent();
  253. look_for_macros(contents, repl);
  254. verbose_unindent();
  255. verbose("Looking in %s for symbols\n", hdr);
  256. verbose_indent();
  257. look_for_definitions(contents, repl);
  258. verbose_unindent();
  259. }
  260. static void write_replacement_file(const char *dir, struct replace **repl)
  261. {
  262. char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
  263. int fd;
  264. struct replace *r;
  265. fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
  266. if (fd < 0) {
  267. if (errno == EEXIST)
  268. errx(1, "%s already exists: can't namespacize twice",
  269. replname);
  270. err(1, "Opening %s", replname);
  271. }
  272. for (r = *repl; r; r = r->next) {
  273. if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
  274. || write(fd, "\n", 1) != 1) {
  275. unlink_no_errno(replname);
  276. if (errno == 0)
  277. errx(1, "Short write to %s: disk full?",
  278. replname);
  279. errx(1, "Writing to %s", replname);
  280. }
  281. }
  282. close(fd);
  283. }
  284. static int unlink_destroy(char *name)
  285. {
  286. unlink(name);
  287. return 0;
  288. }
  289. static char *find_word(char *f, const char *str)
  290. {
  291. char *p = f;
  292. while ((p = strstr(p, str)) != NULL) {
  293. /* Check it's not in the middle of a word. */
  294. if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
  295. p++;
  296. continue;
  297. }
  298. if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
  299. p++;
  300. continue;
  301. }
  302. return p;
  303. }
  304. return NULL;
  305. }
  306. /* This is horribly inefficient but simple. */
  307. static const char *rewrite_file(const char *filename,
  308. const struct replace *repl)
  309. {
  310. char *newname, *file;
  311. int fd;
  312. verbose("Rewriting %s\n", filename);
  313. file = grab_file(filename, filename);
  314. if (!file)
  315. err(1, "Reading file %s", filename);
  316. for (; repl; repl = repl->next) {
  317. char *p;
  318. while ((p = find_word(file, repl->string)) != NULL) {
  319. unsigned int off;
  320. char *new = talloc_array(file, char, strlen(file)+6);
  321. off = p - file;
  322. memcpy(new, file, off);
  323. if (isupper(repl->string[0]))
  324. memcpy(new + off, "CCAN_", 5);
  325. else
  326. memcpy(new + off, "ccan_", 5);
  327. strcpy(new + off + 5, file + off);
  328. file = new;
  329. }
  330. }
  331. /* If we exit for some reason, we want this erased. */
  332. newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
  333. filename);
  334. fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
  335. if (fd < 0)
  336. err(1, "Creating %s", newname);
  337. talloc_set_destructor(newname, unlink_destroy);
  338. if (write(fd, file, strlen(file)) != strlen(file)) {
  339. if (errno == 0)
  340. errx(1, "Short write to %s: disk full?", newname);
  341. errx(1, "Writing to %s", newname);
  342. }
  343. close(fd);
  344. return newname;
  345. }
  346. struct adjusted
  347. {
  348. struct adjusted *next;
  349. const char *file;
  350. const char *tmpfile;
  351. };
  352. static void setup_adjust_files(const char *dir,
  353. const struct replace *repl,
  354. struct adjusted **adj)
  355. {
  356. char **files;
  357. for (files = get_dir(dir); *files; files++) {
  358. if (strends(*files, "/test"))
  359. setup_adjust_files(*files, repl, adj);
  360. else if (strends(*files, ".c") || strends(*files, ".h")) {
  361. struct adjusted *a = talloc(dir, struct adjusted);
  362. a->next = *adj;
  363. a->file = *files;
  364. a->tmpfile = rewrite_file(a->file, repl);
  365. *adj = a;
  366. }
  367. }
  368. }
  369. /* This is the "commit" stage, so we hope it won't fail. */
  370. static void rename_files(const struct adjusted *adj)
  371. {
  372. while (adj) {
  373. if (rename(adj->tmpfile, adj->file) != 0)
  374. warn("Could not rename over '%s', we're in trouble",
  375. adj->file);
  376. adj = adj->next;
  377. }
  378. }
  379. static void convert_dir(const char *dir)
  380. {
  381. char *name;
  382. struct replace *replace = NULL;
  383. struct adjusted *adj = NULL;
  384. /* Remove any ugly trailing slashes. */
  385. name = talloc_strdup(NULL, dir);
  386. while (strends(name, "/"))
  387. name[strlen(name)-1] = '\0';
  388. analyze_headers(name, &replace);
  389. write_replacement_file(name, &replace);
  390. setup_adjust_files(name, replace, &adj);
  391. rename_files(adj);
  392. talloc_free(name);
  393. talloc_free(replace);
  394. }
  395. static struct replace *read_replacement_file(const char *depdir)
  396. {
  397. struct replace *repl = NULL;
  398. char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
  399. char *file, **line;
  400. file = grab_file(replname, replname);
  401. if (!file) {
  402. if (errno != ENOENT)
  403. err(1, "Opening %s", replname);
  404. return NULL;
  405. }
  406. for (line = split(file, file, "\n", NULL); *line; line++)
  407. add_replace(&repl, *line);
  408. return repl;
  409. }
  410. static char *parent_dir(const void *ctx, const char *dir)
  411. {
  412. char *parent, *slash;
  413. parent = talloc_strdup(ctx, dir);
  414. slash = strrchr(parent, '/');
  415. if (slash)
  416. *slash = '\0';
  417. else
  418. parent = talloc_strdup(ctx, ".");
  419. return parent;
  420. }
  421. static void adjust_dir(const char *dir)
  422. {
  423. char *parent = parent_dir(NULL, dir);
  424. char **deps;
  425. verbose("Adjusting %s\n", dir);
  426. verbose_indent();
  427. for (deps = get_deps(parent, dir); *deps; deps++) {
  428. char *depdir;
  429. struct adjusted *adj = NULL;
  430. struct replace *repl;
  431. depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
  432. repl = read_replacement_file(depdir);
  433. if (repl) {
  434. verbose("%s has been namespacized\n", depdir);
  435. setup_adjust_files(parent, repl, &adj);
  436. rename_files(adj);
  437. } else
  438. verbose("%s has not been namespacized\n", depdir);
  439. talloc_free(depdir);
  440. }
  441. verbose_unindent();
  442. }
  443. static void adjust_dependents(const char *dir)
  444. {
  445. char *parent = parent_dir(NULL, dir);
  446. char *base = basename(parent, dir);
  447. char **file;
  448. verbose("Looking for dependents in %s\n", parent);
  449. verbose_indent();
  450. for (file = get_dir(parent); *file; file++) {
  451. char *infoc, **deps;
  452. bool isdep = false;
  453. if (basename(*file, *file)[0] == '.')
  454. continue;
  455. infoc = talloc_asprintf(*file, "%s/_info.c", *file);
  456. if (access(infoc, R_OK) != 0)
  457. continue;
  458. for (deps = get_deps(*file, *file); *deps; deps++) {
  459. if (streq(*deps, base))
  460. isdep = true;
  461. }
  462. if (isdep)
  463. adjust_dir(*file);
  464. else
  465. verbose("%s is not dependent\n", *file);
  466. }
  467. verbose_unindent();
  468. }
  469. int main(int argc, char *argv[])
  470. {
  471. if (argv[1] && streq(argv[1], "--verbose")) {
  472. verbose = true;
  473. argv++;
  474. argc--;
  475. }
  476. if (argc == 2) {
  477. verbose("Namespacizing %s\n", argv[1]);
  478. verbose_indent();
  479. convert_dir(argv[1]);
  480. adjust_dependents(argv[1]);
  481. verbose_unindent();
  482. return 0;
  483. }
  484. if (argc > 2 && streq(argv[1], "--adjust")) {
  485. unsigned int i;
  486. for (i = 2; i < argc; i++)
  487. adjust_dir(argv[i]);
  488. return 0;
  489. }
  490. usage();
  491. }