namespacize.c 12 KB

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