namespacize.c 12 KB

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