namespacize.c 12 KB

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