home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / rcs57pc3.zip / diff / diff3.c < prev    next >
C/C++ Source or Header  |  1996-03-20  |  52KB  |  1,761 lines

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