patch.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /* vi: set sw=4 ts=4:
  2. *
  3. * Apply a "universal" diff.
  4. * Adapted from toybox's patch implementation.
  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. * -d chdir first
  15. * -D define wrap #ifdef and #ifndef around changes
  16. * -o outfile output here instead of in place
  17. * -r rejectfile write rejected hunks to this file
  18. *
  19. * -f force (no questions asked)
  20. * -F fuzz (number, default 2)
  21. * [file] which file to patch
  22. */
  23. //applet:IF_PATCH(APPLET(patch, _BB_DIR_USR_BIN, _BB_SUID_DROP))
  24. //kbuild:lib-$(CONFIG_PATCH) += patch.o
  25. //config:config PATCH
  26. //config: bool "patch"
  27. //config: default y
  28. //config: help
  29. //config: Apply a unified diff formatted patch.
  30. //usage:#define patch_trivial_usage
  31. //usage: "[OPTIONS] [ORIGFILE [PATCHFILE]]"
  32. //usage:#define patch_full_usage "\n\n"
  33. //usage: IF_LONG_OPTS(
  34. //usage: " -p,--strip N Strip N leading components from file names"
  35. //usage: "\n -i,--input DIFF Read DIFF instead of stdin"
  36. //usage: "\n -R,--reverse Reverse patch"
  37. //usage: "\n -N,--forward Ignore already applied patches"
  38. //usage: "\n --dry-run Don't actually change files"
  39. //usage: "\n -E,--remove-empty-files Remove output files if they become empty"
  40. //usage: )
  41. //usage: IF_NOT_LONG_OPTS(
  42. //usage: " -p N Strip N leading components from file names"
  43. //usage: "\n -i DIFF Read DIFF instead of stdin"
  44. //usage: "\n -R Reverse patch"
  45. //usage: "\n -N Ignore already applied patches"
  46. //usage: "\n -E Remove output files if they become empty"
  47. //usage: )
  48. //usage:
  49. //usage:#define patch_example_usage
  50. //usage: "$ patch -p1 < example.diff\n"
  51. //usage: "$ patch -p0 -i example.diff"
  52. #include "libbb.h"
  53. // libbb candidate?
  54. struct double_list {
  55. struct double_list *next;
  56. struct double_list *prev;
  57. char *data;
  58. };
  59. // Free all the elements of a linked list
  60. // Call freeit() on each element before freeing it.
  61. static
  62. void dlist_free(struct double_list *list, void (*freeit)(void *data))
  63. {
  64. while (list) {
  65. void *pop = list;
  66. list = list->next;
  67. freeit(pop);
  68. // Bail out also if list is circular.
  69. if (list == pop) break;
  70. }
  71. }
  72. // Add an entry before "list" element in (circular) doubly linked list
  73. static
  74. struct double_list *dlist_add(struct double_list **list, char *data)
  75. {
  76. struct double_list *llist;
  77. struct double_list *line = xmalloc(sizeof(*line));
  78. line->data = data;
  79. llist = *list;
  80. if (llist) {
  81. struct double_list *p;
  82. line->next = llist;
  83. p = line->prev = llist->prev;
  84. // (list is circular, we assume p is never NULL)
  85. p->next = line;
  86. llist->prev = line;
  87. } else
  88. *list = line->next = line->prev = line;
  89. return line;
  90. }
  91. struct globals {
  92. char *infile;
  93. long prefix;
  94. struct double_list *current_hunk;
  95. long oldline, oldlen, newline, newlen;
  96. long linenum;
  97. int context, state, hunknum;
  98. int filein, fileout;
  99. char *tempname;
  100. int exitval;
  101. };
  102. #define TT (*ptr_to_globals)
  103. #define INIT_TT() do { \
  104. SET_PTR_TO_GLOBALS(xzalloc(sizeof(TT))); \
  105. } while (0)
  106. #define FLAG_STR "Rup:i:NEx"
  107. /* FLAG_REVERSE must be == 1! Code uses this fact. */
  108. #define FLAG_REVERSE (1 << 0)
  109. #define FLAG_u (1 << 1)
  110. #define FLAG_PATHLEN (1 << 2)
  111. #define FLAG_INPUT (1 << 3)
  112. #define FLAG_IGNORE (1 << 4)
  113. #define FLAG_RMEMPTY (1 << 5)
  114. //non-standard:
  115. #define FLAG_DEBUG (1 << 6)
  116. // Dispose of a line of input, either by writing it out or discarding it.
  117. // state < 2: just free
  118. // state = 2: write whole line to stderr
  119. // state = 3: write whole line to fileout
  120. // state > 3: write line+1 to fileout when *line != state
  121. #define PATCH_DEBUG (option_mask32 & FLAG_DEBUG)
  122. static void do_line(void *data)
  123. {
  124. struct double_list *dlist = data;
  125. if (TT.state>1 && *dlist->data != TT.state)
  126. fdprintf(TT.state == 2 ? 2 : TT.fileout,
  127. "%s\n", dlist->data+(TT.state>3 ? 1 : 0));
  128. if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
  129. free(dlist->data);
  130. free(dlist);
  131. }
  132. static void finish_oldfile(void)
  133. {
  134. if (TT.tempname) {
  135. // Copy the rest of the data and replace the original with the copy.
  136. char *temp;
  137. if (TT.filein != -1) {
  138. bb_copyfd_eof(TT.filein, TT.fileout);
  139. xclose(TT.filein);
  140. }
  141. xclose(TT.fileout);
  142. temp = xstrdup(TT.tempname);
  143. temp[strlen(temp) - 6] = '\0';
  144. rename(TT.tempname, temp);
  145. free(temp);
  146. free(TT.tempname);
  147. TT.tempname = NULL;
  148. }
  149. TT.fileout = TT.filein = -1;
  150. }
  151. static void fail_hunk(void)
  152. {
  153. if (!TT.current_hunk) return;
  154. fdprintf(2, "Hunk %d FAILED %ld/%ld.\n", TT.hunknum, TT.oldline, TT.newline);
  155. TT.exitval = 1;
  156. // If we got to this point, we've seeked to the end. Discard changes to
  157. // this file and advance to next file.
  158. TT.state = 2;
  159. TT.current_hunk->prev->next = NULL;
  160. dlist_free(TT.current_hunk, do_line);
  161. TT.current_hunk = NULL;
  162. // Abort the copy and delete the temporary file.
  163. close(TT.filein);
  164. close(TT.fileout);
  165. unlink(TT.tempname);
  166. free(TT.tempname);
  167. TT.tempname = NULL;
  168. TT.state = 0;
  169. }
  170. // Given a hunk of a unified diff, make the appropriate change to the file.
  171. // This does not use the location information, but instead treats a hunk
  172. // as a sort of regex. Copies data from input to output until it finds
  173. // the change to be made, then outputs the changed data and returns.
  174. // (Finding EOF first is an error.) This is a single pass operation, so
  175. // multiple hunks must occur in order in the file.
  176. static int apply_one_hunk(void)
  177. {
  178. struct double_list *plist, *buf = NULL, *check;
  179. int matcheof = 0, reverse = option_mask32 & FLAG_REVERSE, backwarn = 0;
  180. /* Do we try "dummy" revert to check whether
  181. * to silently skip this hunk? Used to implement -N.
  182. */
  183. int dummy_revert = 0;
  184. // Break doubly linked list so we can use singly linked traversal function.
  185. TT.current_hunk->prev->next = NULL;
  186. // Match EOF if there aren't as many ending context lines as beginning
  187. for (plist = TT.current_hunk; plist; plist = plist->next) {
  188. if (plist->data[0]==' ') matcheof++;
  189. else matcheof = 0;
  190. if (PATCH_DEBUG) fdprintf(2, "HUNK:%s\n", plist->data);
  191. }
  192. matcheof = matcheof < TT.context;
  193. if (PATCH_DEBUG) fdprintf(2,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
  194. // Loop through input data searching for this hunk. Match all context
  195. // lines and all lines to be removed until we've found the end of a
  196. // complete hunk.
  197. plist = TT.current_hunk;
  198. buf = NULL;
  199. if (TT.context) for (;;) {
  200. char *data = xmalloc_reads(TT.filein, NULL, NULL);
  201. TT.linenum++;
  202. // Figure out which line of hunk to compare with next. (Skip lines
  203. // of the hunk we'd be adding.)
  204. while (plist && *plist->data == "+-"[reverse]) {
  205. if (data && !strcmp(data, plist->data+1)) {
  206. if (!backwarn) {
  207. backwarn = TT.linenum;
  208. if (option_mask32 & FLAG_IGNORE) {
  209. dummy_revert = 1;
  210. reverse ^= 1;
  211. continue;
  212. }
  213. }
  214. }
  215. plist = plist->next;
  216. }
  217. // Is this EOF?
  218. if (!data) {
  219. if (PATCH_DEBUG) fdprintf(2, "INEOF\n");
  220. // Does this hunk need to match EOF?
  221. if (!plist && matcheof) break;
  222. if (backwarn)
  223. fdprintf(2,"Possibly reversed hunk %d at %ld\n",
  224. TT.hunknum, TT.linenum);
  225. // File ended before we found a place for this hunk.
  226. fail_hunk();
  227. goto done;
  228. }
  229. if (PATCH_DEBUG) fdprintf(2, "IN: %s\n", data);
  230. check = dlist_add(&buf, data);
  231. // Compare this line with next expected line of hunk.
  232. // todo: teach the strcmp() to ignore whitespace.
  233. // A match can fail because the next line doesn't match, or because
  234. // we hit the end of a hunk that needed EOF, and this isn't EOF.
  235. // If match failed, flush first line of buffered data and
  236. // recheck buffered data for a new match until we find one or run
  237. // out of buffer.
  238. for (;;) {
  239. if (!plist || strcmp(check->data, plist->data+1)) {
  240. // Match failed. Write out first line of buffered data and
  241. // recheck remaining buffered data for a new match.
  242. if (PATCH_DEBUG)
  243. fdprintf(2, "NOT: %s\n", plist->data);
  244. TT.state = 3;
  245. check = buf;
  246. buf = buf->next;
  247. check->prev->next = buf;
  248. buf->prev = check->prev;
  249. do_line(check);
  250. plist = TT.current_hunk;
  251. // If we've reached the end of the buffer without confirming a
  252. // match, read more lines.
  253. if (check == buf) {
  254. buf = NULL;
  255. break;
  256. }
  257. check = buf;
  258. } else {
  259. if (PATCH_DEBUG)
  260. fdprintf(2, "MAYBE: %s\n", plist->data);
  261. // This line matches. Advance plist, detect successful match.
  262. plist = plist->next;
  263. if (!plist && !matcheof) goto out;
  264. check = check->next;
  265. if (check == buf) break;
  266. }
  267. }
  268. }
  269. out:
  270. // We have a match. Emit changed data.
  271. TT.state = "-+"[reverse ^ dummy_revert];
  272. dlist_free(TT.current_hunk, do_line);
  273. TT.current_hunk = NULL;
  274. TT.state = 1;
  275. done:
  276. if (buf) {
  277. buf->prev->next = NULL;
  278. dlist_free(buf, do_line);
  279. }
  280. return TT.state;
  281. }
  282. // Read a patch file and find hunks, opening/creating/deleting files.
  283. // Call apply_one_hunk() on each hunk.
  284. // state 0: Not in a hunk, look for +++.
  285. // state 1: Found +++ file indicator, look for @@
  286. // state 2: In hunk: counting initial context lines
  287. // state 3: In hunk: getting body
  288. int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  289. int patch_main(int argc UNUSED_PARAM, char **argv)
  290. {
  291. int opts;
  292. int reverse, state = 0;
  293. char *oldname = NULL, *newname = NULL;
  294. char *opt_p, *opt_i;
  295. INIT_TT();
  296. opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i);
  297. argv += optind;
  298. reverse = opts & FLAG_REVERSE;
  299. TT.prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative!
  300. TT.filein = TT.fileout = -1;
  301. if (opts & FLAG_INPUT) {
  302. xmove_fd(xopen_stdin(opt_i), STDIN_FILENO);
  303. } else {
  304. if (argv[0] && argv[1]) {
  305. xmove_fd(xopen_stdin(argv[1]), STDIN_FILENO);
  306. }
  307. }
  308. if (argv[0]) {
  309. oldname = xstrdup(argv[0]);
  310. newname = xstrdup(argv[0]);
  311. }
  312. // Loop through the lines in the patch
  313. for(;;) {
  314. char *patchline;
  315. patchline = xmalloc_fgetline(stdin);
  316. if (!patchline) break;
  317. // Other versions of patch accept damaged patches,
  318. // so we need to also.
  319. if (!*patchline) {
  320. free(patchline);
  321. patchline = xstrdup(" ");
  322. }
  323. // Are we assembling a hunk?
  324. if (state >= 2) {
  325. if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
  326. dlist_add(&TT.current_hunk, patchline);
  327. if (*patchline != '+') TT.oldlen--;
  328. if (*patchline != '-') TT.newlen--;
  329. // Context line?
  330. if (*patchline==' ' && state==2) TT.context++;
  331. else state=3;
  332. // If we've consumed all expected hunk lines, apply the hunk.
  333. if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
  334. continue;
  335. }
  336. fail_hunk();
  337. state = 0;
  338. continue;
  339. }
  340. // Open a new file?
  341. if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
  342. char *s, **name = reverse ? &newname : &oldname;
  343. int i;
  344. if (*patchline == '+') {
  345. name = reverse ? &oldname : &newname;
  346. state = 1;
  347. }
  348. finish_oldfile();
  349. if (!argv[0]) {
  350. free(*name);
  351. // Trim date from end of filename (if any). We don't care.
  352. for (s = patchline+4; *s && *s!='\t'; s++)
  353. if (*s=='\\' && s[1]) s++;
  354. i = atoi(s);
  355. if (i>1900 && i<=1970)
  356. *name = xstrdup("/dev/null");
  357. else {
  358. *s = 0;
  359. *name = xstrdup(patchline+4);
  360. }
  361. }
  362. // We defer actually opening the file because svn produces broken
  363. // patches that don't signal they want to create a new file the
  364. // way the patch man page says, so you have to read the first hunk
  365. // and _guess_.
  366. // Start a new hunk? Usually @@ -oldline,oldlen +newline,newlen @@
  367. // but a missing ,value means the value is 1.
  368. } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
  369. int i;
  370. char *s = patchline+4;
  371. // Read oldline[,oldlen] +newline[,newlen]
  372. TT.oldlen = TT.newlen = 1;
  373. TT.oldline = strtol(s, &s, 10);
  374. if (*s == ',') TT.oldlen=strtol(s+1, &s, 10);
  375. TT.newline = strtol(s+2, &s, 10);
  376. if (*s == ',') TT.newlen = strtol(s+1, &s, 10);
  377. TT.context = 0;
  378. state = 2;
  379. // If this is the first hunk, open the file.
  380. if (TT.filein == -1) {
  381. int oldsum, newsum, empty = 0;
  382. char *name;
  383. oldsum = TT.oldline + TT.oldlen;
  384. newsum = TT.newline + TT.newlen;
  385. name = reverse ? oldname : newname;
  386. // We're deleting oldname if new file is /dev/null (before -p)
  387. // or if new hunk is empty (zero context) after patching
  388. if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum))
  389. {
  390. name = reverse ? newname : oldname;
  391. empty++;
  392. }
  393. // handle -p path truncation.
  394. for (i=0, s = name; *s;) {
  395. if ((option_mask32 & FLAG_PATHLEN) && TT.prefix == i) break;
  396. if (*(s++)=='/') {
  397. name = s;
  398. i++;
  399. }
  400. }
  401. if (empty) {
  402. // File is empty after the patches have been applied
  403. state = 0;
  404. if (option_mask32 & FLAG_RMEMPTY) {
  405. // If flag -E or --remove-empty-files is set
  406. printf("removing %s\n", name);
  407. xunlink(name);
  408. } else {
  409. printf("patching file %s\n", name);
  410. xclose(xopen(name, O_WRONLY | O_TRUNC));
  411. }
  412. // If we've got a file to open, do so.
  413. } else if (!(option_mask32 & FLAG_PATHLEN) || i <= TT.prefix) {
  414. struct stat statbuf;
  415. // If the old file was null, we're creating a new one.
  416. if (!strcmp(oldname, "/dev/null") || !oldsum) {
  417. printf("creating %s\n", name);
  418. s = strrchr(name, '/');
  419. if (s) {
  420. *s = 0;
  421. bb_make_directory(name, -1, FILEUTILS_RECUR);
  422. *s = '/';
  423. }
  424. TT.filein = xopen(name, O_CREAT|O_EXCL|O_RDWR);
  425. } else {
  426. printf("patching file %s\n", name);
  427. TT.filein = xopen(name, O_RDONLY);
  428. }
  429. TT.tempname = xasprintf("%sXXXXXX", name);
  430. TT.fileout = xmkstemp(TT.tempname);
  431. // Set permissions of output file
  432. fstat(TT.filein, &statbuf);
  433. fchmod(TT.fileout, statbuf.st_mode);
  434. TT.linenum = 0;
  435. TT.hunknum = 0;
  436. }
  437. }
  438. TT.hunknum++;
  439. continue;
  440. }
  441. // If we didn't continue above, discard this line.
  442. free(patchline);
  443. }
  444. finish_oldfile();
  445. if (ENABLE_FEATURE_CLEAN_UP) {
  446. free(oldname);
  447. free(newname);
  448. }
  449. return TT.exitval;
  450. }