namespacize.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /* Code to move a ccan module into the ccan_ namespace. */
  2. #include <errno.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <fcntl.h>
  12. #include "ccan/str/str.h"
  13. #include "ccan/take/take.h"
  14. #include "ccan/rbuf/rbuf.h"
  15. #include "ccan/tal/path/path.h"
  16. #include "ccan/tal/grab_file/grab_file.h"
  17. #include "ccan/err/err.h"
  18. #include "tools.h"
  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 = tal_arr(NULL, char *, 0), *n;
  43. d = opendir(dir);
  44. if (!d)
  45. return NULL;
  46. while ((ent = readdir(d)) != NULL) {
  47. n = tal_fmt(names, "%s/%s", dir, ent->d_name);
  48. tal_expand(&names, &n, 1);
  49. }
  50. n = NULL;
  51. tal_expand(&names, &n, 1);
  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 = tal(*repl, struct replace);
  79. new->next = *repl;
  80. new->string = tal_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 = tal(*repl, struct replace);
  88. new->next = *repl;
  89. new->string = tal_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 (!cisspace(*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 = tal_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 = tal_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 (cisspace(c)) {
  161. c = ' ';
  162. while (cisspace((*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. tal_append_fmt(&answer, "%c", c);
  172. }
  173. if (c == '}' && seen_brackets && brackets == 0) {
  174. (*p)++;
  175. return answer;
  176. }
  177. }
  178. (*p)++;
  179. if (**p == '\0')
  180. return NULL;
  181. }
  182. }
  183. /* This hack should handle well-formatted code. */
  184. static void look_for_definitions(char *contents, struct replace **repl)
  185. {
  186. char *stmt, *p = contents;
  187. preprocess(contents);
  188. while ((stmt = get_statement(contents, &p)) != NULL) {
  189. int i, len;
  190. /* Definition of struct/union? */
  191. if ((strncmp(stmt, "struct", 5) == 0
  192. || strncmp(stmt, "union", 5) == 0)
  193. && strchr(stmt, '{') && stmt[7] != '{')
  194. add_replace_tok(repl, stmt+7);
  195. /* Definition of var or typedef? */
  196. for (i = strlen(stmt)-1; i >= 0; i--)
  197. if (strspn(stmt+i, IDENT_CHARS) == 0)
  198. break;
  199. if (i != strlen(stmt)-1) {
  200. add_replace_tok(repl, stmt+i+1);
  201. continue;
  202. }
  203. /* function or array declaration? */
  204. len = strspn(stmt, IDENT_CHARS "* ");
  205. if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
  206. if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
  207. for (i = len-1; i >= 0; i--)
  208. if (strspn(stmt+i, IDENT_CHARS) == 0)
  209. break;
  210. if (i != len-1) {
  211. add_replace_tok(repl, stmt+i+1);
  212. continue;
  213. }
  214. } else {
  215. /* Pointer to function? */
  216. len++;
  217. len += strspn(stmt + len, " *");
  218. i = strspn(stmt + len, IDENT_CHARS);
  219. if (i > 0 && stmt[len + i] == ')')
  220. add_replace_tok(repl, stmt+len);
  221. }
  222. }
  223. }
  224. }
  225. /* FIXME: Only does main header, should chase local includes. */
  226. static void analyze_headers(const char *dir, struct replace **repl)
  227. {
  228. char *hdr, *contents;
  229. /* Get hold of header, assume that's it. */
  230. hdr = tal_fmt(dir, "%s.h",
  231. path_join(NULL, dir, take(path_basename(NULL, dir))));
  232. contents = grab_file(dir, hdr);
  233. if (!contents)
  234. err(1, "Reading %s", hdr);
  235. verbose("Looking in %s for macros\n", hdr);
  236. verbose_indent();
  237. look_for_macros(contents, repl);
  238. verbose_unindent();
  239. verbose("Looking in %s for symbols\n", hdr);
  240. verbose_indent();
  241. look_for_definitions(contents, repl);
  242. verbose_unindent();
  243. }
  244. static void write_replacement_file(const char *dir, struct replace **repl)
  245. {
  246. char *replname = path_join(dir, dir, ".namespacize");
  247. int fd;
  248. struct replace *r;
  249. fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
  250. if (fd < 0) {
  251. if (errno == EEXIST)
  252. errx(1, "%s already exists: can't namespacize twice",
  253. replname);
  254. err(1, "Opening %s", replname);
  255. }
  256. for (r = *repl; r; r = r->next) {
  257. if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
  258. || write(fd, "\n", 1) != 1) {
  259. unlink_no_errno(replname);
  260. if (errno == 0)
  261. errx(1, "Short write to %s: disk full?",
  262. replname);
  263. errx(1, "Writing to %s", replname);
  264. }
  265. }
  266. close(fd);
  267. }
  268. static void unlink_destroy(char *name)
  269. {
  270. unlink(name);
  271. }
  272. static char *find_word(char *f, const char *str)
  273. {
  274. char *p = f;
  275. while ((p = strstr(p, str)) != NULL) {
  276. /* Check it's not in the middle of a word. */
  277. if (p > f && (cisalnum(p[-1]) || p[-1] == '_')) {
  278. p++;
  279. continue;
  280. }
  281. if (cisalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
  282. p++;
  283. continue;
  284. }
  285. return p;
  286. }
  287. return NULL;
  288. }
  289. /* This is horribly inefficient but simple. */
  290. static const char *rewrite_file(const char *filename,
  291. const struct replace *repl)
  292. {
  293. char *newname, *file;
  294. int fd;
  295. verbose("Rewriting %s\n", filename);
  296. file = grab_file(filename, filename);
  297. if (!file)
  298. err(1, "Reading file %s", filename);
  299. for (; repl; repl = repl->next) {
  300. char *p;
  301. while ((p = find_word(file, repl->string)) != NULL) {
  302. unsigned int off;
  303. char *new = tal_arr(file, char, strlen(file)+6);
  304. off = p - file;
  305. memcpy(new, file, off);
  306. if (cisupper(repl->string[0]))
  307. memcpy(new + off, "CCAN_", 5);
  308. else
  309. memcpy(new + off, "ccan_", 5);
  310. strcpy(new + off + 5, file + off);
  311. file = new;
  312. }
  313. }
  314. /* If we exit for some reason, we want this erased. */
  315. newname = tal_fmt(autofree(), "%s.tmp", filename);
  316. fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
  317. if (fd < 0)
  318. err(1, "Creating %s", newname);
  319. tal_add_destructor(newname, unlink_destroy);
  320. if (write(fd, file, strlen(file)) != strlen(file)) {
  321. if (errno == 0)
  322. errx(1, "Short write to %s: disk full?", newname);
  323. errx(1, "Writing to %s", newname);
  324. }
  325. close(fd);
  326. return newname;
  327. }
  328. struct adjusted
  329. {
  330. struct adjusted *next;
  331. const char *file;
  332. const char *tmpfile;
  333. };
  334. static void setup_adjust_files(const char *dir,
  335. const struct replace *repl,
  336. struct adjusted **adj)
  337. {
  338. char **files;
  339. for (files = get_dir(dir); *files; files++) {
  340. if (strends(*files, "/test"))
  341. setup_adjust_files(*files, repl, adj);
  342. else if (strends(*files, ".c") || strends(*files, ".h")) {
  343. struct adjusted *a = tal(dir, struct adjusted);
  344. a->next = *adj;
  345. a->file = *files;
  346. a->tmpfile = rewrite_file(a->file, repl);
  347. *adj = a;
  348. }
  349. }
  350. }
  351. /* This is the "commit" stage, so we hope it won't fail. */
  352. static void rename_files(const struct adjusted *adj)
  353. {
  354. while (adj) {
  355. if (!move_file(adj->tmpfile, adj->file))
  356. warn("Could not rename over '%s', we're in trouble",
  357. adj->file);
  358. adj = adj->next;
  359. }
  360. }
  361. static void convert_dir(const char *dir)
  362. {
  363. char *name;
  364. struct replace *replace = NULL;
  365. struct adjusted *adj = NULL;
  366. /* Remove any ugly trailing slashes. */
  367. name = path_canon(NULL, dir);
  368. analyze_headers(name, &replace);
  369. write_replacement_file(name, &replace);
  370. setup_adjust_files(name, replace, &adj);
  371. rename_files(adj);
  372. tal_free(name);
  373. tal_free(replace);
  374. }
  375. static struct replace *read_replacement_file(const char *depdir)
  376. {
  377. struct replace *repl = NULL;
  378. char *replname = path_join(depdir, depdir, ".namespacize");
  379. char *file, **line;
  380. file = grab_file(replname, replname);
  381. if (!file) {
  382. if (errno != ENOENT)
  383. err(1, "Opening %s", replname);
  384. return NULL;
  385. }
  386. for (line = tal_strsplit(file, file, "\n", STR_EMPTY_OK); *line; line++)
  387. add_replace(&repl, *line);
  388. return repl;
  389. }
  390. static void adjust_dir(const char *dir)
  391. {
  392. char *parent = path_dirname(autofree(), dir);
  393. char **deps;
  394. verbose("Adjusting %s\n", dir);
  395. verbose_indent();
  396. for (deps = get_deps(parent, dir, "depends", false, compile_info);
  397. *deps;
  398. deps++) {
  399. char *depdir;
  400. struct adjusted *adj = NULL;
  401. struct replace *repl;
  402. depdir = path_join(parent, parent, *deps);
  403. repl = read_replacement_file(depdir);
  404. if (repl) {
  405. verbose("%s has been namespacized\n", depdir);
  406. setup_adjust_files(parent, repl, &adj);
  407. rename_files(adj);
  408. } else
  409. verbose("%s has not been namespacized\n", depdir);
  410. tal_free(depdir);
  411. }
  412. verbose_unindent();
  413. tal_free(parent);
  414. }
  415. static void adjust_dependents(const char *dir)
  416. {
  417. char *parent = path_dirname(NULL, dir);
  418. char *base = path_basename(parent, dir);
  419. char **file;
  420. verbose("Looking for dependents in %s\n", parent);
  421. verbose_indent();
  422. for (file = get_dir(parent); *file; file++) {
  423. char *info, **deps;
  424. bool isdep = false;
  425. if (path_basename(*file, *file)[0] == '.')
  426. continue;
  427. info = path_join(*file, *file, "_info");
  428. if (access(info, R_OK) != 0)
  429. continue;
  430. for (deps = get_deps(*file, *file, "depends", false,
  431. compile_info);
  432. *deps; deps++) {
  433. if (!strstarts(*deps, "ccan/"))
  434. continue;
  435. if (streq(*deps + strlen("ccan/"), base))
  436. isdep = true;
  437. }
  438. if (isdep)
  439. adjust_dir(*file);
  440. else
  441. verbose("%s is not dependent\n", *file);
  442. }
  443. verbose_unindent();
  444. }
  445. int main(int argc, char *argv[])
  446. {
  447. if (argv[1] && streq(argv[1], "--verbose")) {
  448. verbose = true;
  449. argv++;
  450. argc--;
  451. }
  452. if (argc == 2) {
  453. verbose("Namespacizing %s\n", argv[1]);
  454. verbose_indent();
  455. convert_dir(argv[1]);
  456. adjust_dependents(argv[1]);
  457. verbose_unindent();
  458. return 0;
  459. }
  460. if (argc > 2 && streq(argv[1], "--adjust")) {
  461. unsigned int i;
  462. for (i = 2; i < argc; i++)
  463. adjust_dir(argv[i]);
  464. return 0;
  465. }
  466. usage();
  467. }