home *** CD-ROM | disk | FTP | other *** search
/ Media Share 9 / MEDIASHARE_09.ISO / progmisc / dif115as.zip / DIFF3.C < prev    next >
C/C++ Source or Header  |  1992-02-22  |  52KB  |  1,827 lines

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