1 /* File I/O for GNU DIFF.
3 Copyright (C) 1988-1989, 1992-1995, 1998, 2001-2002, 2004, 2006, 2009-2013
4 Free Software Foundation, Inc.
6 This file is part of GNU DIFF.
8 This program is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include <binary-io.h>
24 #include <file-type.h>
27 /* Rotate an unsigned value to the left. */
28 #define ROL(v, n) ((v) << (n) | (v) >> (sizeof (v) * CHAR_BIT - (n)))
30 /* Given a hash value and a new character, return a new hash value. */
31 #define HASH(h, c) ((c) + ROL (h, 7))
33 /* The type of a hash value. */
34 typedef size_t hash_value;
35 verify (! TYPE_SIGNED (hash_value));
37 /* Lines are put into equivalence classes of lines that match in lines_differ.
38 Each equivalence class is represented by one of these structures,
39 but only while the classes are being computed.
40 Afterward, each class is represented by a number. */
43 lin next; /* Next item in this bucket. */
44 hash_value hash; /* Hash of lines in this class. */
45 char const *line; /* A line that fits this class. */
46 size_t length; /* That line's length, not counting its newline. */
49 /* Hash-table: array of buckets, each being a chain of equivalence classes.
50 buckets[-1] is reserved for incomplete lines. */
53 /* Number of buckets in the hash table array, not counting buckets[-1]. */
54 static size_t nbuckets;
56 /* Array in which the equivalence classes are allocated.
57 The bucket-chains go through the elements in this array.
58 The number of an equivalence class is its index in this array. */
59 static struct equivclass *equivs;
61 /* Index of first free element in the array 'equivs'. */
62 static lin equivs_index;
64 /* Number of elements allocated in the array 'equivs'. */
65 static lin equivs_alloc;
67 /* Read a block of data into a file buffer, checking for EOF and error. */
70 file_block_read (struct file_data *current, size_t size)
72 if (size && ! current->eof)
74 size_t s = block_read (current->desc,
75 FILE_BUFFER (current) + current->buffered, size);
77 pfatal_with_name (current->name);
78 current->buffered += s;
79 current->eof = s < size;
83 /* Check for binary files and compare them for exact identity. */
85 /* Return 1 if BUF contains a non text character.
86 SIZE is the number of characters in BUF. */
88 #define binary_file_p(buf, size) (memchr (buf, 0, size) != 0)
90 /* Get ready to read the current file.
91 Return nonzero if SKIP_TEST is zero,
92 and if it appears to be a binary file. */
95 sip (struct file_data *current, bool skip_test)
97 /* If we have a nonexistent file at this stage, treat it as empty. */
98 if (current->desc < 0)
100 /* Leave room for a sentinel. */
101 current->bufsize = sizeof (word);
102 current->buffer = xmalloc (current->bufsize);
106 current->bufsize = buffer_lcm (sizeof (word),
107 STAT_BLOCKSIZE (current->stat),
108 PTRDIFF_MAX - 2 * sizeof (word));
109 current->buffer = xmalloc (current->bufsize);
113 /* Check first part of file to see if it's a binary file. */
115 int prev_mode = set_binary_mode (current->desc, O_BINARY);
117 file_block_read (current, current->bufsize);
118 buffered = current->buffered;
120 if (prev_mode != O_BINARY)
122 /* Revert to text mode and seek back to the start to reread
123 the file. Use relative seek, since file descriptors
124 like stdin might not start at offset zero. */
125 if (lseek (current->desc, - buffered, SEEK_CUR) < 0)
126 pfatal_with_name (current->name);
127 set_binary_mode (current->desc, prev_mode);
128 current->buffered = 0;
129 current->eof = false;
132 return binary_file_p (current->buffer, buffered);
136 current->buffered = 0;
137 current->eof = false;
141 /* Slurp the rest of the current file completely into memory. */
144 slurp (struct file_data *current)
148 if (current->desc < 0)
150 /* The file is nonexistent. */
154 if (S_ISREG (current->stat.st_mode))
156 /* It's a regular file; slurp in the rest all at once. */
158 /* Get the size out of the stat block.
159 Allocate just enough room for appended newline plus word sentinel,
160 plus word-alignment since we want the buffer word-aligned. */
161 size_t file_size = current->stat.st_size;
162 cc = file_size + 2 * sizeof (word) - file_size % sizeof (word);
163 if (file_size != current->stat.st_size || cc < file_size
164 || PTRDIFF_MAX <= cc)
167 if (current->bufsize < cc)
169 current->bufsize = cc;
170 current->buffer = xrealloc (current->buffer, cc);
173 /* Try to read at least 1 more byte than the size indicates, to
174 detect whether the file is growing. This is a nicety for
175 users who run 'diff' on files while they are changing. */
177 if (current->buffered <= file_size)
179 file_block_read (current, file_size + 1 - current->buffered);
180 if (current->buffered <= file_size)
185 /* It's not a regular file, or it's a growing regular file; read it,
186 growing the buffer as needed. */
188 file_block_read (current, current->bufsize - current->buffered);
190 if (current->buffered)
192 while (current->buffered == current->bufsize)
194 if (PTRDIFF_MAX / 2 - sizeof (word) < current->bufsize)
196 current->bufsize *= 2;
197 current->buffer = xrealloc (current->buffer, current->bufsize);
198 file_block_read (current, current->bufsize - current->buffered);
201 /* Allocate just enough room for appended newline plus word
202 sentinel, plus word-alignment. */
203 cc = current->buffered + 2 * sizeof (word);
204 current->bufsize = cc - cc % sizeof (word);
205 current->buffer = xrealloc (current->buffer, current->bufsize);
209 /* Split the file into lines, simultaneously computing the equivalence
210 class for each line. */
213 find_and_hash_each_line (struct file_data *current)
215 char const *p = current->prefix_end;
219 /* Cache often-used quantities in local variables to help the compiler. */
220 char const **linbuf = current->linbuf;
221 lin alloc_lines = current->alloc_lines;
223 lin linbuf_base = current->linbuf_base;
224 lin *cureqs = xmalloc (alloc_lines * sizeof *cureqs);
225 struct equivclass *eqs = equivs;
226 lin eqs_index = equivs_index;
227 lin eqs_alloc = equivs_alloc;
228 char const *suffix_begin = current->suffix_begin;
229 char const *bufend = FILE_BUFFER (current) + current->buffered;
230 bool ig_case = ignore_case;
231 enum DIFF_white_space ig_white_space = ignore_white_space;
232 bool diff_length_compare_anyway =
233 ig_white_space != IGNORE_NO_WHITE_SPACE;
234 bool same_length_diff_contents_compare_anyway =
235 diff_length_compare_anyway | ig_case;
237 while (p < suffix_begin)
243 /* Hash this line until we find a newline. */
244 switch (ig_white_space)
246 case IGNORE_ALL_SPACE:
247 while ((c = *p++) != '\n')
249 h = HASH (h, ig_case ? tolower (c) : c);
252 case IGNORE_SPACE_CHANGE:
253 while ((c = *p++) != '\n')
258 if ((c = *p++) == '\n')
265 /* C is now the first non-space. */
266 h = HASH (h, ig_case ? tolower (c) : c);
270 case IGNORE_TAB_EXPANSION:
271 case IGNORE_TAB_EXPANSION_AND_TRAILING_SPACE:
272 case IGNORE_TRAILING_SPACE:
275 while ((c = *p++) != '\n')
277 if (ig_white_space & IGNORE_TRAILING_SPACE
283 if ((c1 = *p1++) == '\n')
288 while (isspace (c1));
291 size_t repetitions = 1;
293 if (ig_white_space & IGNORE_TAB_EXPANSION)
297 column -= 0 < column;
302 repetitions = tabsize - column % tabsize;
303 column = (column + repetitions < column
305 : column + repetitions);
322 while (--repetitions != 0);
329 while ((c = *p++) != '\n')
330 h = HASH (h, tolower (c));
332 while ((c = *p++) != '\n')
339 bucket = &buckets[h % nbuckets];
343 && current->missing_newline
344 && ROBUST_OUTPUT_STYLE (output_style))
346 /* The last line is incomplete and we do not silently
347 complete lines. If the line cannot compare equal to any
348 complete line, put it into buckets[-1] so that it can
349 compare equal only to the other file's incomplete line
351 if (ig_white_space < IGNORE_TRAILING_SPACE)
352 bucket = &buckets[-1];
355 for (i = *bucket; ; i = eqs[i].next)
358 /* Create a new equivalence class in this bucket. */
362 if (PTRDIFF_MAX / (2 * sizeof *eqs) <= eqs_alloc)
365 eqs = xrealloc (eqs, eqs_alloc * sizeof *eqs);
367 eqs[i].next = *bucket;
370 eqs[i].length = length;
374 else if (eqs[i].hash == h)
376 char const *eqline = eqs[i].line;
378 /* Reuse existing class if lines_differ reports the lines
380 if (eqs[i].length == length)
382 /* Reuse existing equivalence class if the lines are identical.
383 This detects the common case of exact identity
384 faster than lines_differ would. */
385 if (memcmp (eqline, ip, length) == 0)
387 if (!same_length_diff_contents_compare_anyway)
390 else if (!diff_length_compare_anyway)
393 if (! lines_differ (eqline, ip))
397 /* Maybe increase the size of the line table. */
398 if (line == alloc_lines)
400 /* Double (alloc_lines - linbuf_base) by adding to alloc_lines. */
401 if (PTRDIFF_MAX / 3 <= alloc_lines
402 || PTRDIFF_MAX / sizeof *cureqs <= 2 * alloc_lines - linbuf_base
403 || PTRDIFF_MAX / sizeof *linbuf <= alloc_lines - linbuf_base)
405 alloc_lines = 2 * alloc_lines - linbuf_base;
406 cureqs = xrealloc (cureqs, alloc_lines * sizeof *cureqs);
407 linbuf += linbuf_base;
408 linbuf = xrealloc (linbuf,
409 (alloc_lines - linbuf_base) * sizeof *linbuf);
410 linbuf -= linbuf_base;
417 current->buffered_lines = line;
421 /* Record the line start for lines in the suffix that we care about.
422 Record one more line start than lines,
423 so that we can compute the length of any buffered line. */
424 if (line == alloc_lines)
426 /* Double (alloc_lines - linbuf_base) by adding to alloc_lines. */
427 if (PTRDIFF_MAX / 3 <= alloc_lines
428 || PTRDIFF_MAX / sizeof *cureqs <= 2 * alloc_lines - linbuf_base
429 || PTRDIFF_MAX / sizeof *linbuf <= alloc_lines - linbuf_base)
431 alloc_lines = 2 * alloc_lines - linbuf_base;
432 linbuf += linbuf_base;
433 linbuf = xrealloc (linbuf,
434 (alloc_lines - linbuf_base) * sizeof *linbuf);
435 linbuf -= linbuf_base;
441 /* If the last line is incomplete and we do not silently
442 complete lines, don't count its appended newline. */
443 if (current->missing_newline && ROBUST_OUTPUT_STYLE (output_style))
448 if (context <= i && no_diff_means_no_output)
457 /* Done with cache in local variables. */
458 current->linbuf = linbuf;
459 current->valid_lines = line;
460 current->alloc_lines = alloc_lines;
461 current->equivs = cureqs;
463 equivs_alloc = eqs_alloc;
464 equivs_index = eqs_index;
467 /* Prepare the text. Make sure the text end is initialized.
468 Make sure text ends in a newline,
469 but remember that we had to add one.
470 Strip trailing CRs, if that was requested. */
473 prepare_text (struct file_data *current)
475 size_t buffered = current->buffered;
476 char *p = FILE_BUFFER (current);
479 if (buffered == 0 || p[buffered - 1] == '\n')
480 current->missing_newline = false;
483 p[buffered++] = '\n';
484 current->missing_newline = true;
490 /* Don't use uninitialized storage when planting or using sentinels. */
491 memset (p + buffered, 0, sizeof (word));
493 if (strip_trailing_cr && (dst = memchr (p, '\r', buffered)))
495 char const *src = dst;
496 char const *srclim = p + buffered;
499 dst += ! ((*dst = *src++) == '\r' && *src == '\n');
500 while (src < srclim);
502 buffered -= src - dst;
505 current->buffered = buffered;
508 /* We have found N lines in a buffer of size S; guess the
509 proportionate number of lines that will be found in a buffer of
510 size T. However, do not guess a number of lines so large that the
511 resulting line table might cause overflow in size calculations. */
513 guess_lines (lin n, size_t s, size_t t)
515 size_t guessed_bytes_per_line = n < 10 ? 32 : s / (n - 1);
516 lin guessed_lines = MAX (1, t / guessed_bytes_per_line);
517 return MIN (guessed_lines, PTRDIFF_MAX / (2 * sizeof (char *) + 1) - 5) + 5;
520 /* Given a vector of two file_data objects, find the identical
521 prefixes and suffixes of each object. */
524 find_identical_ends (struct file_data filevec[])
527 char *p0, *p1, *buffer0, *buffer1;
528 char const *end0, *beg0;
529 char const **linbuf0, **linbuf1;
532 lin alloc_lines0, alloc_lines1;
533 lin buffered_prefix, prefix_count, prefix_mask;
534 lin middle_guess, suffix_guess;
537 prepare_text (&filevec[0]);
538 if (filevec[0].desc != filevec[1].desc)
541 prepare_text (&filevec[1]);
545 filevec[1].buffer = filevec[0].buffer;
546 filevec[1].bufsize = filevec[0].bufsize;
547 filevec[1].buffered = filevec[0].buffered;
548 filevec[1].missing_newline = filevec[0].missing_newline;
551 /* Find identical prefix. */
553 w0 = filevec[0].buffer;
554 w1 = filevec[1].buffer;
555 p0 = buffer0 = (char *) w0;
556 p1 = buffer1 = (char *) w1;
557 n0 = filevec[0].buffered;
558 n1 = filevec[1].buffered;
561 /* The buffers are the same; sentinels won't work. */
565 /* Insert end sentinels, in this case characters that are guaranteed
566 to make the equality test false, and thus terminate the loop. */
573 /* Loop until first mismatch, or to the sentinel characters. */
575 /* Compare a word at a time for speed. */
579 /* Do the last few bytes of comparison a byte at a time. */
585 /* Don't mistakenly count missing newline as part of prefix. */
586 if (ROBUST_OUTPUT_STYLE (output_style)
587 && ((buffer0 + n0 - filevec[0].missing_newline < p0)
589 (buffer1 + n1 - filevec[1].missing_newline < p1)))
593 /* Now P0 and P1 point at the first nonmatching characters. */
595 /* Skip back to last line-beginning in the prefix,
596 and then discard up to HORIZON_LINES lines from the prefix. */
598 while (p0 != buffer0 && (p0[-1] != '\n' || i--))
601 /* Record the prefix. */
602 filevec[0].prefix_end = p0;
603 filevec[1].prefix_end = p1;
605 /* Find identical suffix. */
607 /* P0 and P1 point beyond the last chars not yet compared. */
611 if (! ROBUST_OUTPUT_STYLE (output_style)
612 || filevec[0].missing_newline == filevec[1].missing_newline)
614 end0 = p0; /* Addr of last char in file 0. */
616 /* Get value of P0 at which we should stop scanning backward:
617 this is when either P0 or P1 points just past the last char
618 of the identical prefix. */
619 beg0 = filevec[0].prefix_end + (n0 < n1 ? 0 : n0 - n1);
621 /* Scan back until chars don't match or we reach that point. */
625 /* Point at the first char of the matching suffix. */
631 /* Are we at a line-beginning in both files? If not, add the rest of
632 this line to the main body. Discard up to HORIZON_LINES lines from
633 the identical suffix. Also, discard one extra line,
634 because shift_boundaries may need it. */
635 i = horizon_lines + !((buffer0 == p0 || p0[-1] == '\n')
637 (buffer1 == p1 || p1[-1] == '\n'));
638 while (i-- && p0 != end0)
639 while (*p0++ != '\n')
645 /* Record the suffix. */
646 filevec[0].suffix_begin = p0;
647 filevec[1].suffix_begin = p1;
649 /* Calculate number of lines of prefix to save.
651 prefix_count == 0 means save the whole prefix;
652 we need this for options like -D that output the whole file,
653 or for enormous contexts (to avoid worrying about arithmetic overflow).
654 We also need it for options like -F that output some preceding line;
655 at least we will need to find the last few lines,
656 but since we don't know how many, it's easiest to find them all.
658 Otherwise, prefix_count != 0. Save just prefix_count lines at start
659 of the line buffer; they'll be moved to the proper location later.
660 Handle 1 more line than the context says (because we count 1 too many),
661 rounded up to the next power of 2 to speed index computation. */
663 if (no_diff_means_no_output && ! function_regexp.fastmap
664 && context < LIN_MAX / 4 && context < n0)
666 middle_guess = guess_lines (0, 0, p0 - filevec[0].prefix_end);
667 suffix_guess = guess_lines (0, 0, buffer0 + n0 - p0);
668 for (prefix_count = 1; prefix_count <= context; prefix_count *= 2)
670 alloc_lines0 = (prefix_count + middle_guess
671 + MIN (context, suffix_guess));
676 alloc_lines0 = guess_lines (0, 0, n0);
679 prefix_mask = prefix_count - 1;
681 linbuf0 = xmalloc (alloc_lines0 * sizeof *linbuf0);
684 /* If the prefix is needed, find the prefix lines. */
685 if (! (no_diff_means_no_output
686 && filevec[0].prefix_end == p0
687 && filevec[1].prefix_end == p1))
689 end0 = filevec[0].prefix_end;
692 lin l = lines++ & prefix_mask;
693 if (l == alloc_lines0)
695 if (PTRDIFF_MAX / (2 * sizeof *linbuf0) <= alloc_lines0)
698 linbuf0 = xrealloc (linbuf0, alloc_lines0 * sizeof *linbuf0);
701 while (*p0++ != '\n')
705 buffered_prefix = prefix_count && context < lines ? context : lines;
707 /* Allocate line buffer 1. */
709 middle_guess = guess_lines (lines, p0 - buffer0, p1 - filevec[1].prefix_end);
710 suffix_guess = guess_lines (lines, p0 - buffer0, buffer1 + n1 - p1);
711 alloc_lines1 = buffered_prefix + middle_guess + MIN (context, suffix_guess);
712 if (alloc_lines1 < buffered_prefix
713 || PTRDIFF_MAX / sizeof *linbuf1 <= alloc_lines1)
715 linbuf1 = xmalloc (alloc_lines1 * sizeof *linbuf1);
717 if (buffered_prefix != lines)
719 /* Rotate prefix lines to proper location. */
720 for (i = 0; i < buffered_prefix; i++)
721 linbuf1[i] = linbuf0[(lines - context + i) & prefix_mask];
722 for (i = 0; i < buffered_prefix; i++)
723 linbuf0[i] = linbuf1[i];
726 /* Initialize line buffer 1 from line buffer 0. */
727 for (i = 0; i < buffered_prefix; i++)
728 linbuf1[i] = linbuf0[i] - buffer0 + buffer1;
730 /* Record the line buffer, adjusted so that
731 linbuf[0] points at the first differing line. */
732 filevec[0].linbuf = linbuf0 + buffered_prefix;
733 filevec[1].linbuf = linbuf1 + buffered_prefix;
734 filevec[0].linbuf_base = filevec[1].linbuf_base = - buffered_prefix;
735 filevec[0].alloc_lines = alloc_lines0 - buffered_prefix;
736 filevec[1].alloc_lines = alloc_lines1 - buffered_prefix;
737 filevec[0].prefix_lines = filevec[1].prefix_lines = lines;
740 /* If 1 < k, then (2**k - prime_offset[k]) is the largest prime less
741 than 2**k. This table is derived from Chris K. Caldwell's list
742 <http://www.utm.edu/research/primes/lists/2small/>. */
744 static unsigned char const prime_offset[] =
746 0, 0, 1, 1, 3, 1, 3, 1, 5, 3, 3, 9, 3, 1, 3, 19, 15, 1, 5, 1, 3, 9, 3,
747 15, 3, 39, 5, 39, 57, 3, 35, 1, 5, 9, 41, 31, 5, 25, 45, 7, 87, 21,
748 11, 57, 17, 55, 21, 115, 59, 81, 27, 129, 47, 111, 33, 55, 5, 13, 27,
752 /* Verify that this host's size_t is not too wide for the above table. */
754 verify (sizeof (size_t) * CHAR_BIT <= sizeof prime_offset);
756 /* Given a vector of two file_data objects, read the file associated
757 with each one, and build the table of equivalence classes.
758 Return nonzero if either file appears to be a binary file.
759 If PRETEND_BINARY is nonzero, pretend they are binary regardless. */
762 read_files (struct file_data filevec[], bool pretend_binary)
765 bool skip_test = text | pretend_binary;
766 bool appears_binary = pretend_binary | sip (&filevec[0], skip_test);
768 if (filevec[0].desc != filevec[1].desc)
769 appears_binary |= sip (&filevec[1], skip_test | appears_binary);
772 filevec[1].buffer = filevec[0].buffer;
773 filevec[1].bufsize = filevec[0].bufsize;
774 filevec[1].buffered = filevec[0].buffered;
778 set_binary_mode (filevec[0].desc, O_BINARY);
779 set_binary_mode (filevec[1].desc, O_BINARY);
783 find_identical_ends (filevec);
785 equivs_alloc = filevec[0].alloc_lines + filevec[1].alloc_lines + 1;
786 if (PTRDIFF_MAX / sizeof *equivs <= equivs_alloc)
788 equivs = xmalloc (equivs_alloc * sizeof *equivs);
789 /* Equivalence class 0 is permanently safe for lines that were not
790 hashed. Real equivalence classes start at 1. */
793 /* Allocate (one plus) a prime number of hash buckets. Use a prime
794 number between 1/3 and 2/3 of the value of equiv_allocs,
796 for (i = 9; (size_t) 1 << i < equivs_alloc / 3; i++)
798 nbuckets = ((size_t) 1 << i) - prime_offset[i];
799 if (PTRDIFF_MAX / sizeof *buckets <= nbuckets)
801 buckets = zalloc ((nbuckets + 1) * sizeof *buckets);
804 for (i = 0; i < 2; i++)
805 find_and_hash_each_line (&filevec[i]);
807 filevec[0].equiv_max = filevec[1].equiv_max = equivs_index;