patch_toybox.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /* Adapted from toybox's patch. */
  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, USE_TOYBOX_DEBUG("x")"up#i:R", TOYFLAG_USR|TOYFLAG_BIN))
  25. config PATCH
  26. bool "patch (9.4 kb)"
  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_simple_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. char *infile;
  192. long prefix;
  193. struct double_list *current_hunk;
  194. long oldline, oldlen, newline, newlen, linenum;
  195. int context, state, filein, fileout, filepatch, hunknum;
  196. char *tempname;
  197. // was toys.foo:
  198. int exitval;
  199. };
  200. #define TT (*ptr_to_globals)
  201. #define INIT_TT() do { \
  202. SET_PTR_TO_GLOBALS(xzalloc(sizeof(TT))); \
  203. } while (0)
  204. //bbox had: "p:i:RN"
  205. #define FLAG_STR "Rup:i:x"
  206. /* FLAG_REVERSE must be == 1! Code uses this fact. */
  207. #define FLAG_REVERSE (1 << 0)
  208. #define FLAG_u (1 << 1)
  209. #define FLAG_PATHLEN (1 << 2)
  210. #define FLAG_INPUT (1 << 3)
  211. //non-standard:
  212. #define FLAG_DEBUG (1 << 4)
  213. // Dispose of a line of input, either by writing it out or discarding it.
  214. // state < 2: just free
  215. // state = 2: write whole line to stderr
  216. // state = 3: write whole line to fileout
  217. // state > 3: write line+1 to fileout when *line != state
  218. #define PATCH_DEBUG (option_mask32 & FLAG_DEBUG)
  219. static void do_line(void *data)
  220. {
  221. struct double_list *dlist = (struct double_list *)data;
  222. if (TT.state>1 && *dlist->data != TT.state)
  223. fdprintf(TT.state == 2 ? 2 : TT.fileout,
  224. "%s\n", dlist->data+(TT.state>3 ? 1 : 0));
  225. if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
  226. free(dlist->data);
  227. free(data);
  228. }
  229. static void finish_oldfile(void)
  230. {
  231. if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
  232. TT.fileout = TT.filein = -1;
  233. }
  234. static void fail_hunk(void)
  235. {
  236. if (!TT.current_hunk) return;
  237. TT.current_hunk->prev->next = 0;
  238. fdprintf(2, "Hunk %d FAILED %ld/%ld.\n", TT.hunknum, TT.oldline, TT.newline);
  239. TT.exitval = 1;
  240. // If we got to this point, we've seeked to the end. Discard changes to
  241. // this file and advance to next file.
  242. TT.state = 2;
  243. TOY_llist_free(TT.current_hunk, do_line);
  244. TT.current_hunk = NULL;
  245. delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
  246. TT.state = 0;
  247. }
  248. // Given a hunk of a unified diff, make the appropriate change to the file.
  249. // This does not use the location information, but instead treats a hunk
  250. // as a sort of regex. Copies data from input to output until it finds
  251. // the change to be made, then outputs the changed data and returns.
  252. // (Finding EOF first is an error.) This is a single pass operation, so
  253. // multiple hunks must occur in order in the file.
  254. static int apply_one_hunk(void)
  255. {
  256. struct double_list *plist, *buf = NULL, *check;
  257. int matcheof = 0, reverse = option_mask32 & FLAG_REVERSE, backwarn = 0;
  258. // Break doubly linked list so we can use singly linked traversal function.
  259. TT.current_hunk->prev->next = NULL;
  260. // Match EOF if there aren't as many ending context lines as beginning
  261. for (plist = TT.current_hunk; plist; plist = plist->next) {
  262. if (plist->data[0]==' ') matcheof++;
  263. else matcheof = 0;
  264. if (PATCH_DEBUG) fdprintf(2, "HUNK:%s\n", plist->data);
  265. }
  266. matcheof = matcheof < TT.context;
  267. if (PATCH_DEBUG) fdprintf(2,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
  268. // Loop through input data searching for this hunk. Match all context
  269. // lines and all lines to be removed until we've found the end of a
  270. // complete hunk.
  271. plist = TT.current_hunk;
  272. buf = NULL;
  273. if (TT.context) for (;;) {
  274. char *data = get_line(TT.filein);
  275. TT.linenum++;
  276. // Figure out which line of hunk to compare with next. (Skip lines
  277. // of the hunk we'd be adding.)
  278. while (plist && *plist->data == "+-"[reverse]) {
  279. if (data && strcmp(data, plist->data+1) == 0) {
  280. if (!backwarn) {
  281. fdprintf(2,"Possibly reversed hunk %d at %ld\n",
  282. TT.hunknum, TT.linenum);
  283. backwarn++;
  284. }
  285. }
  286. plist = plist->next;
  287. }
  288. // Is this EOF?
  289. if (!data) {
  290. if (PATCH_DEBUG) fdprintf(2, "INEOF\n");
  291. // Does this hunk need to match EOF?
  292. if (!plist && matcheof) break;
  293. // File ended before we found a place for this hunk.
  294. fail_hunk();
  295. goto done;
  296. } else if (PATCH_DEBUG) fdprintf(2, "IN: %s\n", data);
  297. check = dlist_add(&buf, data);
  298. // Compare this line with next expected line of hunk.
  299. // todo: teach the strcmp() to ignore whitespace.
  300. // A match can fail because the next line doesn't match, or because
  301. // we hit the end of a hunk that needed EOF, and this isn't EOF.
  302. // If match failed, flush first line of buffered data and
  303. // recheck buffered data for a new match until we find one or run
  304. // out of buffer.
  305. for (;;) {
  306. if (!plist || strcmp(check->data, plist->data+1)) {
  307. // Match failed. Write out first line of buffered data and
  308. // recheck remaining buffered data for a new match.
  309. if (PATCH_DEBUG)
  310. fdprintf(2, "NOT: %s\n", plist->data);
  311. TT.state = 3;
  312. check = TOY_llist_pop(&buf);
  313. check->prev->next = buf;
  314. buf->prev = check->prev;
  315. do_line(check);
  316. plist = TT.current_hunk;
  317. // If we've reached the end of the buffer without confirming a
  318. // match, read more lines.
  319. if (check==buf) {
  320. buf = 0;
  321. break;
  322. }
  323. check = buf;
  324. } else {
  325. if (PATCH_DEBUG)
  326. fdprintf(2, "MAYBE: %s\n", plist->data);
  327. // This line matches. Advance plist, detect successful match.
  328. plist = plist->next;
  329. if (!plist && !matcheof) goto out;
  330. check = check->next;
  331. if (check == buf) break;
  332. }
  333. }
  334. }
  335. out:
  336. // We have a match. Emit changed data.
  337. TT.state = "-+"[reverse];
  338. TOY_llist_free(TT.current_hunk, do_line);
  339. TT.current_hunk = NULL;
  340. TT.state = 1;
  341. done:
  342. if (buf) {
  343. buf->prev->next = NULL;
  344. TOY_llist_free(buf, do_line);
  345. }
  346. return TT.state;
  347. }
  348. // Read a patch file and find hunks, opening/creating/deleting files.
  349. // Call apply_one_hunk() on each hunk.
  350. // state 0: Not in a hunk, look for +++.
  351. // state 1: Found +++ file indicator, look for @@
  352. // state 2: In hunk: counting initial context lines
  353. // state 3: In hunk: getting body
  354. int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  355. int patch_main(int argc UNUSED_PARAM, char **argv)
  356. {
  357. int opts;
  358. int reverse, state = 0;
  359. char *oldname = NULL, *newname = NULL;
  360. char *opt_p, *opt_i;
  361. INIT_TT();
  362. opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i);
  363. reverse = opts & FLAG_REVERSE;
  364. TT.prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative!
  365. if (opts & FLAG_INPUT) TT.filepatch = xopen(opt_i, O_RDONLY);
  366. TT.filein = TT.fileout = -1;
  367. // Loop through the lines in the patch
  368. for(;;) {
  369. char *patchline;
  370. patchline = get_line(TT.filepatch);
  371. if (!patchline) break;
  372. // Other versions of patch accept damaged patches,
  373. // so we need to also.
  374. if (!*patchline) {
  375. free(patchline);
  376. patchline = xstrdup(" ");
  377. }
  378. // Are we assembling a hunk?
  379. if (state >= 2) {
  380. if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
  381. dlist_add(&TT.current_hunk, patchline);
  382. if (*patchline != '+') TT.oldlen--;
  383. if (*patchline != '-') TT.newlen--;
  384. // Context line?
  385. if (*patchline==' ' && state==2) TT.context++;
  386. else state=3;
  387. // If we've consumed all expected hunk lines, apply the hunk.
  388. if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
  389. continue;
  390. }
  391. fail_hunk();
  392. state = 0;
  393. continue;
  394. }
  395. // Open a new file?
  396. if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
  397. char *s, **name = reverse ? &newname : &oldname;
  398. int i;
  399. if (*patchline == '+') {
  400. name = reverse ? &oldname : &newname;
  401. state = 1;
  402. }
  403. free(*name);
  404. finish_oldfile();
  405. // Trim date from end of filename (if any). We don't care.
  406. for (s = patchline+4; *s && *s!='\t'; s++)
  407. if (*s=='\\' && s[1]) s++;
  408. i = atoi(s);
  409. if (i>1900 && i<=1970)
  410. *name = xstrdup("/dev/null");
  411. else {
  412. *s = 0;
  413. *name = xstrdup(patchline+4);
  414. }
  415. // We defer actually opening the file because svn produces broken
  416. // patches that don't signal they want to create a new file the
  417. // way the patch man page says, so you have to read the first hunk
  418. // and _guess_.
  419. // Start a new hunk?
  420. } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
  421. int i;
  422. i = sscanf(patchline+4, "%ld,%ld +%ld,%ld", &TT.oldline,
  423. &TT.oldlen, &TT.newline, &TT.newlen);
  424. if (i != 4)
  425. bb_error_msg_and_die("corrupt hunk %d at %ld", TT.hunknum, TT.linenum);
  426. TT.context = 0;
  427. state = 2;
  428. // If this is the first hunk, open the file.
  429. if (TT.filein == -1) {
  430. int oldsum, newsum, del = 0;
  431. char *s, *name;
  432. oldsum = TT.oldline + TT.oldlen;
  433. newsum = TT.newline + TT.newlen;
  434. name = reverse ? oldname : newname;
  435. // We're deleting oldname if new file is /dev/null (before -p)
  436. // or if new hunk is empty (zero context) after patching
  437. if (strcmp(name, "/dev/null") == 0 || !(reverse ? oldsum : newsum)) {
  438. name = reverse ? newname : oldname;
  439. del++;
  440. }
  441. // handle -p path truncation.
  442. for (i=0, s = name; *s;) {
  443. if ((option_mask32 & FLAG_PATHLEN) && TT.prefix == i) break;
  444. if (*(s++)=='/') {
  445. name = s;
  446. i++;
  447. }
  448. }
  449. if (del) {
  450. printf("removing %s\n", name);
  451. xunlink(name);
  452. state = 0;
  453. // If we've got a file to open, do so.
  454. } else if (!(option_mask32 & FLAG_PATHLEN) || i <= TT.prefix) {
  455. // If the old file was null, we're creating a new one.
  456. if (strcmp(oldname, "/dev/null") == 0 || !oldsum) {
  457. printf("creating %s\n", name);
  458. s = strrchr(name, '/');
  459. if (s) {
  460. *s = 0;
  461. xmkpath(name, -1);
  462. *s = '/';
  463. }
  464. TT.filein = xopen(name, O_CREAT|O_EXCL|O_RDWR);
  465. } else {
  466. printf("patching file %s\n", name);
  467. TT.filein = xopen(name, O_RDWR);
  468. }
  469. TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
  470. TT.linenum = 0;
  471. TT.hunknum = 0;
  472. }
  473. }
  474. TT.hunknum++;
  475. continue;
  476. }
  477. // If we didn't continue above, discard this line.
  478. free(patchline);
  479. }
  480. finish_oldfile();
  481. if (ENABLE_FEATURE_CLEAN_UP) {
  482. close(TT.filepatch);
  483. free(oldname);
  484. free(newname);
  485. }
  486. return TT.exitval;
  487. }