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