home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / rcs / sources / diff3.c < prev    next >
C/C++ Source or Header  |  1991-09-30  |  50KB  |  1,757 lines

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