patch_toybox.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /* Adapted from toybox's patch. Currently unused */
  2. /* vi: set sw=4 ts=4:
  3. *
  4. * patch.c - Apply a "universal" diff.
  5. *
  6. * Copyright 2007 Rob Landley <rob@landley.net>
  7. *
  8. * see http://www.opengroup.org/onlinepubs/009695399/utilities/patch.html
  9. * (But only does -u, because who still cares about "ed"?)
  10. *
  11. * TODO:
  12. * -b backup
  13. * -l treat all whitespace as a single space
  14. * -N ignore already applied
  15. * -d chdir first
  16. * -D define wrap #ifdef and #ifndef around changes
  17. * -o outfile output here instead of in place
  18. * -r rejectfile write rejected hunks to this file
  19. *
  20. * -E remove empty files --remove-empty-files
  21. * -f force (no questions asked)
  22. * -F fuzz (number, default 2)
  23. * [file] which file to patch
  24. USE_PATCH(NEWTOY(patch, "up#i:R", TOYFLAG_USR|TOYFLAG_BIN))
  25. config PATCH
  26. bool "patch"
  27. default y
  28. help
  29. usage: patch [-i file] [-p depth] [-Ru]
  30. Apply a unified diff to one or more files.
  31. -i Input file (defaults=stdin)
  32. -p number of '/' to strip from start of file paths (default=all)
  33. -R Reverse patch.
  34. -u Ignored (only handles "unified" diffs)
  35. This version of patch only handles unified diffs, and only modifies
  36. a file when all all hunks to that file apply. Patch prints failed
  37. hunks to stderr, and exits with nonzero status if any hunks fail.
  38. A file compared against /dev/null (or with a date <= the epoch) is
  39. created/deleted as appropriate.
  40. */
  41. #include "libbb.h"
  42. struct double_list {
  43. struct double_list *next;
  44. struct double_list *prev;
  45. char *data;
  46. };
  47. // Return the first item from the list, advancing the list (which must be called
  48. // as &list)
  49. static
  50. void *TOY_llist_pop(void *list)
  51. {
  52. // I'd use a void ** for the argument, and even accept the typecast in all
  53. // callers as documentation you need the &, except the stupid compiler
  54. // would then scream about type-punned pointers. Screw it.
  55. void **llist = (void **)list;
  56. void **next = (void **)*llist;
  57. *llist = *next;
  58. return (void *)next;
  59. }
  60. // Free all the elements of a linked list
  61. // if freeit!=NULL call freeit() on each element before freeing it.
  62. static
  63. void TOY_llist_free(void *list, void (*freeit)(void *data))
  64. {
  65. while (list) {
  66. void *pop = TOY_llist_pop(&list);
  67. if (freeit) freeit(pop);
  68. else free(pop);
  69. // End doubly linked list too.
  70. if (list==pop) break;
  71. }
  72. }
  73. // Add an entry to the end off a doubly linked list
  74. static
  75. struct double_list *dlist_add(struct double_list **list, char *data)
  76. {
  77. struct double_list *line = xmalloc(sizeof(struct double_list));
  78. line->data = data;
  79. if (*list) {
  80. line->next = *list;
  81. line->prev = (*list)->prev;
  82. (*list)->prev->next = line;
  83. (*list)->prev = line;
  84. } else *list = line->next = line->prev = line;
  85. return line;
  86. }
  87. // Ensure entire path exists.
  88. // If mode != -1 set permissions on newly created dirs.
  89. // Requires that path string be writable (for temporary null terminators).
  90. static
  91. void xmkpath(char *path, int mode)
  92. {
  93. char *p, old;
  94. mode_t mask;
  95. int rc;
  96. struct stat st;
  97. for (p = path; ; p++) {
  98. if (!*p || *p == '/') {
  99. old = *p;
  100. *p = rc = 0;
  101. if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
  102. if (mode != -1) {
  103. mask = umask(0);
  104. rc = mkdir(path, mode);
  105. umask(mask);
  106. } else rc = mkdir(path, 0777);
  107. }
  108. *p = old;
  109. if(rc) bb_perror_msg_and_die("mkpath '%s'", path);
  110. }
  111. if (!*p) break;
  112. }
  113. }
  114. // Slow, but small.
  115. static
  116. char *get_rawline(int fd, long *plen, char end)
  117. {
  118. char c, *buf = NULL;
  119. long len = 0;
  120. for (;;) {
  121. if (1>read(fd, &c, 1)) break;
  122. if (!(len & 63)) buf=xrealloc(buf, len+65);
  123. if ((buf[len++]=c) == end) break;
  124. }
  125. if (buf) buf[len]=0;
  126. if (plen) *plen = len;
  127. return buf;
  128. }
  129. static
  130. char *get_line(int fd)
  131. {
  132. long len;
  133. char *buf = get_rawline(fd, &len, '\n');
  134. if (buf && buf[--len]=='\n') buf[len]=0;
  135. return buf;
  136. }
  137. // Copy the rest of in to out and close both files.
  138. static
  139. void xsendfile(int in, int out)
  140. {
  141. long len;
  142. char buf[4096];
  143. if (in<0) return;
  144. for (;;) {
  145. len = safe_read(in, buf, 4096);
  146. if (len<1) break;
  147. xwrite(out, buf, len);
  148. }
  149. }
  150. // Copy the rest of the data and replace the original with the copy.
  151. static
  152. void replace_tempfile(int fdin, int fdout, char **tempname)
  153. {
  154. char *temp = xstrdup(*tempname);
  155. temp[strlen(temp)-6]=0;
  156. if (fdin != -1) {
  157. xsendfile(fdin, fdout);
  158. xclose(fdin);
  159. }
  160. xclose(fdout);
  161. rename(*tempname, temp);
  162. free(*tempname);
  163. free(temp);
  164. *tempname = NULL;
  165. }
  166. // Open a temporary file to copy an existing file into.
  167. static
  168. int copy_tempfile(int fdin, char *name, char **tempname)
  169. {
  170. struct stat statbuf;
  171. int fd;
  172. *tempname = xasprintf("%sXXXXXX", name);
  173. fd = mkstemp(*tempname);
  174. if(-1 == fd) bb_perror_msg_and_die("no temp file");
  175. // Set permissions of output file
  176. fstat(fdin, &statbuf);
  177. fchmod(fd, statbuf.st_mode);
  178. return fd;
  179. }
  180. // Abort the copy and delete the temporary file.
  181. static
  182. void delete_tempfile(int fdin, int fdout, char **tempname)
  183. {
  184. close(fdin);
  185. close(fdout);
  186. unlink(*tempname);
  187. free(*tempname);
  188. *tempname = NULL;
  189. }
  190. struct globals {
  191. struct double_list *plines;
  192. long linenum;
  193. int context;
  194. int hunknum;
  195. int filein;
  196. int fileout;
  197. int state;
  198. char *tempname;
  199. smallint exitval;
  200. };
  201. #define TT (*ptr_to_globals)
  202. #define INIT_TT() do { \
  203. SET_PTR_TO_GLOBALS(xzalloc(sizeof(TT))); \
  204. } while (0)
  205. //bbox had: "p:i:RN"
  206. #define FLAG_STR "Rup:i:"
  207. /* FLAG_REVERSE must be == 1! Code uses this fact. */
  208. #define FLAG_REVERSE (1 << 0)
  209. #define FLAG_u (1 << 1)
  210. #define FLAG_PATHLEN (1 << 2)
  211. #define FLAG_INPUT (1 << 3)
  212. // Dispose of a line of input, either by writing it out or discarding it.
  213. // state < 2: just free
  214. // state = 2: write whole line to stderr
  215. // state = 3: write whole line to fileout
  216. // state > 3: write line+1 to fileout when *line != state
  217. static void do_line(void *data)
  218. {
  219. struct double_list *dlist = (struct double_list *)data;
  220. if (TT.state>1 && *dlist->data != TT.state)
  221. fdprintf(TT.state == 2 ? 2 : TT.fileout,
  222. "%s\n", dlist->data+(TT.state>3 ? 1 : 0));
  223. free(dlist->data);
  224. free(data);
  225. }
  226. static void finish_oldfile(void)
  227. {
  228. if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
  229. TT.fileout = TT.filein = -1;
  230. }
  231. static void fail_hunk(void)
  232. {
  233. if (!TT.plines) return;
  234. TT.plines->prev->next = 0;
  235. fdprintf(2, "Hunk %d FAILED.\n", TT.hunknum);
  236. TT.exitval = 1;
  237. // If we got to this point, we've seeked to the end. Discard changes to
  238. // this file and advance to next file.
  239. TT.state = 2;
  240. TOY_llist_free(TT.plines, do_line);
  241. TT.plines = NULL;
  242. delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
  243. TT.state = 0;
  244. }
  245. static int apply_hunk(void)
  246. {
  247. struct double_list *plist, *buf = NULL, *check;
  248. int i = 0, backwards = 0, matcheof = 0,
  249. reverse = option_mask32 & FLAG_REVERSE;
  250. // Break doubly linked list so we can use singly linked traversal function.
  251. TT.plines->prev->next = NULL;
  252. // Match EOF if there aren't as many ending context lines as beginning
  253. for (plist = TT.plines; plist; plist = plist->next) {
  254. if (plist->data[0]==' ') i++;
  255. else i = 0;
  256. }
  257. if (i < TT.context) matcheof++;
  258. // Search for a place to apply this hunk. Match all context lines and
  259. // lines to be removed.
  260. plist = TT.plines;
  261. buf = NULL;
  262. i = 0;
  263. // Start of for loop
  264. if (TT.context) for (;;) {
  265. char *data = get_line(TT.filein);
  266. TT.linenum++;
  267. // Skip lines of the hunk we'd be adding.
  268. while (plist && *plist->data == "+-"[reverse]) {
  269. if (data && !strcmp(data, plist->data+1)) {
  270. if (++backwards == TT.context)
  271. fdprintf(2,"Possibly reversed hunk %d at %ld\n",
  272. TT.hunknum, TT.linenum);
  273. } else backwards=0;
  274. plist = plist->next;
  275. }
  276. // Is this EOF?
  277. if (!data) {
  278. // Does this hunk need to match EOF?
  279. if (!plist && matcheof) break;
  280. // File ended before we found a place for this hunk.
  281. fail_hunk();
  282. goto done;
  283. }
  284. check = dlist_add(&buf, data);
  285. // todo: teach the strcmp() to ignore whitespace.
  286. for (;;) {
  287. // If we hit the end of a hunk that needed EOF and this isn't EOF,
  288. // or next line doesn't match, flush first line of buffered data and
  289. // recheck match until we find a new match or run out of buffer.
  290. if (!plist || strcmp(check->data, plist->data+1)) {
  291. // First line isn't a match, write it out.
  292. TT.state = 3;
  293. check = TOY_llist_pop(&buf);
  294. check->prev->next = buf;
  295. buf->prev = check->prev;
  296. do_line(check);
  297. plist = TT.plines;
  298. // Out of buffered lines?
  299. if (check==buf) {
  300. buf = 0;
  301. break;
  302. }
  303. check = buf;
  304. } else {
  305. // This line matches. Advance plist, detect successful match.
  306. plist = plist->next;
  307. if (!plist && !matcheof) goto out;
  308. check = check->next;
  309. if (check == buf) break;
  310. }
  311. }
  312. }
  313. out:
  314. // Got it. Emit changed data.
  315. TT.state = "-+"[reverse];
  316. TOY_llist_free(TT.plines, do_line);
  317. TT.plines = NULL;
  318. TT.state = 1;
  319. done:
  320. if (buf) {
  321. buf->prev->next = NULL;
  322. TOY_llist_free(buf, do_line);
  323. }
  324. return TT.state;
  325. }
  326. // state 0: Not in a hunk, look for +++.
  327. // state 1: Found +++ file indicator, look for @@
  328. // state 2: In hunk: counting initial context lines
  329. // state 3: In hunk: getting body
  330. int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  331. int patch_main(int argc UNUSED_PARAM, char **argv)
  332. {
  333. int opts;
  334. int reverse, state = 0;
  335. char *oldname = NULL, *newname = NULL;
  336. char *opt_p, *opt_i;
  337. int prefix;
  338. long oldline = 0, oldlen = 0, newline = 0, newlen = 0;
  339. INIT_TT();
  340. opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i);
  341. reverse = opts & FLAG_REVERSE;
  342. if (opts & FLAG_INPUT) xmove_fd(xopen(opt_i, O_RDONLY), STDIN_FILENO);
  343. prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative!
  344. TT.filein = TT.fileout = -1;
  345. // Loop through the lines in the patch
  346. for(;;) {
  347. char *patchline;
  348. patchline = get_line(STDIN_FILENO);
  349. if (!patchline) break;
  350. // Other versions of patch accept damaged patches,
  351. // so we need to also.
  352. if (!*patchline) {
  353. free(patchline);
  354. patchline = xstrdup(" ");
  355. }
  356. // Are we assembling a hunk?
  357. if (state >= 2) {
  358. if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
  359. dlist_add(&TT.plines, patchline);
  360. if (*patchline != '+') oldlen--;
  361. if (*patchline != '-') newlen--;
  362. // Context line?
  363. if (*patchline==' ' && state==2) TT.context++;
  364. else state=3;
  365. // If we've consumed all expected hunk lines, apply the hunk.
  366. if (!oldlen && !newlen) state = apply_hunk();
  367. continue;
  368. }
  369. fail_hunk();
  370. state = 0;
  371. continue;
  372. }
  373. // Open a new file?
  374. if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
  375. char *s, **name = &oldname;
  376. int i;
  377. if (*patchline == '+') {
  378. name = &newname;
  379. state = 1;
  380. }
  381. free(*name);
  382. finish_oldfile();
  383. // Trim date from end of filename (if any). We don't care.
  384. for (s = patchline+4; *s && *s!='\t'; s++)
  385. if (*s=='\\' && s[1]) s++;
  386. i = atoi(s);
  387. if (i && i<=1970)
  388. *name = xstrdup("/dev/null");
  389. else {
  390. *s = 0;
  391. *name = xstrdup(patchline+4);
  392. }
  393. // We defer actually opening the file because svn produces broken
  394. // patches that don't signal they want to create a new file the
  395. // way the patch man page says, so you have to read the first hunk
  396. // and _guess_.
  397. // Start a new hunk?
  398. } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
  399. int i;
  400. i = sscanf(patchline+4, "%ld,%ld +%ld,%ld",
  401. &oldline, &oldlen, &newline, &newlen);
  402. if (i != 4)
  403. bb_error_msg_and_die("corrupt hunk %d at %ld", TT.hunknum, TT.linenum);
  404. TT.context = 0;
  405. state = 2;
  406. // If this is the first hunk, open the file.
  407. if (TT.filein == -1) {
  408. int oldsum, newsum, del = 0;
  409. char *s, *name;
  410. oldsum = oldline + oldlen;
  411. newsum = newline + newlen;
  412. name = reverse ? oldname : newname;
  413. // We're deleting oldname if new file is /dev/null (before -p)
  414. // or if new hunk is empty (zero context) after patching
  415. if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum)) {
  416. name = reverse ? newname : oldname;
  417. del++;
  418. }
  419. // handle -p path truncation.
  420. for (i=0, s = name; *s;) {
  421. if ((option_mask32 & FLAG_PATHLEN) && prefix == i)
  422. break;
  423. if (*(s++)=='/') {
  424. name = s;
  425. i++;
  426. }
  427. }
  428. if (del) {
  429. printf("removing %s\n", name);
  430. xunlink(name);
  431. state = 0;
  432. // If we've got a file to open, do so.
  433. } else if (!(option_mask32 & FLAG_PATHLEN) || i <= prefix) {
  434. // If the old file was null, we're creating a new one.
  435. if (!strcmp(oldname, "/dev/null") || !oldsum) {
  436. printf("creating %s\n", name);
  437. s = strrchr(name, '/');
  438. if (s) {
  439. *s = 0;
  440. xmkpath(name, -1);
  441. *s = '/';
  442. }
  443. TT.filein = xopen3(name, O_CREAT|O_EXCL|O_RDWR, 0666);
  444. } else {
  445. printf("patching file %s\n", name);
  446. TT.filein = xopen(name, O_RDWR);
  447. }
  448. TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
  449. TT.linenum = 0;
  450. TT.hunknum = 0;
  451. }
  452. }
  453. TT.hunknum++;
  454. continue;
  455. }
  456. // If we didn't continue above, discard this line.
  457. free(patchline);
  458. }
  459. finish_oldfile();
  460. if (ENABLE_FEATURE_CLEAN_UP) {
  461. free(oldname);
  462. free(newname);
  463. }
  464. return TT.exitval;
  465. }