diff3.c 49 KB

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