3 /* File I/O for GNU DIFF.
5 Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1998, 2001, 2002
6 Free Software Foundation, Inc.
8 This file is part of GNU DIFF.
10 GNU DIFF is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2, or (at your option)
15 GNU DIFF is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; see the file COPYING.
22 If not, write to the Free Software Foundation,
23 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
31 /* Rotate an unsigned value to the left. */
32 #define ROL(v, n) ((v) << (n) | (v) >> (sizeof (v) * CHAR_BIT - (n)))
34 /* Given a hash value and a new character, return a new hash value. */
35 #define HASH(h, c) ((c) + ROL (h, 7))
37 /* The type of a hash value. */
38 typedef size_t hash_value
;
39 verify (hash_value_is_unsigned
, ! TYPE_SIGNED (hash_value
));
41 /* Lines are put into equivalence classes of lines that match in lines_differ.
42 Each equivalence class is represented by one of these structures,
43 but only while the classes are being computed.
44 Afterward, each class is represented by a number. */
47 lin next
; /* Next item in this bucket. */
48 hash_value hash
; /* Hash of lines in this class. */
49 char const *line
; /* A line that fits this class. */
50 size_t length
; /* That line's length, not counting its newline. */
53 /* Hash-table: array of buckets, each being a chain of equivalence classes.
54 buckets[-1] is reserved for incomplete lines. */
57 /* Number of buckets in the hash table array, not counting buckets[-1]. */
58 static size_t nbuckets
;
60 /* Array in which the equivalence classes are allocated.
61 The bucket-chains go through the elements in this array.
62 The number of an equivalence class is its index in this array. */
63 static struct equivclass
*equivs
;
65 /* Index of first free element in the array `equivs'. */
66 static lin equivs_index
;
68 /* Number of elements allocated in the array `equivs'. */
69 static lin equivs_alloc
;
71 /* Read a block of data into a file buffer, checking for EOF and error. */
74 file_block_read (struct file_data
*current
, size_t size
)
76 if (size
&& ! current
->eof
)
78 size_t s
= block_read (current
->desc
,
79 FILE_BUFFER (current
) + current
->buffered
, size
);
81 pfatal_with_name (current
->name
);
82 current
->buffered
+= s
;
83 current
->eof
= s
< size
;
87 /* Check for binary files and compare them for exact identity. */
89 /* Return 1 if BUF contains a non text character.
90 SIZE is the number of characters in BUF. */
92 #define binary_file_p(buf, size) (memchr (buf, 0, size) != 0)
94 /* Get ready to read the current file.
95 Return nonzero if SKIP_TEST is zero,
96 and if it appears to be a binary file. */
99 sip (struct file_data
*current
, bool skip_test
)
101 /* If we have a nonexistent file at this stage, treat it as empty. */
102 if (current
->desc
< 0)
104 /* Leave room for a sentinel. */
105 current
->bufsize
= sizeof (word
);
106 current
->buffer
= xmalloc (current
->bufsize
);
110 current
->bufsize
= buffer_lcm (sizeof (word
),
111 STAT_BLOCKSIZE (current
->stat
),
112 PTRDIFF_MAX
- 2 * sizeof (word
));
113 current
->buffer
= xmalloc (current
->bufsize
);
117 /* Check first part of file to see if it's a binary file. */
119 bool was_binary
= set_binary_mode (current
->desc
, 1);
121 file_block_read (current
, current
->bufsize
);
122 buffered
= current
->buffered
;
126 /* Revert to text mode and seek back to the beginning to
127 reread the file. Use relative seek, since file
128 descriptors like stdin might not start at offset
131 if (lseek (current
->desc
, - buffered
, SEEK_CUR
) == -1)
132 pfatal_with_name (current
->name
);
133 set_binary_mode (current
->desc
, 0);
134 current
->buffered
= 0;
138 return binary_file_p (current
->buffer
, buffered
);
142 current
->buffered
= 0;
147 /* Slurp the rest of the current file completely into memory. */
150 slurp (struct file_data
*current
)
154 if (current
->desc
< 0)
156 /* The file is nonexistent. */
160 if (S_ISREG (current
->stat
.st_mode
))
162 /* It's a regular file; slurp in the rest all at once. */
164 /* Get the size out of the stat block.
165 Allocate just enough room for appended newline plus word sentinel,
166 plus word-alignment since we want the buffer word-aligned. */
167 size_t file_size
= current
->stat
.st_size
;
168 cc
= file_size
+ 2 * sizeof (word
) - file_size
% sizeof (word
);
169 if (file_size
!= current
->stat
.st_size
|| cc
< file_size
170 || PTRDIFF_MAX
<= cc
)
173 if (current
->bufsize
< cc
)
175 current
->bufsize
= cc
;
176 current
->buffer
= xrealloc (current
->buffer
, cc
);
179 /* Try to read at least 1 more byte than the size indicates, to
180 detect whether the file is growing. This is a nicety for
181 users who run 'diff' on files while they are changing. */
183 if (current
->buffered
<= file_size
)
185 file_block_read (current
, file_size
+ 1 - current
->buffered
);
186 if (current
->buffered
<= file_size
)
191 /* It's not a regular file, or it's a growing regular file; read it,
192 growing the buffer as needed. */
194 file_block_read (current
, current
->bufsize
- current
->buffered
);
196 if (current
->buffered
)
198 while (current
->buffered
== current
->bufsize
)
200 if (PTRDIFF_MAX
/ 2 - sizeof (word
) < current
->bufsize
)
202 current
->bufsize
*= 2;
203 current
->buffer
= xrealloc (current
->buffer
, current
->bufsize
);
204 file_block_read (current
, current
->bufsize
- current
->buffered
);
207 /* Allocate just enough room for appended newline plus word
208 sentinel, plus word-alignment. */
209 cc
= current
->buffered
+ 2 * sizeof (word
);
210 current
->bufsize
= cc
- cc
% sizeof (word
);
211 current
->buffer
= xrealloc (current
->buffer
, current
->bufsize
);
215 /* Split the file into lines, simultaneously computing the equivalence
216 class for each line. */
219 find_and_hash_each_line (struct file_data
*current
)
222 unsigned char const *p
= (unsigned char const *) current
->prefix_end
;
227 /* Cache often-used quantities in local variables to help the compiler. */
228 char const **linbuf
= current
->linbuf
;
229 lin alloc_lines
= current
->alloc_lines
;
231 lin linbuf_base
= current
->linbuf_base
;
232 lin
*cureqs
= xmalloc (alloc_lines
* sizeof *cureqs
);
233 struct equivclass
*eqs
= equivs
;
234 lin eqs_index
= equivs_index
;
235 lin eqs_alloc
= equivs_alloc
;
236 char const *suffix_begin
= current
->suffix_begin
;
237 char const *bufend
= FILE_BUFFER (current
) + current
->buffered
;
238 bool diff_length_compare_anyway
=
239 ignore_white_space
!= IGNORE_NO_WHITE_SPACE
;
240 bool same_length_diff_contents_compare_anyway
=
241 diff_length_compare_anyway
| ignore_case
;
243 while ((char const *) p
< suffix_begin
)
245 char const *ip
= (char const *) p
;
249 /* Hash this line until we find a newline. */
251 switch (ignore_white_space
)
253 case IGNORE_ALL_SPACE
:
254 while ((c
= *p
++) != '\n')
256 h
= HASH (h
, TOLOWER (c
));
259 case IGNORE_SPACE_CHANGE
:
260 while ((c
= *p
++) != '\n')
265 if ((c
= *p
++) == '\n')
272 /* C is now the first non-space. */
273 h
= HASH (h
, TOLOWER (c
));
277 case IGNORE_TAB_EXPANSION
:
280 while ((c
= *p
++) != '\n')
287 column
-= 0 < column
;
292 repetitions
= TAB_WIDTH
- column
% TAB_WIDTH
;
293 column
+= repetitions
;
308 while (--repetitions
!= 0);
314 while ((c
= *p
++) != '\n')
315 h
= HASH (h
, TOLOWER (c
));
319 switch (ignore_white_space
)
321 case IGNORE_ALL_SPACE
:
322 while ((c
= *p
++) != '\n')
327 case IGNORE_SPACE_CHANGE
:
328 while ((c
= *p
++) != '\n')
333 if ((c
= *p
++) == '\n')
340 /* C is now the first non-space. */
345 case IGNORE_TAB_EXPANSION
:
348 while ((c
= *p
++) != '\n')
355 column
-= 0 < column
;
360 repetitions
= TAB_WIDTH
- column
% TAB_WIDTH
;
361 column
+= repetitions
;
375 while (--repetitions
!= 0);
381 while ((c
= *p
++) != '\n')
388 bucket
= &buckets
[h
% nbuckets
];
389 length
= (char const *) p
- ip
- 1;
391 if ((char const *) p
== bufend
392 && current
->missing_newline
393 && ROBUST_OUTPUT_STYLE (output_style
))
395 /* This line is incomplete. If this is significant,
396 put the line into buckets[-1]. */
397 if (ignore_white_space
< IGNORE_SPACE_CHANGE
)
398 bucket
= &buckets
[-1];
400 /* Omit the inserted newline when computing linbuf later. */
402 bufend
= suffix_begin
= (char const *) p
;
405 for (i
= *bucket
; ; i
= eqs
[i
].next
)
408 /* Create a new equivalence class in this bucket. */
412 if (PTRDIFF_MAX
/ (2 * sizeof *eqs
) <= eqs_alloc
)
415 eqs
= xrealloc (eqs
, eqs_alloc
* sizeof *eqs
);
417 eqs
[i
].next
= *bucket
;
420 eqs
[i
].length
= length
;
424 else if (eqs
[i
].hash
== h
)
426 char const *eqline
= eqs
[i
].line
;
428 /* Reuse existing class if lines_differ reports the lines
430 if (eqs
[i
].length
== length
)
432 /* Reuse existing equivalence class if the lines are identical.
433 This detects the common case of exact identity
434 faster than lines_differ would. */
435 if (memcmp (eqline
, ip
, length
) == 0)
437 if (!same_length_diff_contents_compare_anyway
)
440 else if (!diff_length_compare_anyway
)
443 if (! lines_differ (eqline
, ip
))
447 /* Maybe increase the size of the line table. */
448 if (line
== alloc_lines
)
450 /* Double (alloc_lines - linbuf_base) by adding to alloc_lines. */
451 if (PTRDIFF_MAX
/ 3 <= alloc_lines
452 || PTRDIFF_MAX
/ sizeof *cureqs
<= 2 * alloc_lines
- linbuf_base
453 || PTRDIFF_MAX
/ sizeof *linbuf
<= alloc_lines
- linbuf_base
)
455 alloc_lines
= 2 * alloc_lines
- linbuf_base
;
456 cureqs
= xrealloc (cureqs
, alloc_lines
* sizeof *cureqs
);
457 linbuf
+= linbuf_base
;
458 linbuf
= xrealloc (linbuf
,
459 (alloc_lines
- linbuf_base
) * sizeof *linbuf
);
460 linbuf
-= linbuf_base
;
467 current
->buffered_lines
= line
;
471 /* Record the line start for lines in the suffix that we care about.
472 Record one more line start than lines,
473 so that we can compute the length of any buffered line. */
474 if (line
== alloc_lines
)
476 /* Double (alloc_lines - linbuf_base) by adding to alloc_lines. */
477 if (PTRDIFF_MAX
/ 3 <= alloc_lines
478 || PTRDIFF_MAX
/ sizeof *cureqs
<= 2 * alloc_lines
- linbuf_base
479 || PTRDIFF_MAX
/ sizeof *linbuf
<= alloc_lines
- linbuf_base
)
481 alloc_lines
= 2 * alloc_lines
- linbuf_base
;
482 linbuf
+= linbuf_base
;
483 linbuf
= xrealloc (linbuf
,
484 (alloc_lines
- linbuf_base
) * sizeof *linbuf
);
485 linbuf
-= linbuf_base
;
487 linbuf
[line
] = (char const *) p
;
489 if ((char const *) p
== bufend
)
492 if (context
<= i
&& no_diff_means_no_output
)
501 /* Done with cache in local variables. */
502 current
->linbuf
= linbuf
;
503 current
->valid_lines
= line
;
504 current
->alloc_lines
= alloc_lines
;
505 current
->equivs
= cureqs
;
507 equivs_alloc
= eqs_alloc
;
508 equivs_index
= eqs_index
;
511 /* Prepare the text. Make sure the text end is initialized.
512 Make sure text ends in a newline,
513 but remember that we had to add one.
514 Strip trailing CRs, if that was requested. */
517 prepare_text (struct file_data
*current
)
519 size_t buffered
= current
->buffered
;
520 char *p
= FILE_BUFFER (current
);
523 if (buffered
== 0 || p
[buffered
- 1] == '\n')
524 current
->missing_newline
= 0;
527 p
[buffered
++] = '\n';
528 current
->missing_newline
= 1;
534 /* Don't use uninitialized storage when planting or using sentinels. */
535 memset (p
+ buffered
, 0, sizeof (word
));
537 if (strip_trailing_cr
&& (dst
= memchr (p
, '\r', buffered
)))
539 char const *src
= dst
;
540 char const *srclim
= p
+ buffered
;
543 dst
+= ! ((*dst
= *src
++) == '\r' && *src
== '\n');
544 while (src
< srclim
);
546 buffered
-= src
- dst
;
549 current
->buffered
= buffered
;
552 /* We have found N lines in a buffer of size S; guess the
553 proportionate number of lines that will be found in a buffer of
554 size T. However, do not guess a number of lines so large that the
555 resulting line table might cause overflow in size calculations. */
557 guess_lines (lin n
, size_t s
, size_t t
)
559 size_t guessed_bytes_per_line
= n
< 10 ? 32 : s
/ (n
- 1);
560 lin guessed_lines
= MAX (1, t
/ guessed_bytes_per_line
);
561 return MIN (guessed_lines
, PTRDIFF_MAX
/ (2 * sizeof (char *) + 1) - 5) + 5;
564 /* Given a vector of two file_data objects, find the identical
565 prefixes and suffixes of each object. */
568 find_identical_ends (struct file_data filevec
[])
571 char *p0
, *p1
, *buffer0
, *buffer1
;
572 char const *end0
, *beg0
;
573 char const **linbuf0
, **linbuf1
;
576 lin alloc_lines0
, alloc_lines1
;
577 lin buffered_prefix
, prefix_count
, prefix_mask
;
578 lin middle_guess
, suffix_guess
;
581 prepare_text (&filevec
[0]);
582 if (filevec
[0].desc
!= filevec
[1].desc
)
585 prepare_text (&filevec
[1]);
589 filevec
[1].buffer
= filevec
[0].buffer
;
590 filevec
[1].bufsize
= filevec
[0].bufsize
;
591 filevec
[1].buffered
= filevec
[0].buffered
;
592 filevec
[1].missing_newline
= filevec
[0].missing_newline
;
595 /* Find identical prefix. */
597 w0
= filevec
[0].buffer
;
598 w1
= filevec
[1].buffer
;
599 p0
= buffer0
= (char *) w0
;
600 p1
= buffer1
= (char *) w1
;
601 n0
= filevec
[0].buffered
;
602 n1
= filevec
[1].buffered
;
605 /* The buffers are the same; sentinels won't work. */
609 /* Insert end sentinels, in this case characters that are guaranteed
610 to make the equality test false, and thus terminate the loop. */
617 /* Loop until first mismatch, or to the sentinel characters. */
619 /* Compare a word at a time for speed. */
623 /* Do the last few bytes of comparison a byte at a time. */
629 /* Don't mistakenly count missing newline as part of prefix. */
630 if (ROBUST_OUTPUT_STYLE (output_style
)
631 && ((buffer0
+ n0
- filevec
[0].missing_newline
< p0
)
633 (buffer1
+ n1
- filevec
[1].missing_newline
< p1
)))
637 /* Now P0 and P1 point at the first nonmatching characters. */
639 /* Skip back to last line-beginning in the prefix,
640 and then discard up to HORIZON_LINES lines from the prefix. */
642 while (p0
!= buffer0
&& (p0
[-1] != '\n' || i
--))
645 /* Record the prefix. */
646 filevec
[0].prefix_end
= p0
;
647 filevec
[1].prefix_end
= p1
;
649 /* Find identical suffix. */
651 /* P0 and P1 point beyond the last chars not yet compared. */
655 if (! ROBUST_OUTPUT_STYLE (output_style
)
656 || filevec
[0].missing_newline
== filevec
[1].missing_newline
)
658 end0
= p0
; /* Addr of last char in file 0. */
660 /* Get value of P0 at which we should stop scanning backward:
661 this is when either P0 or P1 points just past the last char
662 of the identical prefix. */
663 beg0
= filevec
[0].prefix_end
+ (n0
< n1
? 0 : n0
- n1
);
665 /* Scan back until chars don't match or we reach that point. */
666 for (; p0
!= beg0
; p0
--, p1
--)
669 /* Point at the first char of the matching suffix. */
674 /* Are we at a line-beginning in both files? If not, add the rest of
675 this line to the main body. Discard up to HORIZON_LINES lines from
676 the identical suffix. Also, discard one extra line,
677 because shift_boundaries may need it. */
678 i
= horizon_lines
+ !((buffer0
== p0
|| p0
[-1] == '\n')
680 (buffer1
== p1
|| p1
[-1] == '\n'));
681 while (i
-- && p0
!= end0
)
682 while (*p0
++ != '\n')
688 /* Record the suffix. */
689 filevec
[0].suffix_begin
= p0
;
690 filevec
[1].suffix_begin
= p1
;
692 /* Calculate number of lines of prefix to save.
694 prefix_count == 0 means save the whole prefix;
695 we need this for options like -D that output the whole file,
696 or for enormous contexts (to avoid worrying about arithmetic overflow).
697 We also need it for options like -F that output some preceding line;
698 at least we will need to find the last few lines,
699 but since we don't know how many, it's easiest to find them all.
701 Otherwise, prefix_count != 0. Save just prefix_count lines at start
702 of the line buffer; they'll be moved to the proper location later.
703 Handle 1 more line than the context says (because we count 1 too many),
704 rounded up to the next power of 2 to speed index computation. */
706 if (no_diff_means_no_output
&& ! function_regexp
.fastmap
707 && context
< LIN_MAX
/ 4 && context
< n0
)
709 middle_guess
= guess_lines (0, 0, p0
- filevec
[0].prefix_end
);
710 suffix_guess
= guess_lines (0, 0, buffer0
+ n0
- p0
);
711 for (prefix_count
= 1; prefix_count
<= context
; prefix_count
*= 2)
713 alloc_lines0
= (prefix_count
+ middle_guess
714 + MIN (context
, suffix_guess
));
719 alloc_lines0
= guess_lines (0, 0, n0
);
722 prefix_mask
= prefix_count
- 1;
724 linbuf0
= xmalloc (alloc_lines0
* sizeof *linbuf0
);
727 /* If the prefix is needed, find the prefix lines. */
728 if (! (no_diff_means_no_output
729 && filevec
[0].prefix_end
== p0
730 && filevec
[1].prefix_end
== p1
))
732 end0
= filevec
[0].prefix_end
;
735 lin l
= lines
++ & prefix_mask
;
736 if (l
== alloc_lines0
)
738 if (PTRDIFF_MAX
/ (2 * sizeof *linbuf0
) <= alloc_lines0
)
741 linbuf0
= xrealloc (linbuf0
, alloc_lines0
* sizeof *linbuf0
);
744 while (*p0
++ != '\n')
748 buffered_prefix
= prefix_count
&& context
< lines
? context
: lines
;
750 /* Allocate line buffer 1. */
752 middle_guess
= guess_lines (lines
, p0
- buffer0
, p1
- filevec
[1].prefix_end
);
753 suffix_guess
= guess_lines (lines
, p0
- buffer0
, buffer1
+ n1
- p1
);
754 alloc_lines1
= buffered_prefix
+ middle_guess
+ MIN (context
, suffix_guess
);
755 if (alloc_lines1
< buffered_prefix
756 || PTRDIFF_MAX
/ sizeof *linbuf1
<= alloc_lines1
)
758 linbuf1
= xmalloc (alloc_lines1
* sizeof *linbuf1
);
760 if (buffered_prefix
!= lines
)
762 /* Rotate prefix lines to proper location. */
763 for (i
= 0; i
< buffered_prefix
; i
++)
764 linbuf1
[i
] = linbuf0
[(lines
- context
+ i
) & prefix_mask
];
765 for (i
= 0; i
< buffered_prefix
; i
++)
766 linbuf0
[i
] = linbuf1
[i
];
769 /* Initialize line buffer 1 from line buffer 0. */
770 for (i
= 0; i
< buffered_prefix
; i
++)
771 linbuf1
[i
] = linbuf0
[i
] - buffer0
+ buffer1
;
773 /* Record the line buffer, adjusted so that
774 linbuf[0] points at the first differing line. */
775 filevec
[0].linbuf
= linbuf0
+ buffered_prefix
;
776 filevec
[1].linbuf
= linbuf1
+ buffered_prefix
;
777 filevec
[0].linbuf_base
= filevec
[1].linbuf_base
= - buffered_prefix
;
778 filevec
[0].alloc_lines
= alloc_lines0
- buffered_prefix
;
779 filevec
[1].alloc_lines
= alloc_lines1
- buffered_prefix
;
780 filevec
[0].prefix_lines
= filevec
[1].prefix_lines
= lines
;
783 /* If 1 < k, then (2**k - prime_offset[k]) is the largest prime less
784 than 2**k. This table is derived from Chris K. Caldwell's list
785 <http://www.utm.edu/research/primes/lists/2small/>. */
787 static unsigned char const prime_offset
[] =
789 0, 0, 1, 1, 3, 1, 3, 1, 5, 3, 3, 9, 3, 1, 3, 19, 15, 1, 5, 1, 3, 9, 3,
790 15, 3, 39, 5, 39, 57, 3, 35, 1, 5, 9, 41, 31, 5, 25, 45, 7, 87, 21,
791 11, 57, 17, 55, 21, 115, 59, 81, 27, 129, 47, 111, 33, 55, 5, 13, 27,
795 /* Verify that this host's size_t is not too wide for the above table. */
797 verify (enough_prime_offsets
,
798 sizeof (size_t) * CHAR_BIT
<= sizeof prime_offset
);
800 /* Given a vector of two file_data objects, read the file associated
801 with each one, and build the table of equivalence classes.
802 Return nonzero if either file appears to be a binary file.
803 If PRETEND_BINARY is nonzero, pretend they are binary regardless. */
806 read_files (struct file_data filevec
[], bool pretend_binary
)
809 bool skip_test
= text
| pretend_binary
;
810 bool appears_binary
= pretend_binary
| sip (&filevec
[0], skip_test
);
812 if (filevec
[0].desc
!= filevec
[1].desc
)
813 appears_binary
|= sip (&filevec
[1], skip_test
| appears_binary
);
816 filevec
[1].buffer
= filevec
[0].buffer
;
817 filevec
[1].bufsize
= filevec
[0].bufsize
;
818 filevec
[1].buffered
= filevec
[0].buffered
;
822 set_binary_mode (filevec
[0].desc
, 1);
823 set_binary_mode (filevec
[1].desc
, 1);
827 find_identical_ends (filevec
);
829 equivs_alloc
= filevec
[0].alloc_lines
+ filevec
[1].alloc_lines
+ 1;
830 if (PTRDIFF_MAX
/ sizeof *equivs
<= equivs_alloc
)
832 equivs
= xmalloc (equivs_alloc
* sizeof *equivs
);
833 /* Equivalence class 0 is permanently safe for lines that were not
834 hashed. Real equivalence classes start at 1. */
837 /* Allocate (one plus) a prime number of hash buckets. Use a prime
838 number between 1/3 and 2/3 of the value of equiv_allocs,
840 for (i
= 9; (size_t) 1 << i
< equivs_alloc
/ 3; i
++)
842 nbuckets
= ((size_t) 1 << i
) - prime_offset
[i
];
843 if (PTRDIFF_MAX
/ sizeof *buckets
<= nbuckets
)
845 buckets
= zalloc ((nbuckets
+ 1) * sizeof *buckets
);
848 for (i
= 0; i
< 2; i
++)
849 find_and_hash_each_line (&filevec
[i
]);
851 filevec
[0].equiv_max
= filevec
[1].equiv_max
= equivs_index
;