namespacize.c 12 KB

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