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

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