PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/cvs/diff/diff3.c

https://bitbucket.org/freebsd/freebsd-head/
C | 1930 lines | 1306 code | 216 blank | 408 comment | 251 complexity | 3eaf867e4ec90e251e45c2d796cf4b9f MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, LGPL-2.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, AGPL-1.0, GPL-2.0
  1. /* Three way file comparison program (diff3) for Project GNU.
  2. Copyright (C) 1988, 1989, 1992, 1993, 1994, 1997, 1998 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. */
  12. /*
  13. * $FreeBSD$
  14. */
  15. /* Written by Randy Smith */
  16. /* Librarification by Tim Pierce */
  17. #include "system.h"
  18. #include <stdio.h>
  19. #include <setjmp.h>
  20. #include "getopt.h"
  21. #include "diffrun.h"
  22. /* diff3.c has a real initialize_main function. */
  23. #ifdef initialize_main
  24. #undef initialize_main
  25. #endif
  26. extern char const diff_version_string[];
  27. extern FILE *outfile;
  28. extern const struct diff_callbacks *callbacks;
  29. void write_output PARAMS((char const *, size_t));
  30. void printf_output PARAMS((char const *, ...))
  31. #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 6)
  32. __attribute__ ((__format__ (__printf__, 1, 2)))
  33. #endif
  34. ;
  35. void flush_output PARAMS((void));
  36. char * cvs_temp_name PARAMS((void));
  37. /*
  38. * Internal data structures and macros for the diff3 program; includes
  39. * data structures for both diff3 diffs and normal diffs.
  40. */
  41. /* Different files within a three way diff. */
  42. #define FILE0 0
  43. #define FILE1 1
  44. #define FILE2 2
  45. /*
  46. * A three way diff is built from two two-way diffs; the file which
  47. * the two two-way diffs share is:
  48. */
  49. #define FILEC FILE2
  50. /*
  51. * Different files within a two way diff.
  52. * FC is the common file, FO the other file.
  53. */
  54. #define FO 0
  55. #define FC 1
  56. /* The ranges are indexed by */
  57. #define START 0
  58. #define END 1
  59. enum diff_type {
  60. ERROR, /* Should not be used */
  61. ADD, /* Two way diff add */
  62. CHANGE, /* Two way diff change */
  63. DELETE, /* Two way diff delete */
  64. DIFF_ALL, /* All three are different */
  65. DIFF_1ST, /* Only the first is different */
  66. DIFF_2ND, /* Only the second */
  67. DIFF_3RD /* Only the third */
  68. };
  69. /* Two way diff */
  70. struct diff_block {
  71. int ranges[2][2]; /* Ranges are inclusive */
  72. char **lines[2]; /* The actual lines (may contain nulls) */
  73. size_t *lengths[2]; /* Line lengths (including newlines, if any) */
  74. struct diff_block *next;
  75. };
  76. /* Three way diff */
  77. struct diff3_block {
  78. enum diff_type correspond; /* Type of diff */
  79. int ranges[3][2]; /* Ranges are inclusive */
  80. char **lines[3]; /* The actual lines (may contain nulls) */
  81. size_t *lengths[3]; /* Line lengths (including newlines, if any) */
  82. struct diff3_block *next;
  83. };
  84. /*
  85. * Access the ranges on a diff block.
  86. */
  87. #define D_LOWLINE(diff, filenum) \
  88. ((diff)->ranges[filenum][START])
  89. #define D_HIGHLINE(diff, filenum) \
  90. ((diff)->ranges[filenum][END])
  91. #define D_NUMLINES(diff, filenum) \
  92. (D_HIGHLINE (diff, filenum) - D_LOWLINE (diff, filenum) + 1)
  93. /*
  94. * Access the line numbers in a file in a diff by relative line
  95. * numbers (i.e. line number within the diff itself). Note that these
  96. * are lvalues and can be used for assignment.
  97. */
  98. #define D_RELNUM(diff, filenum, linenum) \
  99. ((diff)->lines[filenum][linenum])
  100. #define D_RELLEN(diff, filenum, linenum) \
  101. ((diff)->lengths[filenum][linenum])
  102. /*
  103. * And get at them directly, when that should be necessary.
  104. */
  105. #define D_LINEARRAY(diff, filenum) \
  106. ((diff)->lines[filenum])
  107. #define D_LENARRAY(diff, filenum) \
  108. ((diff)->lengths[filenum])
  109. /*
  110. * Next block.
  111. */
  112. #define D_NEXT(diff) ((diff)->next)
  113. /*
  114. * Access the type of a diff3 block.
  115. */
  116. #define D3_TYPE(diff) ((diff)->correspond)
  117. /*
  118. * Line mappings based on diffs. The first maps off the top of the
  119. * diff, the second off of the bottom.
  120. */
  121. #define D_HIGH_MAPLINE(diff, fromfile, tofile, lineno) \
  122. ((lineno) \
  123. - D_HIGHLINE ((diff), (fromfile)) \
  124. + D_HIGHLINE ((diff), (tofile)))
  125. #define D_LOW_MAPLINE(diff, fromfile, tofile, lineno) \
  126. ((lineno) \
  127. - D_LOWLINE ((diff), (fromfile)) \
  128. + D_LOWLINE ((diff), (tofile)))
  129. /*
  130. * General memory allocation function.
  131. */
  132. #define ALLOCATE(number, type) \
  133. (type *) xmalloc ((number) * sizeof (type))
  134. /* Options variables for flags set on command line. */
  135. /* If nonzero, treat all files as text files, never as binary. */
  136. static int always_text;
  137. /* If nonzero, write out an ed script instead of the standard diff3 format. */
  138. static int edscript;
  139. /* If nonzero, in the case of overlapping diffs (type DIFF_ALL),
  140. preserve the lines which would normally be deleted from
  141. file 1 with a special flagging mechanism. */
  142. static int flagging;
  143. /* Number of lines to keep in identical prefix and suffix. */
  144. static int const horizon_lines = 10;
  145. /* Use a tab to align output lines (-T). */
  146. static int tab_align_flag;
  147. /* If nonzero, do not output information for overlapping diffs. */
  148. static int simple_only;
  149. /* If nonzero, do not output information for non-overlapping diffs. */
  150. static int overlap_only;
  151. /* If nonzero, show information for DIFF_2ND diffs. */
  152. static int show_2nd;
  153. /* If nonzero, include `:wq' at the end of the script
  154. to write out the file being edited. */
  155. static int finalwrite;
  156. /* If nonzero, output a merged file. */
  157. static int merge;
  158. extern char *diff_program_name;
  159. static char *read_diff PARAMS((char const *, char const *, char **));
  160. static char *scan_diff_line PARAMS((char *, char **, size_t *, char *, int));
  161. static enum diff_type process_diff_control PARAMS((char **, struct diff_block *));
  162. static int compare_line_list PARAMS((char * const[], size_t const[], char * const[], size_t const[], int));
  163. static int copy_stringlist PARAMS((char * const[], size_t const[], char *[], size_t[], int));
  164. static int dotlines PARAMS((struct diff3_block *, int));
  165. static int output_diff3_edscript PARAMS((struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *));
  166. static int output_diff3_merge PARAMS((FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *));
  167. static size_t myread PARAMS((int, char *, size_t));
  168. static struct diff3_block *create_diff3_block PARAMS((int, int, int, int, int, int));
  169. static struct diff3_block *make_3way_diff PARAMS((struct diff_block *, struct diff_block *));
  170. static struct diff3_block *reverse_diff3_blocklist PARAMS((struct diff3_block *));
  171. static struct diff3_block *using_to_diff3_block PARAMS((struct diff_block *[2], struct diff_block *[2], int, int, struct diff3_block const *));
  172. static struct diff_block *process_diff PARAMS((char const *, char const *, struct diff_block **, char **));
  173. static void check_output PARAMS((FILE *));
  174. static void diff3_fatal PARAMS((char const *));
  175. static void output_diff3 PARAMS((struct diff3_block *, int const[3], int const[3]));
  176. static void diff3_perror_with_exit PARAMS((char const *));
  177. static int try_help PARAMS((char const *));
  178. static void undotlines PARAMS((int, int, int));
  179. static void usage PARAMS((void));
  180. static void initialize_main PARAMS((int *, char ***));
  181. static void free_diff_blocks PARAMS((struct diff_block *));
  182. static void free_diff3_blocks PARAMS((struct diff3_block *));
  183. /* Functions provided in libdiff.a or other external sources. */
  184. VOID *xmalloc PARAMS((size_t));
  185. VOID *xrealloc PARAMS((VOID *, size_t));
  186. void perror_with_name PARAMS((char const *));
  187. void diff_error PARAMS((char const *, char const *, char const *));
  188. /* Permit non-local exits from diff3. */
  189. static jmp_buf diff3_abort_buf;
  190. #define DIFF3_ABORT(retval) longjmp(diff3_abort_buf, retval)
  191. static struct option const longopts[] =
  192. {
  193. {"text", 0, 0, 'a'},
  194. {"show-all", 0, 0, 'A'},
  195. {"ed", 0, 0, 'e'},
  196. {"show-overlap", 0, 0, 'E'},
  197. {"label", 1, 0, 'L'},
  198. {"merge", 0, 0, 'm'},
  199. {"initial-tab", 0, 0, 'T'},
  200. {"overlap-only", 0, 0, 'x'},
  201. {"easy-only", 0, 0, '3'},
  202. {"version", 0, 0, 'v'},
  203. {"help", 0, 0, 129},
  204. {0, 0, 0, 0}
  205. };
  206. /*
  207. * Main program. Calls diff twice on two pairs of input files,
  208. * combines the two diffs, and outputs them.
  209. */
  210. int
  211. diff3_run (argc, argv, out, callbacks_arg)
  212. int argc;
  213. char **argv;
  214. char *out;
  215. const struct diff_callbacks *callbacks_arg;
  216. {
  217. int c, i;
  218. int mapping[3];
  219. int rev_mapping[3];
  220. int incompat = 0;
  221. int conflicts_found;
  222. int status;
  223. struct diff_block *thread0, *thread1, *last_block;
  224. char *content0, *content1;
  225. struct diff3_block *diff3;
  226. int tag_count = 0;
  227. char *tag_strings[3];
  228. char *commonname;
  229. char **file;
  230. struct stat statb;
  231. int optind_old;
  232. int opened_file = 0;
  233. callbacks = callbacks_arg;
  234. initialize_main (&argc, &argv);
  235. optind_old = optind;
  236. optind = 0;
  237. while ((c = getopt_long (argc, argv, "aeimvx3AEL:TX", longopts, 0)) != EOF)
  238. {
  239. switch (c)
  240. {
  241. case 'a':
  242. always_text = 1;
  243. break;
  244. case 'A':
  245. show_2nd = 1;
  246. flagging = 1;
  247. incompat++;
  248. break;
  249. case 'x':
  250. overlap_only = 1;
  251. incompat++;
  252. break;
  253. case '3':
  254. simple_only = 1;
  255. incompat++;
  256. break;
  257. case 'i':
  258. finalwrite = 1;
  259. break;
  260. case 'm':
  261. merge = 1;
  262. break;
  263. case 'X':
  264. overlap_only = 1;
  265. /* Falls through */
  266. case 'E':
  267. flagging = 1;
  268. /* Falls through */
  269. case 'e':
  270. incompat++;
  271. break;
  272. case 'T':
  273. tab_align_flag = 1;
  274. break;
  275. case 'v':
  276. if (callbacks && callbacks->write_stdout)
  277. {
  278. (*callbacks->write_stdout) ("diff3 - GNU diffutils version ");
  279. (*callbacks->write_stdout) (diff_version_string);
  280. (*callbacks->write_stdout) ("\n");
  281. }
  282. else
  283. printf ("diff3 - GNU diffutils version %s\n", diff_version_string);
  284. return 0;
  285. case 129:
  286. usage ();
  287. if (! callbacks || ! callbacks->write_stdout)
  288. check_output (stdout);
  289. return 0;
  290. case 'L':
  291. /* Handle up to three -L options. */
  292. if (tag_count < 3)
  293. {
  294. tag_strings[tag_count++] = optarg;
  295. break;
  296. }
  297. return try_help ("Too many labels were given. The limit is 3.");
  298. default:
  299. return try_help (0);
  300. }
  301. }
  302. edscript = incompat & ~merge; /* -AeExX3 without -m implies ed script. */
  303. show_2nd |= ~incompat & merge; /* -m without -AeExX3 implies -A. */
  304. flagging |= ~incompat & merge;
  305. if (incompat > 1 /* Ensure at most one of -AeExX3. */
  306. || finalwrite & merge /* -i -m would rewrite input file. */
  307. || (tag_count && ! flagging)) /* -L requires one of -AEX. */
  308. return try_help ("incompatible options");
  309. if (argc - optind != 3)
  310. return try_help (argc - optind < 3 ? "missing operand" : "extra operand");
  311. file = &argv[optind];
  312. optind = optind_old;
  313. for (i = tag_count; i < 3; i++)
  314. tag_strings[i] = file[i];
  315. /* Always compare file1 to file2, even if file2 is "-".
  316. This is needed for -mAeExX3. Using the file0 as
  317. the common file would produce wrong results, because if the
  318. file0-file1 diffs didn't line up with the file0-file2 diffs
  319. (which is entirely possible since we don't use diff's -n option),
  320. diff3 might report phantom changes from file1 to file2. */
  321. /* Also try to compare file0 to file1 because this is the where
  322. changes are expected to come from. Diffing between these pairs
  323. of files is is most likely to return the intended changes. There
  324. can also be the same problem with phantom changes from file0 to
  325. file1. */
  326. /* Historically, the default common file was file2. Ediff for emacs
  327. and possibly other applications, have therefore made file2 the
  328. ancestor. So, for compatibility, if this is simply a three
  329. way diff (not a merge or edscript) then use the old way with
  330. file2 as the common file. */
  331. {
  332. int common;
  333. if (edscript || merge )
  334. {
  335. common = 1;
  336. }
  337. else
  338. {
  339. common = 2;
  340. }
  341. if (strcmp (file[common], "-") == 0)
  342. {
  343. /* Sigh. We've got standard input as the arg corresponding to
  344. the desired common file. We can't call diff twice on
  345. stdin. Use another arg as the common file instead. */
  346. common = 3 - common;
  347. if (strcmp (file[0], "-") == 0 || strcmp (file[common], "-") == 0)
  348. {
  349. diff_error ("%s", "`-' specified for more than one input file", 0);
  350. return 2;
  351. }
  352. }
  353. mapping[0] = 0;
  354. mapping[1] = 3 - common;
  355. mapping[2] = common;
  356. }
  357. for (i = 0; i < 3; i++)
  358. rev_mapping[mapping[i]] = i;
  359. for (i = 0; i < 3; i++)
  360. if (strcmp (file[i], "-") != 0)
  361. {
  362. if (stat (file[i], &statb) < 0)
  363. {
  364. perror_with_name (file[i]);
  365. return 2;
  366. }
  367. else if (S_ISDIR(statb.st_mode))
  368. {
  369. diff_error ("%s: Is a directory", file[i], 0);
  370. return 2;
  371. }
  372. }
  373. if (callbacks && callbacks->write_output)
  374. {
  375. if (out != NULL)
  376. {
  377. diff_error ("write callback with output file", 0, 0);
  378. return 2;
  379. }
  380. }
  381. else
  382. {
  383. if (out == NULL)
  384. outfile = stdout;
  385. else
  386. {
  387. outfile = fopen (out, "w");
  388. if (outfile == NULL)
  389. {
  390. perror_with_name (out);
  391. return 2;
  392. }
  393. opened_file = 1;
  394. }
  395. }
  396. /* Set the jump buffer, so that diff may abort execution without
  397. terminating the process. */
  398. status = setjmp (diff3_abort_buf);
  399. if (status != 0)
  400. return status;
  401. commonname = file[rev_mapping[FILEC]];
  402. thread1 = process_diff (file[rev_mapping[FILE1]], commonname, &last_block,
  403. &content1);
  404. /* What is the intention behind determining horizon_lines from first
  405. diff? I think it is better to use the same parameters for each
  406. diff so that equal differences in each diff will appear the
  407. same. */
  408. /*
  409. if (thread1)
  410. for (i = 0; i < 2; i++)
  411. {
  412. horizon_lines = max (horizon_lines, D_NUMLINES (thread1, i));
  413. horizon_lines = max (horizon_lines, D_NUMLINES (last_block, i));
  414. }
  415. */
  416. thread0 = process_diff (file[rev_mapping[FILE0]], commonname, &last_block,
  417. &content0);
  418. diff3 = make_3way_diff (thread0, thread1);
  419. if (edscript)
  420. conflicts_found
  421. = output_diff3_edscript (diff3, mapping, rev_mapping,
  422. tag_strings[0], tag_strings[1], tag_strings[2]);
  423. else if (merge)
  424. {
  425. FILE *mfp = fopen (file[rev_mapping[FILE0]], "r");
  426. if (! mfp)
  427. diff3_perror_with_exit (file[rev_mapping[FILE0]]);
  428. conflicts_found = output_diff3_merge (mfp, diff3, mapping, rev_mapping,
  429. tag_strings[0], tag_strings[1], tag_strings[2]);
  430. if (ferror (mfp))
  431. diff3_fatal ("read error");
  432. if (fclose(mfp) != 0)
  433. perror_with_name (file[rev_mapping[FILE0]]);
  434. }
  435. else
  436. {
  437. output_diff3 (diff3, mapping, rev_mapping);
  438. conflicts_found = 0;
  439. }
  440. free(content0);
  441. free(content1);
  442. free_diff3_blocks(diff3);
  443. if (! callbacks || ! callbacks->write_output)
  444. check_output (outfile);
  445. if (opened_file)
  446. if (fclose (outfile) != 0)
  447. perror_with_name ("close error on output file");
  448. return conflicts_found;
  449. }
  450. static int
  451. try_help (reason)
  452. char const *reason;
  453. {
  454. if (reason)
  455. diff_error ("%s", reason, 0);
  456. diff_error ("Try `%s --help' for more information.", diff_program_name, 0);
  457. return 2;
  458. }
  459. static void
  460. check_output (stream)
  461. FILE *stream;
  462. {
  463. if (ferror (stream) || fflush (stream) != 0)
  464. diff3_fatal ("write error");
  465. }
  466. /*
  467. * Explain, patiently and kindly, how to use this program.
  468. */
  469. static void
  470. usage ()
  471. {
  472. if (callbacks && callbacks->write_stdout)
  473. {
  474. (*callbacks->write_stdout) ("Usage: ");
  475. (*callbacks->write_stdout) (diff_program_name);
  476. (*callbacks->write_stdout) (" [OPTION]... MYFILE OLDFILE YOURFILE\n\n");
  477. (*callbacks->write_stdout) ("\
  478. -e --ed Output unmerged changes from OLDFILE to YOURFILE into MYFILE.\n\
  479. -E --show-overlap Output unmerged changes, bracketing conflicts.\n\
  480. -A --show-all Output all changes, bracketing conflicts.\n\
  481. -x --overlap-only Output overlapping changes.\n\
  482. -X Output overlapping changes, bracketing them.\n\
  483. -3 --easy-only Output unmerged nonoverlapping changes.\n\n");
  484. (*callbacks->write_stdout) ("\
  485. -m --merge Output merged file instead of ed script (default -A).\n\
  486. -L LABEL --label=LABEL Use LABEL instead of file name.\n\
  487. -i Append `w' and `q' commands to ed scripts.\n\
  488. -a --text Treat all files as text.\n\
  489. -T --initial-tab Make tabs line up by prepending a tab.\n\n");
  490. (*callbacks->write_stdout) ("\
  491. -v --version Output version info.\n\
  492. --help Output this help.\n\n");
  493. (*callbacks->write_stdout) ("If a FILE is `-', read standard input.\n");
  494. }
  495. else
  496. {
  497. printf ("Usage: %s [OPTION]... MYFILE OLDFILE YOURFILE\n\n", diff_program_name);
  498. printf ("%s", "\
  499. -e --ed Output unmerged changes from OLDFILE to YOURFILE into MYFILE.\n\
  500. -E --show-overlap Output unmerged changes, bracketing conflicts.\n\
  501. -A --show-all Output all changes, bracketing conflicts.\n\
  502. -x --overlap-only Output overlapping changes.\n\
  503. -X Output overlapping changes, bracketing them.\n\
  504. -3 --easy-only Output unmerged nonoverlapping changes.\n\n");
  505. printf ("%s", "\
  506. -m --merge Output merged file instead of ed script (default -A).\n\
  507. -L LABEL --label=LABEL Use LABEL instead of file name.\n\
  508. -i Append `w' and `q' commands to ed scripts.\n\
  509. -a --text Treat all files as text.\n\
  510. -T --initial-tab Make tabs line up by prepending a tab.\n\n");
  511. printf ("%s", "\
  512. -v --version Output version info.\n\
  513. --help Output this help.\n\n");
  514. printf ("If a FILE is `-', read standard input.\n");
  515. }
  516. }
  517. /*
  518. * Routines that combine the two diffs together into one. The
  519. * algorithm used follows:
  520. *
  521. * File2 is shared in common between the two diffs.
  522. * Diff02 is the diff between 0 and 2.
  523. * Diff12 is the diff between 1 and 2.
  524. *
  525. * 1) Find the range for the first block in File2.
  526. * a) Take the lowest of the two ranges (in File2) in the two
  527. * current blocks (one from each diff) as being the low
  528. * water mark. Assign the upper end of this block as
  529. * being the high water mark and move the current block up
  530. * one. Mark the block just moved over as to be used.
  531. * b) Check the next block in the diff that the high water
  532. * mark is *not* from.
  533. *
  534. * *If* the high water mark is above
  535. * the low end of the range in that block,
  536. *
  537. * mark that block as to be used and move the current
  538. * block up. Set the high water mark to the max of
  539. * the high end of this block and the current. Repeat b.
  540. *
  541. * 2) Find the corresponding ranges in File0 (from the blocks
  542. * in diff02; line per line outside of diffs) and in File1.
  543. * Create a diff3_block, reserving space as indicated by the ranges.
  544. *
  545. * 3) Copy all of the pointers for file2 in. At least for now,
  546. * do memcmp's between corresponding strings in the two diffs.
  547. *
  548. * 4) Copy all of the pointers for file0 and 1 in. Get what you
  549. * need from file2 (when there isn't a diff block, it's
  550. * identical to file2 within the range between diff blocks).
  551. *
  552. * 5) If the diff blocks you used came from only one of the two
  553. * strings of diffs, then that file (i.e. the one other than
  554. * the common file in that diff) is the odd person out. If you used
  555. * diff blocks from both sets, check to see if files 0 and 1 match:
  556. *
  557. * Same number of lines? If so, do a set of memcmp's (if a
  558. * memcmp matches; copy the pointer over; it'll be easier later
  559. * if you have to do any compares). If they match, 0 & 1 are
  560. * the same. If not, all three different.
  561. *
  562. * Then you do it again, until you run out of blocks.
  563. *
  564. */
  565. /*
  566. * This routine makes a three way diff (chain of diff3_block's) from two
  567. * two way diffs (chains of diff_block's). It is assumed that each of
  568. * the two diffs passed are onto the same file (i.e. that each of the
  569. * diffs were made "to" the same file). The three way diff pointer
  570. * returned will have numbering FILE0--the other file in diff02,
  571. * FILE1--the other file in diff12, and FILEC--the common file.
  572. */
  573. static struct diff3_block *
  574. make_3way_diff (thread0, thread1)
  575. struct diff_block *thread0, *thread1;
  576. {
  577. /*
  578. * This routine works on the two diffs passed to it as threads.
  579. * Thread number 0 is diff02, thread number 1 is diff12. The USING
  580. * array is set to the base of the list of blocks to be used to
  581. * construct each block of the three way diff; if no blocks from a
  582. * particular thread are to be used, that element of the using array
  583. * is set to 0. The elements LAST_USING array are set to the last
  584. * elements on each of the using lists.
  585. *
  586. * The HIGH_WATER_MARK is set to the highest line number in the common file
  587. * described in any of the diffs in either of the USING lists. The
  588. * HIGH_WATER_THREAD names the thread. Similarly the BASE_WATER_MARK
  589. * and BASE_WATER_THREAD describe the lowest line number in the common file
  590. * described in any of the diffs in either of the USING lists. The
  591. * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  592. * taken.
  593. *
  594. * The HIGH_WATER_DIFF should always be equal to LAST_USING
  595. * [HIGH_WATER_THREAD]. The OTHER_DIFF is the next diff to check for
  596. * higher water, and should always be equal to
  597. * CURRENT[HIGH_WATER_THREAD ^ 0x1]. The OTHER_THREAD is the thread
  598. * in which the OTHER_DIFF is, and hence should always be equal to
  599. * HIGH_WATER_THREAD ^ 0x1.
  600. *
  601. * The variable LAST_DIFF is kept set to the last diff block produced
  602. * by this routine, for line correspondence purposes between that diff
  603. * and the one currently being worked on. It is initialized to
  604. * ZERO_DIFF before any blocks have been created.
  605. */
  606. struct diff_block
  607. *using[2],
  608. *last_using[2],
  609. *current[2];
  610. int
  611. high_water_mark;
  612. int
  613. high_water_thread,
  614. base_water_thread,
  615. other_thread;
  616. struct diff_block
  617. *high_water_diff,
  618. *other_diff;
  619. struct diff3_block
  620. *result,
  621. *tmpblock,
  622. **result_end;
  623. struct diff3_block const *last_diff3;
  624. static struct diff3_block const zero_diff3 = { 0 };
  625. /* Initialization */
  626. result = 0;
  627. result_end = &result;
  628. current[0] = thread0; current[1] = thread1;
  629. last_diff3 = &zero_diff3;
  630. /* Sniff up the threads until we reach the end */
  631. while (current[0] || current[1])
  632. {
  633. using[0] = using[1] = last_using[0] = last_using[1] = 0;
  634. /* Setup low and high water threads, diffs, and marks. */
  635. if (!current[0])
  636. base_water_thread = 1;
  637. else if (!current[1])
  638. base_water_thread = 0;
  639. else
  640. base_water_thread =
  641. (D_LOWLINE (current[0], FC) > D_LOWLINE (current[1], FC));
  642. high_water_thread = base_water_thread;
  643. high_water_diff = current[high_water_thread];
  644. #if 0
  645. /* low and high waters start off same diff */
  646. base_water_mark = D_LOWLINE (high_water_diff, FC);
  647. #endif
  648. high_water_mark = D_HIGHLINE (high_water_diff, FC);
  649. /* Make the diff you just got info from into the using class */
  650. using[high_water_thread]
  651. = last_using[high_water_thread]
  652. = high_water_diff;
  653. current[high_water_thread] = high_water_diff->next;
  654. last_using[high_water_thread]->next = 0;
  655. /* And mark the other diff */
  656. other_thread = high_water_thread ^ 0x1;
  657. other_diff = current[other_thread];
  658. /* Shuffle up the ladder, checking the other diff to see if it
  659. needs to be incorporated. */
  660. while (other_diff
  661. && D_LOWLINE (other_diff, FC) <= high_water_mark + 1)
  662. {
  663. /* Incorporate this diff into the using list. Note that
  664. this doesn't take it off the current list */
  665. if (using[other_thread])
  666. last_using[other_thread]->next = other_diff;
  667. else
  668. using[other_thread] = other_diff;
  669. last_using[other_thread] = other_diff;
  670. /* Take it off the current list. Note that this following
  671. code assumes that other_diff enters it equal to
  672. current[high_water_thread ^ 0x1] */
  673. current[other_thread] = current[other_thread]->next;
  674. other_diff->next = 0;
  675. /* Set the high_water stuff
  676. If this comparison is equal, then this is the last pass
  677. through this loop; since diff blocks within a given
  678. thread cannot overlap, the high_water_mark will be
  679. *below* the range_start of either of the next diffs. */
  680. if (high_water_mark < D_HIGHLINE (other_diff, FC))
  681. {
  682. high_water_thread ^= 1;
  683. high_water_diff = other_diff;
  684. high_water_mark = D_HIGHLINE (other_diff, FC);
  685. }
  686. /* Set the other diff */
  687. other_thread = high_water_thread ^ 0x1;
  688. other_diff = current[other_thread];
  689. }
  690. /* The using lists contain a list of all of the blocks to be
  691. included in this diff3_block. Create it. */
  692. tmpblock = using_to_diff3_block (using, last_using,
  693. base_water_thread, high_water_thread,
  694. last_diff3);
  695. free_diff_blocks(using[0]);
  696. free_diff_blocks(using[1]);
  697. if (!tmpblock)
  698. diff3_fatal ("internal error: screwup in format of diff blocks");
  699. /* Put it on the list. */
  700. *result_end = tmpblock;
  701. result_end = &tmpblock->next;
  702. /* Set up corresponding lines correctly. */
  703. last_diff3 = tmpblock;
  704. }
  705. return result;
  706. }
  707. /*
  708. * using_to_diff3_block:
  709. * This routine takes two lists of blocks (from two separate diff
  710. * threads) and puts them together into one diff3 block.
  711. * It then returns a pointer to this diff3 block or 0 for failure.
  712. *
  713. * All arguments besides using are for the convenience of the routine;
  714. * they could be derived from the using array.
  715. * LAST_USING is a pair of pointers to the last blocks in the using
  716. * structure.
  717. * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  718. * and highest line numbers for File0.
  719. * last_diff3 contains the last diff produced in the calling routine.
  720. * This is used for lines mappings which would still be identical to
  721. * the state that diff ended in.
  722. *
  723. * A distinction should be made in this routine between the two diffs
  724. * that are part of a normal two diff block, and the three diffs that
  725. * are part of a diff3_block.
  726. */
  727. static struct diff3_block *
  728. using_to_diff3_block (using, last_using, low_thread, high_thread, last_diff3)
  729. struct diff_block
  730. *using[2],
  731. *last_using[2];
  732. int low_thread, high_thread;
  733. struct diff3_block const *last_diff3;
  734. {
  735. int low[2], high[2];
  736. struct diff3_block *result;
  737. struct diff_block *ptr;
  738. int d, i;
  739. /* Find the range in the common file. */
  740. int lowc = D_LOWLINE (using[low_thread], FC);
  741. int highc = D_HIGHLINE (last_using[high_thread], FC);
  742. /* Find the ranges in the other files.
  743. If using[d] is null, that means that the file to which that diff
  744. refers is equivalent to the common file over this range. */
  745. for (d = 0; d < 2; d++)
  746. if (using[d])
  747. {
  748. low[d] = D_LOW_MAPLINE (using[d], FC, FO, lowc);
  749. high[d] = D_HIGH_MAPLINE (last_using[d], FC, FO, highc);
  750. }
  751. else
  752. {
  753. low[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, lowc);
  754. high[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, highc);
  755. }
  756. /* Create a block with the appropriate sizes */
  757. result = create_diff3_block (low[0], high[0], low[1], high[1], lowc, highc);
  758. /* Copy information for the common file.
  759. Return with a zero if any of the compares failed. */
  760. for (d = 0; d < 2; d++)
  761. for (ptr = using[d]; ptr; ptr = D_NEXT (ptr))
  762. {
  763. int result_offset = D_LOWLINE (ptr, FC) - lowc;
  764. if (!copy_stringlist (D_LINEARRAY (ptr, FC),
  765. D_LENARRAY (ptr, FC),
  766. D_LINEARRAY (result, FILEC) + result_offset,
  767. D_LENARRAY (result, FILEC) + result_offset,
  768. D_NUMLINES (ptr, FC)))
  769. return 0;
  770. }
  771. /* Copy information for file d. First deal with anything that might be
  772. before the first diff. */
  773. for (d = 0; d < 2; d++)
  774. {
  775. struct diff_block *u = using[d];
  776. int lo = low[d], hi = high[d];
  777. for (i = 0;
  778. i + lo < (u ? D_LOWLINE (u, FO) : hi + 1);
  779. i++)
  780. {
  781. D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, i);
  782. D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, i);
  783. }
  784. for (ptr = u; ptr; ptr = D_NEXT (ptr))
  785. {
  786. int result_offset = D_LOWLINE (ptr, FO) - lo;
  787. int linec;
  788. if (!copy_stringlist (D_LINEARRAY (ptr, FO),
  789. D_LENARRAY (ptr, FO),
  790. D_LINEARRAY (result, FILE0 + d) + result_offset,
  791. D_LENARRAY (result, FILE0 + d) + result_offset,
  792. D_NUMLINES (ptr, FO)))
  793. return 0;
  794. /* Catch the lines between here and the next diff */
  795. linec = D_HIGHLINE (ptr, FC) + 1 - lowc;
  796. for (i = D_HIGHLINE (ptr, FO) + 1 - lo;
  797. i < (D_NEXT (ptr) ? D_LOWLINE (D_NEXT (ptr), FO) : hi + 1) - lo;
  798. i++)
  799. {
  800. D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, linec);
  801. D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, linec);
  802. linec++;
  803. }
  804. }
  805. }
  806. /* Set correspond */
  807. if (!using[0])
  808. D3_TYPE (result) = DIFF_2ND;
  809. else if (!using[1])
  810. D3_TYPE (result) = DIFF_1ST;
  811. else
  812. {
  813. int nl0 = D_NUMLINES (result, FILE0);
  814. int nl1 = D_NUMLINES (result, FILE1);
  815. if (nl0 != nl1
  816. || !compare_line_list (D_LINEARRAY (result, FILE0),
  817. D_LENARRAY (result, FILE0),
  818. D_LINEARRAY (result, FILE1),
  819. D_LENARRAY (result, FILE1),
  820. nl0))
  821. D3_TYPE (result) = DIFF_ALL;
  822. else
  823. D3_TYPE (result) = DIFF_3RD;
  824. }
  825. return result;
  826. }
  827. /*
  828. * This routine copies pointers from a list of strings to a different list
  829. * of strings. If a spot in the second list is already filled, it
  830. * makes sure that it is filled with the same string; if not it
  831. * returns 0, the copy incomplete.
  832. * Upon successful completion of the copy, it returns 1.
  833. */
  834. static int
  835. copy_stringlist (fromptrs, fromlengths, toptrs, tolengths, copynum)
  836. char * const fromptrs[];
  837. char *toptrs[];
  838. size_t const fromlengths[];
  839. size_t tolengths[];
  840. int copynum;
  841. {
  842. register char * const *f = fromptrs;
  843. register char **t = toptrs;
  844. register size_t const *fl = fromlengths;
  845. register size_t *tl = tolengths;
  846. while (copynum--)
  847. {
  848. if (*t)
  849. { if (*fl != *tl || memcmp (*f, *t, *fl)) return 0; }
  850. else
  851. { *t = *f ; *tl = *fl; }
  852. t++; f++; tl++; fl++;
  853. }
  854. return 1;
  855. }
  856. /*
  857. * Create a diff3_block, with ranges as specified in the arguments.
  858. * Allocate the arrays for the various pointers (and zero them) based
  859. * on the arguments passed. Return the block as a result.
  860. */
  861. static struct diff3_block *
  862. create_diff3_block (low0, high0, low1, high1, low2, high2)
  863. register int low0, high0, low1, high1, low2, high2;
  864. {
  865. struct diff3_block *result = ALLOCATE (1, struct diff3_block);
  866. int numlines;
  867. D3_TYPE (result) = ERROR;
  868. D_NEXT (result) = 0;
  869. /* Assign ranges */
  870. D_LOWLINE (result, FILE0) = low0;
  871. D_HIGHLINE (result, FILE0) = high0;
  872. D_LOWLINE (result, FILE1) = low1;
  873. D_HIGHLINE (result, FILE1) = high1;
  874. D_LOWLINE (result, FILE2) = low2;
  875. D_HIGHLINE (result, FILE2) = high2;
  876. /* Allocate and zero space */
  877. numlines = D_NUMLINES (result, FILE0);
  878. if (numlines)
  879. {
  880. D_LINEARRAY (result, FILE0) = ALLOCATE (numlines, char *);
  881. D_LENARRAY (result, FILE0) = ALLOCATE (numlines, size_t);
  882. bzero (D_LINEARRAY (result, FILE0), (numlines * sizeof (char *)));
  883. bzero (D_LENARRAY (result, FILE0), (numlines * sizeof (size_t)));
  884. }
  885. else
  886. {
  887. D_LINEARRAY (result, FILE0) = 0;
  888. D_LENARRAY (result, FILE0) = 0;
  889. }
  890. numlines = D_NUMLINES (result, FILE1);
  891. if (numlines)
  892. {
  893. D_LINEARRAY (result, FILE1) = ALLOCATE (numlines, char *);
  894. D_LENARRAY (result, FILE1) = ALLOCATE (numlines, size_t);
  895. bzero (D_LINEARRAY (result, FILE1), (numlines * sizeof (char *)));
  896. bzero (D_LENARRAY (result, FILE1), (numlines * sizeof (size_t)));
  897. }
  898. else
  899. {
  900. D_LINEARRAY (result, FILE1) = 0;
  901. D_LENARRAY (result, FILE1) = 0;
  902. }
  903. numlines = D_NUMLINES (result, FILE2);
  904. if (numlines)
  905. {
  906. D_LINEARRAY (result, FILE2) = ALLOCATE (numlines, char *);
  907. D_LENARRAY (result, FILE2) = ALLOCATE (numlines, size_t);
  908. bzero (D_LINEARRAY (result, FILE2), (numlines * sizeof (char *)));
  909. bzero (D_LENARRAY (result, FILE2), (numlines * sizeof (size_t)));
  910. }
  911. else
  912. {
  913. D_LINEARRAY (result, FILE2) = 0;
  914. D_LENARRAY (result, FILE2) = 0;
  915. }
  916. /* Return */
  917. return result;
  918. }
  919. /*
  920. * Compare two lists of lines of text.
  921. * Return 1 if they are equivalent, 0 if not.
  922. */
  923. static int
  924. compare_line_list (list1, lengths1, list2, lengths2, nl)
  925. char * const list1[], * const list2[];
  926. size_t const lengths1[], lengths2[];
  927. int nl;
  928. {
  929. char
  930. * const *l1 = list1,
  931. * const *l2 = list2;
  932. size_t const
  933. *lgths1 = lengths1,
  934. *lgths2 = lengths2;
  935. while (nl--)
  936. if (!*l1 || !*l2 || *lgths1 != *lgths2++
  937. || memcmp (*l1++, *l2++, *lgths1++))
  938. return 0;
  939. return 1;
  940. }
  941. /*
  942. * Routines to input and parse two way diffs.
  943. */
  944. extern char **environ;
  945. static struct diff_block *
  946. process_diff (filea, fileb, last_block, diff_contents)
  947. char const *filea, *fileb;
  948. struct diff_block **last_block;
  949. char **diff_contents;
  950. {
  951. char *diff_limit;
  952. char *scan_diff;
  953. enum diff_type dt;
  954. int i;
  955. struct diff_block *block_list, **block_list_end, *bptr;
  956. diff_limit = read_diff (filea, fileb, diff_contents);
  957. scan_diff = *diff_contents;
  958. block_list_end = &block_list;
  959. bptr = 0; /* Pacify `gcc -W'. */
  960. while (scan_diff < diff_limit)
  961. {
  962. bptr = ALLOCATE (1, struct diff_block);
  963. bptr->lines[0] = bptr->lines[1] = 0;
  964. bptr->lengths[0] = bptr->lengths[1] = 0;
  965. dt = process_diff_control (&scan_diff, bptr);
  966. if (dt == ERROR || *scan_diff != '\n')
  967. {
  968. char *serr;
  969. for (serr = scan_diff; *serr != '\n'; serr++)
  970. ;
  971. *serr = '\0';
  972. diff_error ("diff error: %s", scan_diff, 0);
  973. *serr = '\n';
  974. DIFF3_ABORT (2);
  975. }
  976. scan_diff++;
  977. /* Force appropriate ranges to be null, if necessary */
  978. switch (dt)
  979. {
  980. case ADD:
  981. bptr->ranges[0][0]++;
  982. break;
  983. case DELETE:
  984. bptr->ranges[1][0]++;
  985. break;
  986. case CHANGE:
  987. break;
  988. default:
  989. diff3_fatal ("internal error: invalid diff type in process_diff");
  990. break;
  991. }
  992. /* Allocate space for the pointers for the lines from filea, and
  993. parcel them out among these pointers */
  994. if (dt != ADD)
  995. {
  996. int numlines = D_NUMLINES (bptr, 0);
  997. bptr->lines[0] = ALLOCATE (numlines, char *);
  998. bptr->lengths[0] = ALLOCATE (numlines, size_t);
  999. for (i = 0; i < numlines; i++)
  1000. scan_diff = scan_diff_line (scan_diff,
  1001. &(bptr->lines[0][i]),
  1002. &(bptr->lengths[0][i]),
  1003. diff_limit,
  1004. '<');
  1005. }
  1006. /* Get past the separator for changes */
  1007. if (dt == CHANGE)
  1008. {
  1009. if (strncmp (scan_diff, "---\n", 4))
  1010. diff3_fatal ("invalid diff format; invalid change separator");
  1011. scan_diff += 4;
  1012. }
  1013. /* Allocate space for the pointers for the lines from fileb, and
  1014. parcel them out among these pointers */
  1015. if (dt != DELETE)
  1016. {
  1017. int numlines = D_NUMLINES (bptr, 1);
  1018. bptr->lines[1] = ALLOCATE (numlines, char *);
  1019. bptr->lengths[1] = ALLOCATE (numlines, size_t);
  1020. for (i = 0; i < numlines; i++)
  1021. scan_diff = scan_diff_line (scan_diff,
  1022. &(bptr->lines[1][i]),
  1023. &(bptr->lengths[1][i]),
  1024. diff_limit,
  1025. '>');
  1026. }
  1027. /* Place this block on the blocklist. */
  1028. *block_list_end = bptr;
  1029. block_list_end = &bptr->next;
  1030. }
  1031. *block_list_end = 0;
  1032. *last_block = bptr;
  1033. return block_list;
  1034. }
  1035. /*
  1036. * This routine will parse a normal format diff control string. It
  1037. * returns the type of the diff (ERROR if the format is bad). All of
  1038. * the other important information is filled into to the structure
  1039. * pointed to by db, and the string pointer (whose location is passed
  1040. * to this routine) is updated to point beyond the end of the string
  1041. * parsed. Note that only the ranges in the diff_block will be set by
  1042. * this routine.
  1043. *
  1044. * If some specific pair of numbers has been reduced to a single
  1045. * number, then both corresponding numbers in the diff block are set
  1046. * to that number. In general these numbers are interpetted as ranges
  1047. * inclusive, unless being used by the ADD or DELETE commands. It is
  1048. * assumed that these will be special cased in a superior routine.
  1049. */
  1050. static enum diff_type
  1051. process_diff_control (string, db)
  1052. char **string;
  1053. struct diff_block *db;
  1054. {
  1055. char *s = *string;
  1056. int holdnum;
  1057. enum diff_type type;
  1058. /* These macros are defined here because they can use variables
  1059. defined in this function. Don't try this at home kids, we're
  1060. trained professionals!
  1061. Also note that SKIPWHITE only recognizes tabs and spaces, and
  1062. that READNUM can only read positive, integral numbers */
  1063. #define SKIPWHITE(s) { while (*s == ' ' || *s == '\t') s++; }
  1064. #define READNUM(s, num) \
  1065. { unsigned char c = *s; if (!ISDIGIT (c)) return ERROR; holdnum = 0; \
  1066. do { holdnum = (c - '0' + holdnum * 10); } \
  1067. while (ISDIGIT (c = *++s)); (num) = holdnum; }
  1068. /* Read first set of digits */
  1069. SKIPWHITE (s);
  1070. READNUM (s, db->ranges[0][START]);
  1071. /* Was that the only digit? */
  1072. SKIPWHITE (s);
  1073. if (*s == ',')
  1074. {
  1075. /* Get the next digit */
  1076. s++;
  1077. READNUM (s, db->ranges[0][END]);
  1078. }
  1079. else
  1080. db->ranges[0][END] = db->ranges[0][START];
  1081. /* Get the letter */
  1082. SKIPWHITE (s);
  1083. switch (*s)
  1084. {
  1085. case 'a':
  1086. type = ADD;
  1087. break;
  1088. case 'c':
  1089. type = CHANGE;
  1090. break;
  1091. case 'd':
  1092. type = DELETE;
  1093. break;
  1094. default:
  1095. return ERROR; /* Bad format */
  1096. }
  1097. s++; /* Past letter */
  1098. /* Read second set of digits */
  1099. SKIPWHITE (s);
  1100. READNUM (s, db->ranges[1][START]);
  1101. /* Was that the only digit? */
  1102. SKIPWHITE (s);
  1103. if (*s == ',')
  1104. {
  1105. /* Get the next digit */
  1106. s++;
  1107. READNUM (s, db->ranges[1][END]);
  1108. SKIPWHITE (s); /* To move to end */
  1109. }
  1110. else
  1111. db->ranges[1][END] = db->ranges[1][START];
  1112. *string = s;
  1113. return type;
  1114. }
  1115. static char *
  1116. read_diff (filea, fileb, output_placement)
  1117. char const *filea, *fileb;
  1118. char **output_placement;
  1119. {
  1120. char *diff_result;
  1121. size_t bytes, current_chunk_size, total;
  1122. int fd, wstatus;
  1123. struct stat pipestat;
  1124. FILE *outfile_hold;
  1125. const struct diff_callbacks *callbacks_hold;
  1126. struct diff_callbacks my_callbacks;
  1127. struct diff_callbacks *my_callbacks_arg;
  1128. /* 302 / 1000 is log10(2.0) rounded up. Subtract 1 for the sign bit;
  1129. add 1 for integer division truncation; add 1 more for a minus sign. */
  1130. #define INT_STRLEN_BOUND(type) ((sizeof(type)*CHAR_BIT - 1) * 302 / 1000 + 2)
  1131. char const *argv[7];
  1132. char horizon_arg[17 + INT_STRLEN_BOUND (int)];
  1133. char const **ap;
  1134. char *diffout;
  1135. ap = argv;
  1136. *ap++ = "diff";
  1137. if (always_text)
  1138. *ap++ = "-a";
  1139. sprintf (horizon_arg, "--horizon-lines=%d", horizon_lines);
  1140. *ap++ = horizon_arg;
  1141. *ap++ = "--";
  1142. *ap++ = filea;
  1143. *ap++ = fileb;
  1144. *ap = 0;
  1145. diffout = cvs_temp_name ();
  1146. outfile_hold = outfile;
  1147. callbacks_hold = callbacks;
  1148. /* We want to call diff_run preserving any stdout and stderr
  1149. callbacks, but discarding any callbacks to handle file output,
  1150. since we want the file output to go to our temporary file.
  1151. FIXME: We should use callbacks to just read it into a memory
  1152. buffer; that's we do with the temporary file just below anyhow. */
  1153. if (callbacks == NULL)
  1154. my_callbacks_arg = NULL;
  1155. else
  1156. {
  1157. my_callbacks = *callbacks;
  1158. my_callbacks.write_output = NULL;
  1159. my_callbacks.flush_output = NULL;
  1160. my_callbacks_arg = &my_callbacks;
  1161. }
  1162. wstatus = diff_run (ap - argv, (char **) argv, diffout, my_callbacks_arg);
  1163. outfile = outfile_hold;
  1164. callbacks = callbacks_hold;
  1165. if (wstatus == 2)
  1166. diff3_fatal ("subsidiary diff failed");
  1167. if (-1 == (fd = open (diffout, O_RDONLY)))
  1168. diff3_fatal ("could not open temporary diff file");
  1169. current_chunk_size = 8 * 1024;
  1170. if (fstat (fd, &pipestat) == 0)
  1171. current_chunk_size = max (current_chunk_size, STAT_BLOCKSIZE (pipestat));
  1172. diff_result = xmalloc (current_chunk_size);
  1173. total = 0;
  1174. do {
  1175. bytes = myread (fd,
  1176. diff_result + total,
  1177. current_chunk_size - total);
  1178. total += bytes;
  1179. if (total == current_chunk_size)
  1180. {
  1181. if (current_chunk_size < 2 * current_chunk_size)
  1182. current_chunk_size = 2 * current_chunk_size;
  1183. else if (current_chunk_size < (size_t) -1)
  1184. current_chunk_size = (size_t) -1;
  1185. else
  1186. diff3_fatal ("files are too large to fit into memory");
  1187. diff_result = xrealloc (diff_result, (current_chunk_size *= 2));
  1188. }
  1189. } while (bytes);
  1190. if (total != 0 && diff_result[total-1] != '\n')
  1191. diff3_fatal ("invalid diff format; incomplete last line");
  1192. *output_placement = diff_result;
  1193. if (close (fd) != 0)
  1194. diff3_perror_with_exit ("pipe close");
  1195. unlink (diffout);
  1196. free( diffout );
  1197. return diff_result + total;
  1198. }
  1199. /*
  1200. * Scan a regular diff line (consisting of > or <, followed by a
  1201. * space, followed by text (including nulls) up to a newline.
  1202. *
  1203. * This next routine began life as a macro and many parameters in it
  1204. * are used as call-by-reference values.
  1205. */
  1206. static char *
  1207. scan_diff_line (scan_ptr, set_start, set_length, limit, leadingchar)
  1208. char *scan_ptr, **set_start;
  1209. size_t *set_length;
  1210. char *limit;
  1211. int leadingchar;
  1212. {
  1213. char *line_ptr;
  1214. if (!(scan_ptr[0] == leadingchar
  1215. && scan_ptr[1] == ' '))
  1216. diff3_fatal ("invalid diff format; incorrect leading line chars");
  1217. *set_start = line_ptr = scan_ptr + 2;
  1218. while (*line_ptr++ != '\n')
  1219. ;
  1220. /* Include newline if the original line ended in a newline,
  1221. or if an edit script is being generated.
  1222. Copy any missing newline message to stderr if an edit script is being
  1223. generated, because edit scripts cannot handle missing newlines.
  1224. Return the beginning of the next line. */
  1225. *set_length = line_ptr - *set_start;
  1226. if (line_ptr < limit && *line_ptr == '\\')
  1227. {
  1228. if (! edscript)
  1229. {
  1230. --*set_length;
  1231. line_ptr++;
  1232. while (*line_ptr++ != '\n')
  1233. ;
  1234. }
  1235. else
  1236. {
  1237. char *serr;
  1238. line_ptr++;
  1239. serr = line_ptr;
  1240. while (*line_ptr++ != '\n')
  1241. ;
  1242. line_ptr[-1] = '\0';
  1243. diff_error ("%s", serr, 0);
  1244. line_ptr[-1] = '\n';
  1245. }
  1246. }
  1247. return line_ptr;
  1248. }
  1249. /*
  1250. * This routine outputs a three way diff passed as a list of
  1251. * diff3_block's.
  1252. * The argument MAPPING is indexed by external file number (in the
  1253. * argument list) and contains the internal file number (from the
  1254. * diff passed). This is important because the user expects his
  1255. * outputs in terms of the argument list number, and the diff passed
  1256. * may have been done slightly differently (if the last argument
  1257. * was "-", for example).
  1258. * REV_MAPPING is the inverse of MAPPING.
  1259. */
  1260. static void
  1261. output_diff3 (diff, mapping, rev_mapping)
  1262. struct diff3_block *diff;
  1263. int const mapping[3], rev_mapping[3];
  1264. {
  1265. int i;
  1266. int oddoneout;
  1267. char *cp;
  1268. struct diff3_block *ptr;
  1269. int line;
  1270. size_t length;
  1271. int dontprint;
  1272. static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1273. char const *line_prefix = tab_align_flag ? "\t" : " ";
  1274. for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1275. {
  1276. char x[2];
  1277. switch (ptr->correspond)
  1278. {
  1279. case DIFF_ALL:
  1280. x[0] = '\0';
  1281. dontprint = 3; /* Print them all */
  1282. oddoneout = 3; /* Nobody's odder than anyone else */
  1283. break;
  1284. case DIFF_1ST:
  1285. case DIFF_2ND:
  1286. case DIFF_3RD:
  1287. oddoneout = rev_mapping[(int) ptr->correspond - (int) DIFF_1ST];
  1288. x[0] = oddoneout + '1';
  1289. x[1] = '\0';
  1290. dontprint = oddoneout==0;
  1291. break;
  1292. default:
  1293. diff3_fatal ("internal error: invalid diff type passed to output");
  1294. }
  1295. printf_output ("====%s\n", x);
  1296. /* Go 0, 2, 1 if the first and third outputs are equivalent. */
  1297. for (i = 0; i < 3;
  1298. i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1299. {
  1300. int realfile = mapping[i];
  1301. int
  1302. lowt = D_LOWLINE (ptr, realfile),
  1303. hight = D_HIGHLINE (ptr, realfile);
  1304. printf_output ("%d:", i + 1);
  1305. switch (lowt - hight)
  1306. {
  1307. case 1:
  1308. printf_output ("%da\n", lowt - 1);
  1309. break;
  1310. case 0:
  1311. printf_output ("%dc\n", lowt);
  1312. break;
  1313. default:
  1314. printf_output ("%d,%dc\n", lowt, hight);
  1315. break;
  1316. }
  1317. if (i == dontprint) continue;
  1318. if (lowt <= hight)
  1319. {
  1320. line = 0;
  1321. do
  1322. {
  1323. printf_output (line_prefix);
  1324. cp = D_RELNUM (ptr, realfile, line);
  1325. length = D_RELLEN (ptr, realfile, line);
  1326. write_output (cp, length);
  1327. }
  1328. while (++line < hight - lowt + 1);
  1329. if (cp[length - 1] != '\n')
  1330. printf_output ("\n\\ No newline at end of file\n");
  1331. }
  1332. }
  1333. }
  1334. }
  1335. /*
  1336. * Output the lines of B taken from FILENUM.
  1337. * Double any initial '.'s; yield nonzero if any initial '.'s were doubled.
  1338. */
  1339. static int
  1340. dotlines (b, filenum)
  1341. struct diff3_block *b;
  1342. int filenum;
  1343. {
  1344. int i;
  1345. int leading_dot = 0;
  1346. for (i = 0;
  1347. i < D_NUMLINES (b, filenum);
  1348. i++)
  1349. {
  1350. char *line = D_RELNUM (b, filenum, i);
  1351. if (line[0] == '.')
  1352. {
  1353. leading_dot = 1;
  1354. write_output (".", 1);
  1355. }
  1356. write_output (line, D_RELLEN (b, filenum, i));
  1357. }
  1358. return leading_dot;
  1359. }
  1360. /*
  1361. * Output to OUTPUTFILE a '.' line. If LEADING_DOT is nonzero,
  1362. * also output a command that removes initial '.'s
  1363. * starting with line START and continuing for NUM lines.
  1364. */
  1365. static void
  1366. undotlines (leading_dot, start, num)
  1367. int leading_dot, start, num;
  1368. {
  1369. write_output (".\n", 2);
  1370. if (leading_dot)
  1371. if (num == 1)
  1372. printf_output ("%ds/^\\.//\n", start);
  1373. else
  1374. printf_output ("%d,%ds/^\\.//\n", start, start + num - 1);
  1375. }
  1376. /*
  1377. * This routine outputs a diff3 set of blocks as an ed script. This
  1378. * script applies the changes between file's 2 & 3 to file 1. It
  1379. * takes the precise format of the ed script to be output from global
  1380. * variables set during options processing. Note that it does
  1381. * destructive things to the set of diff3 blocks it is passed; it
  1382. * reverses their order (this gets around the problems involved with
  1383. * changing line numbers in an ed script).
  1384. *
  1385. * Note that this routine has the same problem of mapping as the last
  1386. * one did; the variable MAPPING maps from file number according to
  1387. * the argument list to file number according to the diff passed. All
  1388. * files listed below are in terms of the argument list.
  1389. * REV_MAPPING is the inverse of MAPPING.
  1390. *
  1391. * The arguments FILE0, FILE1 and FILE2 are the strings to print
  1392. * as the names of the three files. These may be the actual names,
  1393. * or may be the arguments specified with -L.
  1394. *
  1395. * Returns 1 if conflicts were found.
  1396. */
  1397. static int
  1398. output_diff3_edscript (diff, mapping, rev_mapping, file0, file1, file2)
  1399. struct diff3_block *diff;
  1400. int const mapping[3], rev_mapping[3];
  1401. char const *file0, *file1, *file2;
  1402. {
  1403. int leading_dot;
  1404. int conflicts_found = 0, conflict;
  1405. struct diff3_block *b;
  1406. for (b = reverse_diff3_blocklist (diff); b; b = b->next)
  1407. {
  1408. /* Must do mapping correctly. */
  1409. enum diff_type type
  1410. = ((b->correspond == DIFF_ALL) ?
  1411. DIFF_ALL :
  1412. ((enum diff_type)
  1413. (((int) DIFF_1ST)
  1414. + rev_mapping[(int) b->correspond - (int) DIFF_1ST])));
  1415. /* If we aren't supposed to do this output block, skip it. */
  1416. switch (type)
  1417. {
  1418. default: continue;
  1419. case DIFF_2ND: if (!show_2nd) continue; conflict = 1; break;
  1420. case DIFF_3RD: if (overlap_only) continue; conflict = 0; break;
  1421. case DIFF_ALL: if (simple_only) continue; conflict = flagging; break;
  1422. }
  1423. if (conflict)
  1424. {
  1425. conflicts_found = 1;
  1426. /* Mark end of conflict. */
  1427. printf_output ("%da\n", D_HIGHLINE (b, mapping[FILE0]));
  1428. leading_dot = 0;
  1429. if (type == DIFF_ALL)
  1430. {
  1431. if (show_2nd)
  1432. {
  1433. /* Append lines from FILE1. */
  1434. printf_output ("||||||| %s\n", file1);
  1435. leading_dot = dotlines (b, mapping[FILE1]);
  1436. }
  1437. /* Append lines from FILE2. */
  1438. printf_output ("=======\n");
  1439. leading_dot |= dotlines (b, mapping[FILE2]);
  1440. }
  1441. printf_output (">>>>>>> %s\n", file2);
  1442. undotlines (leading_dot,
  1443. D_HIGHLINE (b, mapping[FILE0]) + 2,
  1444. (D_NUMLINES (b, mapping[FILE1])
  1445. + D_NUMLINES (b, mapping[FILE2]) + 1));
  1446. /* Mark start of conflict. */
  1447. printf_output ("%da\n<<<<<<< %s\n",
  1448. D_LOWLINE (b, mapping[FILE0]) - 1,
  1449. type == DIFF_ALL ? file0 : file1);
  1450. leading_dot = 0;
  1451. if (type == DIFF_2ND)
  1452. {
  1453. /* Prepend lines from FILE1. */
  1454. leading_dot = dotlines (b, mapping[FILE1]);
  1455. printf_output ("=======\n");
  1456. }
  1457. undotlines (leading_dot,
  1458. D_LOWLINE (b, mapping[FILE0]) + 1,
  1459. D_NUMLINES (b, mapping[FILE1]));
  1460. }
  1461. else if (D_NUMLINES (b, mapping[FILE2]) == 0)
  1462. /* Write out a delete */
  1463. {
  1464. if (D_NUMLINES (b, mapping[FILE0]) == 1)
  1465. printf_output ("%dd\n", D_LOWLINE (b, mapping[FILE0]));
  1466. else
  1467. printf_output ("%d,%dd\n",
  1468. D_LOWLINE (b, mapping[FILE0]),
  1469. D_HIGHLINE (b, mapping[FILE0]));
  1470. }
  1471. else
  1472. /* Write out an add or change */
  1473. {
  1474. switch (D_NUMLINES (b, mapping[FILE0]))
  1475. {
  1476. case 0:
  1477. printf_output ("%da\n", D_HIGHLINE (b, mapping[FILE0]));
  1478. break;
  1479. case 1:
  1480. printf_output ("%dc\n", D_HIGHLINE (b, mapping[FILE0]));
  1481. break;
  1482. default:
  1483. printf_output ("%d,%dc\n",
  1484. D_LOWLINE (b, mapping[FILE0]),
  1485. D_HIGHLINE (b, mapping[FILE0]));
  1486. break;
  1487. }
  1488. undotlines (dotlines (b, mapping[FILE2]),
  1489. D_LOWLINE (b, mapping[FILE0]),
  1490. D_NUMLINES (b, mapping[FILE2]));
  1491. }
  1492. }
  1493. if (finalwrite) printf_output ("w\nq\n");
  1494. return conflicts_found;
  1495. }
  1496. /*
  1497. * Read from INFILE and output to the standard output file a set of
  1498. * diff3_ blocks DIFF as a merged file. This acts like 'ed file0
  1499. * <[output_diff3_edscript]', except that it works even for binary
  1500. * data or incomplete lines.
  1501. *
  1502. * As before, MAPPING maps from arg list file number to diff file number,
  1503. * REV_MAPPING is its inverse,
  1504. * and FILE0, FILE1, and FILE2 are the names of the files.
  1505. *
  1506. * Returns 1 if conflicts were found.
  1507. */
  1508. static int
  1509. output_diff3_merge (infile, diff, mapping, rev_mapping,
  1510. file0, file1, file2)
  1511. FILE *infile;
  1512. struct diff3_block *diff;
  1513. int const mapping[3], rev_mapping[3];
  1514. char const *file0, *file1, *file2;
  1515. {
  1516. int c, i;
  1517. char cc;
  1518. int conflicts_found = 0, conflict;
  1519. struct diff3_block *b;
  1520. int linesread = 0;
  1521. for (b = diff; b; b = b->next)
  1522. {
  1523. /* Must do mapping correctly. */
  1524. enum diff_type type
  1525. = ((b->correspond == DIFF_ALL) ?
  1526. DIFF_ALL :
  1527. ((enum diff_type)
  1528. (((int) DIFF_1ST)
  1529. + rev_mapping[(int) b->correspond - (int) DIFF_1ST])));
  1530. char const *format_2nd = "<<<<<<< %s\n";
  1531. /* If we aren't supposed to do this output block, skip it. */
  1532. switch (type)
  1533. {
  1534. default: continue;
  1535. case DIFF_2ND: if (!show_2nd) continue; conflict = 1; break;
  1536. case DIFF_3RD: if (overlap_only) continue; conflict = 0; break;
  1537. case DIFF_ALL: if (simple_only) continue; conflict = flagging;
  1538. format_2nd = "||||||| %s\n";
  1539. break;
  1540. }
  1541. /* Copy I lines from file 0. */
  1542. i = D_LOWLINE (b, FILE0) - linesread - 1;
  1543. linesread += i;
  1544. while (0 <= --i)
  1545. do
  1546. {
  1547. c = getc (infile);
  1548. if (c == EOF)
  1549. if (ferror (infile))
  1550. diff3_perror_with_exit ("input file");
  1551. else if (feof (infile))
  1552. diff3_fatal ("input file shrank");
  1553. cc = c;
  1554. write_output (&cc, 1);
  1555. }
  1556. while (c != '\n');
  1557. if (conflict)
  1558. {
  1559. conflicts_found = 1;
  1560. if (type == DIFF_ALL)
  1561. {
  1562. /* Put in lines from FILE0 with bracket. */
  1563. printf_output ("<<<<<<< %s\n", file0);
  1564. for (i = 0;
  1565. i < D_NUMLINES (b, mapping[FILE0]);
  1566. i++)
  1567. write_output (D_RELNUM (b, mapping[FILE0], i),
  1568. D_RELLEN (b, mapping[FILE0], i));
  1569. }
  1570. if (show_2nd)
  1571. {
  1572. /* Put in lines from FILE1 with bracket. */
  1573. printf_output (format_2nd, file1);
  1574. for (i = 0;
  1575. i < D_NUMLINES (b, mapping[FILE1]);
  1576. i++)
  1577. write_output (D_RELNUM (b, mapping[FILE1], i),
  1578. D_RELLEN (b, mapping[FILE1], i));
  1579. }
  1580. printf_output ("=======\n");
  1581. }
  1582. /* Put in lines from FILE2. */
  1583. for (i = 0;
  1584. i < D_NUMLINES (b, mapping[FILE2]);
  1585. i++)
  1586. write_output (D_RELNUM (b, mapping[FILE2], i),
  1587. D_RELLEN (b, mapping[FILE2], i));
  1588. if (conflict)
  1589. printf_output (">>>>>>> %s\n", file2);
  1590. /* Skip I lines in file 0. */
  1591. i = D_NUMLINES (b, FILE0);
  1592. linesread += i;
  1593. while (0 <= --i)
  1594. while ((c = getc (infile)) != '\n')
  1595. if (c == EOF)
  1596. if (ferror (infile))
  1597. diff3_perror_with_exit ("input file");
  1598. else if (feof (infile))
  1599. {
  1600. if (i || b->next)
  1601. diff3_fatal ("input file shrank");
  1602. return conflicts_found;
  1603. }
  1604. }
  1605. /* Copy rest of common file. */
  1606. while ((c = getc (infile)) != EOF || !(ferror (infile) | feof (infile)))
  1607. {
  1608. cc = c;
  1609. write_output (&cc, 1);
  1610. }
  1611. return conflicts_found;
  1612. }
  1613. /*
  1614. * Reverse the order of the list of diff3 blocks.
  1615. */
  1616. static struct diff3_block *
  1617. reverse_diff3_blocklist (diff)
  1618. struct diff3_block *diff;
  1619. {
  1620. register struct diff3_block *tmp, *next, *prev;
  1621. for (tmp = diff, prev = 0; tmp; tmp = next)
  1622. {
  1623. next = tmp->next;
  1624. tmp->next = prev;
  1625. prev = tmp;
  1626. }
  1627. return prev;
  1628. }
  1629. static size_t
  1630. myread (fd, ptr, size)
  1631. int fd;
  1632. char *ptr;
  1633. size_t size;
  1634. {
  1635. ssize_t result = read (fd, ptr, size);
  1636. if (result == -1)
  1637. diff3_perror_with_exit ("read failed");
  1638. return (size_t)result;
  1639. }
  1640. static void
  1641. diff3_fatal (string)
  1642. char const *string;
  1643. {
  1644. diff_error ("%s", string, 0);
  1645. DIFF3_ABORT (2);
  1646. }
  1647. static void
  1648. diff3_perror_with_exit (string)
  1649. char const *string;
  1650. {
  1651. perror_with_name (string);
  1652. DIFF3_ABORT (2);
  1653. }
  1654. static void
  1655. initialize_main (argcp, argvp)
  1656. int *argcp;
  1657. char ***argvp;
  1658. {
  1659. always_text = 0;
  1660. edscript = 0;
  1661. flagging = 0;
  1662. tab_align_flag = 0;
  1663. simple_only = 0;
  1664. overlap_only = 0;
  1665. show_2nd = 0;
  1666. finalwrite = 0;
  1667. merge = 0;
  1668. diff_program_name = (*argvp)[0];
  1669. outfile = NULL;
  1670. }
  1671. static void
  1672. free_diff_blocks(p)
  1673. struct diff_block *p;
  1674. {
  1675. register struct diff_block *next;
  1676. while (p)
  1677. {
  1678. next = p->next;
  1679. if (p->lines[0]) free(p->lines[0]);
  1680. if (p->lines[1]) free(p->lines[1]);
  1681. if (p->lengths[0]) free(p->lengths[0]);
  1682. if (p->lengths[1]) free(p->lengths[1]);
  1683. free(p);
  1684. p = next;
  1685. }
  1686. }
  1687. static void
  1688. free_diff3_blocks(p)
  1689. struct diff3_block *p;
  1690. {
  1691. register struct diff3_block *next;
  1692. while (p)
  1693. {
  1694. next = p->next;
  1695. if (p->lines[0]) free(p->lines[0]);
  1696. if (p->lines[1]) free(p->lines[1]);
  1697. if (p->lines[2]) free(p->lines[2]);
  1698. if (p->lengths[0]) free(p->lengths[0]);
  1699. if (p->lengths[1]) free(p->lengths[1]);
  1700. if (p->lengths[2]) free(p->lengths[2]);
  1701. free(p);
  1702. p = next;
  1703. }
  1704. }