Debian Codegraph @

src/diff.c

raw
1 /* GNU diff - compare files line by line
2
3 Copyright (C) 1988-1989, 1992-1994, 1996, 1998, 2001-2002, 2004, 2006-2007,
4 2009-2013, 2015-2025 Free Software Foundation, Inc.
5
6 This file is part of GNU DIFF.
7
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.
12
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.
17
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/>. */
20
21 #define DIFF_INLINE _GL_EXTERN_INLINE
22 #include "diff.h"
23 #include "paths.h"
24
25 #include <binary-io.h>
26 #include <c-ctype.h>
27 #include <c-stack.h>
28 #include <careadlinkat.h>
29 #include <diagnose.h>
30 #include <dirname.h>
31 #include <error.h>
32 #include <exclude.h>
33 #include <exitfail.h>
34 #include <file-type.h>
35 #include <filenamecat.h>
36 #include <fnmatch.h>
37 #include <getopt.h>
38 #include <hard-locale.h>
39 #include <progname.h>
40 #include <quote.h>
41 #include <sh-quote.h>
42 #include <stat-time.h>
43 #include <version-etc.h>
44 #include <xalloc.h>
45 #include <xstdopen.h>
46
47 #ifdef MAJOR_IN_MKDEV
48 # include <sys/mkdev.h>
49 #elif defined MAJOR_IN_SYSMACROS
50 # include <sys/sysmacros.h>
51 #elif !defined major /* Might be defined in sys/types.h. */
52 # define major(dev) (((dev) >> 8) & 0xff)
53 # define minor(dev) ((dev) & 0xff)
54 #endif
55
56 /* The official name of this program (e.g., no 'g' prefix). */
57 static char const PROGRAM_NAME[] = "diff";
58
59 #define AUTHORS \
60 _("Paul Eggert"), \
61 _("Mike Haertel"), \
62 _("David Hayes"), \
63 _("Richard Stallman"), \
64 _("Len Tower")
65
66 #ifndef GUTTER_WIDTH_MINIMUM
67 # define GUTTER_WIDTH_MINIMUM 3
68 #endif
69
70 struct regexp_list
71 {
72 char *regexps; /* chars representing disjunction of the regexps */
73 idx_t len; /* chars used in 'regexps' */
74 idx_t size; /* size malloc'ed for 'regexps'; 0 if not malloc'ed */
75 bool multiple_regexps;/* Does 'regexps' represent a disjunction? */
76 struct re_pattern_buffer *buf;
77 };
78
79 static void add_regexp (struct regexp_list *, char const *);
80 static void summarize_regexp_list (struct regexp_list *);
81 static void specify_style (enum output_style);
82 static void specify_value (char const **, char const *, char const *);
83 static void specify_colors_style (char const *);
84 static void check_stdout (void);
85 static void usage (void);
86
87 /* If comparing directories, compare their common subdirectories
88 recursively. */
89 static bool recursive;
90
91 /* In context diffs, show previous lines that match these regexps. */
92 static struct regexp_list function_regexp_list;
93
94 /* Ignore changes affecting only lines that match these regexps. */
95 static struct regexp_list ignore_regexp_list;
96
97 #if O_BINARY
98 /* Use binary I/O when reading and writing data (--binary).
99 On POSIX hosts, this has no effect. */
100 static bool binary;
101 #else
102 enum { binary = true };
103 #endif
104
105 /* Use Linux-style O_PATH if available and supported by fstat(),
106 POSIX-style O_SEARCH otherwise. */
107 #if O_PATH_SUPPORTS_FSTAT
108 enum { O_PATH_DEFINED = true };
109 enum { O_PATHSEARCH = O_PATH };
110 #else
111 enum { O_PATH_DEFINED = false };
112 enum { O_PATHSEARCH = O_SEARCH };
113 #endif
114
115 /* If one file is missing, treat it as present but empty (-N). */
116 static bool new_file;
117
118 /* If the first file is missing, treat it as present but empty
119 (--unidirectional-new-file). */
120 static bool unidirectional_new_file;
121
122 /* Report files compared that are the same (-s).
123 Normally nothing is output when that happens. */
124 static bool report_identical_files;
125
126 /* Do not treat directories specially. */
127 static bool no_directory;
128
129 /* Values for long options that do not have single-letter equivalents. */
130 enum
131 {
132 BINARY_OPTION = CHAR_MAX + 1,
133 FROM_FILE_OPTION,
134 HELP_OPTION,
135 HORIZON_LINES_OPTION,
136 IGNORE_FILE_NAME_CASE_OPTION,
137 INHIBIT_HUNK_MERGE_OPTION,
138 LEFT_COLUMN_OPTION,
139 LINE_FORMAT_OPTION,
140 NO_DEREFERENCE_OPTION,
141 NO_IGNORE_FILE_NAME_CASE_OPTION,
142 NORMAL_OPTION,
143 SDIFF_MERGE_ASSIST_OPTION,
144 STRIP_TRAILING_CR_OPTION,
145 SUPPRESS_BLANK_EMPTY_OPTION,
146 SUPPRESS_COMMON_LINES_OPTION,
147 TABSIZE_OPTION,
148 TO_FILE_OPTION,
149
150 /* These options must be in sequence. */
151 UNCHANGED_LINE_FORMAT_OPTION,
152 OLD_LINE_FORMAT_OPTION,
153 NEW_LINE_FORMAT_OPTION,
154
155 /* These options must be in sequence. */
156 UNCHANGED_GROUP_FORMAT_OPTION,
157 OLD_GROUP_FORMAT_OPTION,
158 NEW_GROUP_FORMAT_OPTION,
159 CHANGED_GROUP_FORMAT_OPTION,
160
161 COLOR_OPTION,
162 COLOR_PALETTE_OPTION,
163
164 NO_DIRECTORY_OPTION,
165 PRESUME_OUTPUT_TTY_OPTION,
166 };
167
168 static char const group_format_option[][sizeof "--unchanged-group-format"] =
169 {
170 "--unchanged-group-format",
171 "--old-group-format",
172 "--new-group-format",
173 "--changed-group-format"
174 };
175
176 static char const line_format_option[][sizeof "--unchanged-line-format"] =
177 {
178 "--unchanged-line-format",
179 "--old-line-format",
180 "--new-line-format"
181 };
182
183 static char const shortopts[] =
184 "0123456789abBcC:dD:eEfF:hHiI:lL:nNpPqrsS:tTuU:vwW:x:X:yZ";
185 static struct option const longopts[] =
186 {
187 {"binary", 0, 0, BINARY_OPTION},
188 {"brief", 0, 0, 'q'},
189 {"changed-group-format", 1, 0, CHANGED_GROUP_FORMAT_OPTION},
190 {"color", 2, 0, COLOR_OPTION},
191 {"context", 2, 0, 'C'},
192 {"ed", 0, 0, 'e'},
193 {"exclude", 1, 0, 'x'},
194 {"exclude-from", 1, 0, 'X'},
195 {"expand-tabs", 0, 0, 't'},
196 {"forward-ed", 0, 0, 'f'},
197 {"from-file", 1, 0, FROM_FILE_OPTION},
198 {"help", 0, 0, HELP_OPTION},
199 {"horizon-lines", 1, 0, HORIZON_LINES_OPTION},
200 {"ifdef", 1, 0, 'D'},
201 {"ignore-all-space", 0, 0, 'w'},
202 {"ignore-blank-lines", 0, 0, 'B'},
203 {"ignore-case", 0, 0, 'i'},
204 {"ignore-file-name-case", 0, 0, IGNORE_FILE_NAME_CASE_OPTION},
205 {"ignore-matching-lines", 1, 0, 'I'},
206 {"ignore-space-change", 0, 0, 'b'},
207 {"ignore-tab-expansion", 0, 0, 'E'},
208 {"ignore-trailing-space", 0, 0, 'Z'},
209 {"inhibit-hunk-merge", 0, 0, INHIBIT_HUNK_MERGE_OPTION},
210 {"initial-tab", 0, 0, 'T'},
211 {"label", 1, 0, 'L'},
212 {"left-column", 0, 0, LEFT_COLUMN_OPTION},
213 {"line-format", 1, 0, LINE_FORMAT_OPTION},
214 {"minimal", 0, 0, 'd'},
215 {"new-file", 0, 0, 'N'},
216 {"new-group-format", 1, 0, NEW_GROUP_FORMAT_OPTION},
217 {"new-line-format", 1, 0, NEW_LINE_FORMAT_OPTION},
218 {"no-dereference", 0, 0, NO_DEREFERENCE_OPTION},
219 {"no-ignore-file-name-case", 0, 0, NO_IGNORE_FILE_NAME_CASE_OPTION},
220 {"normal", 0, 0, NORMAL_OPTION},
221 {"old-group-format", 1, 0, OLD_GROUP_FORMAT_OPTION},
222 {"old-line-format", 1, 0, OLD_LINE_FORMAT_OPTION},
223 {"paginate", 0, 0, 'l'},
224 {"palette", 1, 0, COLOR_PALETTE_OPTION},
225 {"rcs", 0, 0, 'n'},
226 {"recursive", 0, 0, 'r'},
227 {"report-identical-files", 0, 0, 's'},
228 {"sdiff-merge-assist", 0, 0, SDIFF_MERGE_ASSIST_OPTION},
229 {"show-c-function", 0, 0, 'p'},
230 {"show-function-line", 1, 0, 'F'},
231 {"side-by-side", 0, 0, 'y'},
232 {"speed-large-files", 0, 0, 'H'},
233 {"starting-file", 1, 0, 'S'},
234 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
235 {"suppress-blank-empty", 0, 0, SUPPRESS_BLANK_EMPTY_OPTION},
236 {"suppress-common-lines", 0, 0, SUPPRESS_COMMON_LINES_OPTION},
237 {"tabsize", 1, 0, TABSIZE_OPTION},
238 {"text", 0, 0, 'a'},
239 {"to-file", 1, 0, TO_FILE_OPTION},
240 {"unchanged-group-format", 1, 0, UNCHANGED_GROUP_FORMAT_OPTION},
241 {"unchanged-line-format", 1, 0, UNCHANGED_LINE_FORMAT_OPTION},
242 {"unidirectional-new-file", 0, 0, 'P'},
243 {"unified", 2, 0, 'U'},
244 {"version", 0, 0, 'v'},
245 {"width", 1, 0, 'W'},
246
247 /* This is solely for diff3. Do not document. */
248 {"-no-directory", no_argument, nullptr, NO_DIRECTORY_OPTION},
249
250 /* This is solely for testing. Do not document. */
251 {"-presume-output-tty", no_argument, nullptr, PRESUME_OUTPUT_TTY_OPTION},
252 {0, 0, 0, 0}
253 };
254
255 /* Return a string containing the command options with which diff was invoked.
256 Spaces appear between what were separate ARGV-elements.
257 There is a space at the beginning but none at the end.
258 If there were no options, the result is an empty string.
259
260 Arguments: OPTIONVEC, a vector containing separate ARGV-elements, and COUNT,
261 the length of that vector. */
262
263 static char *
264 option_list (char **optionvec, int count)
265 {
266 idx_t size = 1;
267
268 for (int i = 0; i < count; i++)
269 {
270 size_t optsize = 1 + shell_quote_length (optionvec[i]);
271 if (ckd_add (&size, size, optsize))
272 xalloc_die ();
273 }
274
275 char *result = ximalloc (size);
276 char *p = result;
277
278 for (int i = 0; i < count; i++)
279 {
280 *p++ = ' ';
281 p = shell_quote_copy (p, optionvec[i]);
282 }
283
284 *p = '\0';
285 return result;
286 }
287
288
289 /* Return an option value suitable for add_exclude. */
290
291 static int
292 exclude_options (void)
293 {
294 return EXCLUDE_WILDCARDS | (ignore_file_name_case ? FNM_CASEFOLD : 0);
295 }
296
297 int
298 main (int argc, char **argv)
299 {
300 /* Do our initializations. */
301 exit_failure = EXIT_TROUBLE;
302 initialize_main (&argc, &argv);
303 set_program_name (argv[0]);
304 setlocale (LC_ALL, "");
305 bindtextdomain (PACKAGE, LOCALEDIR);
306 bindtextdomain ("gnulib", GNULIB_LOCALEDIR);
307 textdomain (PACKAGE);
308 c_stack_action (nullptr);
309 function_regexp_list.buf = &function_regexp;
310 ignore_regexp_list.buf = &ignore_regexp;
311 re_set_syntax (RE_SYNTAX_GREP | RE_NO_POSIX_BACKTRACKING);
312 excluded = new_exclude ();
313 presume_output_tty = false;
314 xstdopen ();
315
316 /* Parse command line options. */
317
318 lin ocontext = -1;
319 bool explicit_context = false;
320 intmax_t width = 0;
321 bool show_c_function = false;
322 char const *from_file = nullptr;
323 char const *to_file = nullptr;
324
325 for (int prev = -1, c;
326 0 <= (c = getopt_long (argc, argv, shortopts, longopts, nullptr));
327 prev = c)
328 switch (c)
329 {
330 case 0:
331 break;
332
333 case '0':
334 case '1':
335 case '2':
336 case '3':
337 case '4':
338 case '5':
339 case '6':
340 case '7':
341 case '8':
342 case '9':
343 if (! c_isdigit (prev))
344 ocontext = 0;
345 if (ckd_mul (&ocontext, ocontext, 10)
346 || ckd_add (&ocontext, ocontext, c - '0'))
347 ocontext = LIN_MAX;
348 break;
349
350 case 'a':
351 text = true;
352 break;
353
354 case 'b':
355 if (ignore_white_space < IGNORE_SPACE_CHANGE)
356 ignore_white_space = IGNORE_SPACE_CHANGE;
357 break;
358
359 case 'Z':
360 if (ignore_white_space < IGNORE_SPACE_CHANGE)
361 ignore_white_space |= IGNORE_TRAILING_SPACE;
362 break;
363
364 case 'B':
365 ignore_blank_lines = true;
366 break;
367
368 case 'C':
369 case 'U':
370 {
371 intmax_t numval;
372
373 if (optarg)
374 {
375 char *numend;
376 numval = strtoimax (optarg, &numend, 10);
377 if (*numend || numval < 0)
378 try_help ("invalid context length %s", quote (optarg));
379 }
380 else
381 numval = 3;
382
383 specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
384 if (context < numval)
385 context = MIN (numval, LIN_MAX);
386 explicit_context = true;
387 }
388 break;
389
390 case 'c':
391 specify_style (OUTPUT_CONTEXT);
392 if (context < 3)
393 context = 3;
394 break;
395
396 case 'd':
397 minimal = true;
398 break;
399
400 case 'D':
401 specify_style (OUTPUT_IFDEF);
402 {
403 static char const C_ifdef_group_formats[]
404 = (/* UNCHANGED */
405 "%="
406 "\0"
407
408 /* OLD */
409 "#ifndef @\n"
410 "%<"
411 "#endif /* ! @ */\n"
412 "\0"
413
414 /* NEW */
415 "#ifdef @\n"
416 "%>"
417 "#endif /* @ */\n"
418 "\0"
419
420 /* CHANGED */
421 "#ifndef @\n"
422 "%<"
423 "#else /* @ */\n"
424 "%>"
425 "#endif /* @ */\n");
426 int nats = 7; /* 7 "@"s are in C_ifdef_group_formats. */
427
428 char *b = xinmalloc (((sizeof C_ifdef_group_formats + 1) / nats
429 + strlen (optarg)),
430 nats);
431 char *base = b;
432 int changes = 0;
433
434 for (int i = 0; i < sizeof C_ifdef_group_formats; i++)
435 {
436 char ch = C_ifdef_group_formats[i];
437 switch (ch)
438 {
439 default:
440 *b++ = ch;
441 break;
442
443 case '@':
444 b = stpcpy (b, optarg);
445 break;
446
447 case '\0':
448 *b++ = ch;
449 specify_value (&group_format[changes++], base, "-D");
450 base = b;
451 break;
452 }
453 }
454 }
455 break;
456
457 case 'e':
458 specify_style (OUTPUT_ED);
459 break;
460
461 case 'E':
462 if (ignore_white_space < IGNORE_SPACE_CHANGE)
463 ignore_white_space |= IGNORE_TAB_EXPANSION;
464 break;
465
466 case 'f':
467 specify_style (OUTPUT_FORWARD_ED);
468 break;
469
470 case 'F':
471 add_regexp (&function_regexp_list, optarg);
472 break;
473
474 case 'h':
475 /* Split the files into chunks for faster processing.
476 Usually does not change the result.
477
478 This currently has no effect. */
479 break;
480
481 case 'H':
482 speed_large_files = true;
483 break;
484
485 case 'i':
486 ignore_case = true;
487 break;
488
489 case 'I':
490 add_regexp (&ignore_regexp_list, optarg);
491 break;
492
493 case 'l':
494 if (!pr_program[0])
495 try_help ("pagination not supported on this host", nullptr);
496 paginate = true;
497 #ifdef SIGCHLD
498 /* Pagination requires forking and waiting, and
499 System V fork+wait does not work if SIGCHLD is ignored. */
500 signal (SIGCHLD, SIG_DFL);
501 #endif
502 break;
503
504 case 'L':
505 if (!file_label[0])
506 file_label[0] = optarg;
507 else if (!file_label[1])
508 file_label[1] = optarg;
509 else
510 fatal ("too many file label options");
511 break;
512
513 case 'n':
514 specify_style (OUTPUT_RCS);
515 break;
516
517 case 'N':
518 new_file = true;
519 break;
520
521 case 'p':
522 show_c_function = true;
523 add_regexp (&function_regexp_list, "^[[:alpha:]$_]");
524 break;
525
526 case 'P':
527 unidirectional_new_file = true;
528 break;
529
530 case 'q':
531 brief = true;
532 break;
533
534 case 'r':
535 recursive = true;
536 break;
537
538 case 's':
539 report_identical_files = true;
540 break;
541
542 case 'S':
543 specify_value (&starting_file, optarg, "-S");
544 break;
545
546 case 't':
547 expand_tabs = true;
548 break;
549
550 case 'T':
551 initial_tab = true;
552 break;
553
554 case 'u':
555 specify_style (OUTPUT_UNIFIED);
556 if (context < 3)
557 context = 3;
558 break;
559
560 case 'v':
561 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version,
562 AUTHORS, nullptr);
563 check_stdout ();
564 return EXIT_SUCCESS;
565
566 case 'w':
567 ignore_white_space = IGNORE_ALL_SPACE;
568 break;
569
570 case 'x':
571 add_exclude (excluded, optarg, exclude_options ());
572 break;
573
574 case 'X':
575 if (add_exclude_file (add_exclude, excluded, optarg,
576 exclude_options (), '\n'))
577 pfatal_with_name (optarg);
578 break;
579
580 case 'y':
581 specify_style (OUTPUT_SDIFF);
582 break;
583
584 case 'W':
585 {
586 char *numend;
587 intmax_t numval = strtoimax (optarg, &numend, 10);
588 if (numval <= 0 || *numend)
589 try_help ("invalid width %s", quote (optarg));
590 if (width != numval)
591 {
592 if (width)
593 fatal ("conflicting width options");
594 width = numval;
595 }
596 }
597 break;
598
599 case BINARY_OPTION:
600 #if O_BINARY
601 binary = true;
602 if (! isatty (STDOUT_FILENO))
603 set_binary_mode (STDOUT_FILENO, O_BINARY);
604 #endif
605 break;
606
607 case FROM_FILE_OPTION:
608 specify_value (&from_file, optarg, "--from-file");
609 break;
610
611 case HELP_OPTION:
612 usage ();
613 check_stdout ();
614 return EXIT_SUCCESS;
615
616 case HORIZON_LINES_OPTION:
617 {
618 char *numend;
619 intmax_t numval = strtoimax (optarg, &numend, 10);
620 if (*numend || numval < 0)
621 try_help ("invalid horizon length %s", quote (optarg));
622 horizon_lines = MAX (horizon_lines, MIN (numval, LIN_MAX));
623 }
624 break;
625
626 case IGNORE_FILE_NAME_CASE_OPTION:
627 ignore_file_name_case = true;
628 break;
629
630 case INHIBIT_HUNK_MERGE_OPTION:
631 /* This option is obsolete, but accept it for backward
632 compatibility. */
633 break;
634
635 case LEFT_COLUMN_OPTION:
636 left_column = true;
637 break;
638
639 case LINE_FORMAT_OPTION:
640 specify_style (OUTPUT_IFDEF);
641 for (int i = 0; i < sizeof line_format / sizeof line_format[0]; i++)
642 specify_value (&line_format[i], optarg, "--line-format");
643 break;
644
645 case NO_DEREFERENCE_OPTION:
646 no_dereference_symlinks = true;
647 break;
648
649 case NO_IGNORE_FILE_NAME_CASE_OPTION:
650 ignore_file_name_case = false;
651 break;
652
653 case NORMAL_OPTION:
654 specify_style (OUTPUT_NORMAL);
655 break;
656
657 case SDIFF_MERGE_ASSIST_OPTION:
658 specify_style (OUTPUT_SDIFF);
659 sdiff_merge_assist = true;
660 break;
661
662 case STRIP_TRAILING_CR_OPTION:
663 strip_trailing_cr = true;
664 break;
665
666 case SUPPRESS_BLANK_EMPTY_OPTION:
667 suppress_blank_empty = true;
668 break;
669
670 case SUPPRESS_COMMON_LINES_OPTION:
671 suppress_common_lines = true;
672 break;
673
674 case TABSIZE_OPTION:
675 {
676 char *numend;
677 intmax_t numval = strtoimax (optarg, &numend, 10);
678 if (! (0 < numval && numval <= INTMAX_MAX - GUTTER_WIDTH_MINIMUM)
679 || *numend)
680 try_help ("invalid tabsize %s", quote (optarg));
681 if (tabsize != numval)
682 {
683 if (tabsize)
684 fatal ("conflicting tabsize options");
685 tabsize = numval;
686 }
687 }
688 break;
689
690 case TO_FILE_OPTION:
691 specify_value (&to_file, optarg, "--to-file");
692 break;
693
694 case UNCHANGED_LINE_FORMAT_OPTION:
695 case OLD_LINE_FORMAT_OPTION:
696 case NEW_LINE_FORMAT_OPTION:
697 specify_style (OUTPUT_IFDEF);
698 c -= UNCHANGED_LINE_FORMAT_OPTION;
699 specify_value (&line_format[c], optarg, line_format_option[c]);
700 break;
701
702 case UNCHANGED_GROUP_FORMAT_OPTION:
703 case OLD_GROUP_FORMAT_OPTION:
704 case NEW_GROUP_FORMAT_OPTION:
705 case CHANGED_GROUP_FORMAT_OPTION:
706 specify_style (OUTPUT_IFDEF);
707 c -= UNCHANGED_GROUP_FORMAT_OPTION;
708 specify_value (&group_format[c], optarg, group_format_option[c]);
709 break;
710
711 case COLOR_OPTION:
712 specify_colors_style (optarg);
713 break;
714
715 case COLOR_PALETTE_OPTION:
716 set_color_palette (optarg);
717 break;
718
719 case NO_DIRECTORY_OPTION:
720 no_directory = true;
721 break;
722
723 case PRESUME_OUTPUT_TTY_OPTION:
724 presume_output_tty = true;
725 break;
726
727 default:
728 try_help (nullptr, nullptr);
729 }
730
731 if (colors_style == AUTO)
732 {
733 char const *t = getenv ("TERM");
734 if (t && STREQ (t, "dumb"))
735 colors_style = NEVER;
736 }
737
738 if (output_style == OUTPUT_UNSPECIFIED)
739 {
740 if (show_c_function)
741 {
742 specify_style (OUTPUT_CONTEXT);
743 if (ocontext < 0)
744 context = 3;
745 }
746 else
747 specify_style (OUTPUT_NORMAL);
748 }
749
750 if (output_style != OUTPUT_CONTEXT || hard_locale (LC_TIME))
751 {
752 #if defined STAT_TIMESPEC || defined STAT_TIMESPEC_NS
753 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
754 #else
755 time_format = "%Y-%m-%d %H:%M:%S %z";
756 #endif
757 #if !HAVE_TM_GMTOFF
758 localtz = tzalloc (getenv ("TZ"));
759 #endif
760 }
761 else
762 {
763 /* See POSIX 1003.1-2017 for this format. */
764 time_format = "%a %b %e %T %Y";
765 }
766
767 if (0 <= ocontext
768 && (output_style == OUTPUT_CONTEXT
769 || output_style == OUTPUT_UNIFIED)
770 && (context < ocontext
771 || (ocontext < context && ! explicit_context)))
772 context = ocontext;
773
774 if (! tabsize)
775 tabsize = 8;
776 if (! width)
777 width = 130;
778
779 {
780 /* Maximize first the half line width, and then the gutter width,
781 according to the following constraints:
782
783 1. Two half lines plus a gutter must fit in a line.
784 2. If the half line width is nonzero:
785 a. The gutter width is at least GUTTER_WIDTH_MINIMUM.
786 b. If tabs are not expanded to spaces,
787 a half line plus a gutter is an integral number of tabs,
788 so that tabs in the right column line up. */
789
790 intmax_t t = expand_tabs ? 1 : tabsize;
791 intmax_t w = width;
792 intmax_t t_plus_g = t + GUTTER_WIDTH_MINIMUM;
793 intmax_t unaligned_off = (w >> 1) + (t_plus_g >> 1) + (w & t_plus_g & 1);
794 intmax_t off = unaligned_off - unaligned_off % t;
795 sdiff_half_width = MAX (0, MIN (off - GUTTER_WIDTH_MINIMUM, w - off));
796 sdiff_column2_offset = sdiff_half_width ? off : w;
797 }
798
799 /* Make the horizon at least as large as the context, so that
800 shift_boundaries has more freedom to shift the first and last hunks. */
801 if (horizon_lines < context)
802 horizon_lines = context;
803
804 summarize_regexp_list (&function_regexp_list);
805 summarize_regexp_list (&ignore_regexp_list);
806
807 if (output_style == OUTPUT_IFDEF)
808 {
809 for (int i = 0; i < sizeof line_format / sizeof line_format[0]; i++)
810 if (!line_format[i])
811 line_format[i] = "%l\n";
812 if (!group_format[OLD])
813 group_format[OLD]
814 = group_format[CHANGED] ? group_format[CHANGED] : "%<";
815 if (!group_format[NEW])
816 group_format[NEW]
817 = group_format[CHANGED] ? group_format[CHANGED] : "%>";
818 if (!group_format[UNCHANGED])
819 group_format[UNCHANGED] = "%=";
820 if (!group_format[CHANGED])
821 {
822 char *p = xmalloc (strlen (group_format[OLD])
823 + strlen (group_format[NEW]) + 1);
824 group_format[CHANGED] = p;
825 strcpy (stpcpy (p, group_format[OLD]), group_format[NEW]);
826 }
827 }
828
829 no_diff_means_no_output =
830 (output_style == OUTPUT_IFDEF ?
831 (!*group_format[UNCHANGED]
832 || (STREQ (group_format[UNCHANGED], "%=")
833 && !*line_format[UNCHANGED]))
834 : (output_style != OUTPUT_SDIFF) | suppress_common_lines);
835
836 files_can_be_treated_as_binary =
837 (brief & binary
838 & ~ (ignore_blank_lines | ignore_case | strip_trailing_cr
839 | (ignore_regexp_list.regexps || ignore_white_space)));
840
841 switch_string = option_list (argv + 1, optind - 1);
842
843 int exit_status = EXIT_SUCCESS;
844
845 noparent.file[0].desc = AT_FDCWD;
846 noparent.file[1].desc = AT_FDCWD;
847 static enum detype const de_unknowns[] = {DE_UNKNOWN, DE_UNKNOWN};
848
849 if (from_file)
850 {
851 if (to_file)
852 fatal ("--from-file and --to-file both specified");
853 else
854 for (; optind < argc; optind++)
855 {
856 int status = compare_files (&noparent, de_unknowns,
857 from_file, argv[optind]);
858 if (exit_status < status)
859 exit_status = status;
860 }
861 }
862 else
863 {
864 if (to_file)
865 for (; optind < argc; optind++)
866 {
867 int status = compare_files (&noparent, de_unknowns,
868 argv[optind], to_file);
869 if (exit_status < status)
870 exit_status = status;
871 }
872 else
873 {
874 if (argc - optind != 2)
875 {
876 if (argc - optind < 2)
877 try_help ("missing operand after %s", quote (argv[argc - 1]));
878 else
879 try_help ("extra operand %s", quote (argv[optind + 2]));
880 }
881
882 exit_status = compare_files (&noparent, de_unknowns,
883 argv[optind], argv[optind + 1]);
884 }
885 }
886
887 /* Print any messages that were saved up for last. */
888 print_message_queue ();
889
890 check_stdout ();
891 cleanup_signal_handlers ();
892 return exit_status;
893 }
894
895 /* Append to REGLIST the regexp PATTERN. */
896
897 static void
898 add_regexp (struct regexp_list *reglist, char const *pattern)
899 {
900 idx_t patlen = strlen (pattern);
901 char const *m = re_compile_pattern (pattern, patlen, reglist->buf);
902
903 if (m != 0)
904 error (EXIT_TROUBLE, 0, "%s: %s", squote (0, pattern), m);
905 else
906 {
907 char *regexps = reglist->regexps;
908 idx_t len = reglist->len;
909 bool multiple_regexps = reglist->multiple_regexps = regexps != 0;
910 idx_t newlen = reglist->len = len + 2 * multiple_regexps + patlen;
911 idx_t size = reglist->size;
912
913 if (size <= newlen)
914 regexps = reglist->regexps = xpalloc (regexps, &reglist->size,
915 newlen - size + 1, -1, 1);
916 if (multiple_regexps)
917 {
918 regexps[len++] = '\\';
919 regexps[len++] = '|';
920 }
921 memcpy (regexps + len, pattern, patlen + 1);
922 }
923 }
924
925 /* Ensure that REGLIST represents the disjunction of its regexps.
926 This is done here, rather than earlier, to avoid O(N^2) behavior. */
927
928 static void
929 summarize_regexp_list (struct regexp_list *reglist)
930 {
931 if (reglist->regexps)
932 {
933 /* At least one regexp was specified. Allocate a fastmap for it. */
934 reglist->buf->fastmap = xmalloc (1 << CHAR_BIT);
935 if (reglist->multiple_regexps)
936 {
937 /* Compile the disjunction of the regexps.
938 (If just one regexp was specified, it is already compiled.) */
939 char const *m = re_compile_pattern (reglist->regexps, reglist->len,
940 reglist->buf);
941 if (m)
942 error (EXIT_TROUBLE, 0, "%s: %s",
943 squote (0, reglist->regexps), m);
944 }
945 }
946 }
947
948 /* Get the value of errno after a system call fails,
949 and help the compiler by telling it that errno is positive. */
950 static int
951 get_errno (void)
952 {
953 int err = errno;
954 dassert (0 < err);
955 return err;
956 }
957
958 static void
959 check_stdout (void)
960 {
961 if (ferror (stdout))
962 fatal ("write failed");
963 else if (fclose (stdout) != 0)
964 pfatal_with_name (_("standard output"));
965 }
966
967 static char const *const option_help_msgid[] = {
968 N_(" --normal output a normal diff (the default)"),
969 N_("-q, --brief report only when files differ"),
970 N_("-s, --report-identical-files report when two files are the same"),
971 N_("-c, -C NUM, --context[=NUM] output NUM (default 3) lines of copied context"),
972 N_("-u, -U NUM, --unified[=NUM] output NUM (default 3) lines of unified context"),
973 N_("-e, --ed output an ed script"),
974 N_("-n, --rcs output an RCS format diff"),
975 N_("-y, --side-by-side output in two columns"),
976 N_("-W, --width=NUM output at most NUM (default 130) print columns"),
977 N_(" --left-column output only the left column of common lines"),
978 N_(" --suppress-common-lines do not output common lines"),
979 "",
980 N_("-p, --show-c-function show which C function each change is in"),
981 N_("-F, --show-function-line=RE show the most recent line matching RE"),
982 N_(" --label LABEL use LABEL instead of file name and timestamp\n"
983 " (can be repeated)"),
984 "",
985 N_("-t, --expand-tabs expand tabs to spaces in output"),
986 N_("-T, --initial-tab make tabs line up by prepending a tab"),
987 N_(" --tabsize=NUM tab stops every NUM (default 8) print columns"),
988 N_(" --suppress-blank-empty suppress space or tab before empty output lines"),
989 N_("-l, --paginate pass output through 'pr' to paginate it"),
990 "",
991 N_("-r, --recursive recursively compare any subdirectories found"),
992 N_(" --no-dereference don't follow symbolic links"),
993 N_("-N, --new-file treat absent files as empty"),
994 N_(" --unidirectional-new-file treat absent first files as empty"),
995 N_(" --ignore-file-name-case ignore case when comparing file names"),
996 N_(" --no-ignore-file-name-case consider case when comparing file names"),
997 N_("-x, --exclude=PAT exclude files that match PAT"),
998 N_("-X, --exclude-from=FILE exclude files that match any pattern in FILE"),
999 N_("-S, --starting-file=FILE start with FILE when comparing directories"),
1000 N_(" --from-file=FILE1 compare FILE1 to all operands;\n"
1001 " FILE1 can be a directory"),
1002 N_(" --to-file=FILE2 compare all operands to FILE2;\n"
1003 " FILE2 can be a directory"),
1004 "",
1005 N_("-i, --ignore-case ignore case differences in file contents"),
1006 N_("-E, --ignore-tab-expansion ignore changes due to tab expansion"),
1007 N_("-Z, --ignore-trailing-space ignore white space at line end"),
1008 N_("-b, --ignore-space-change ignore changes in the amount of white space"),
1009 N_("-w, --ignore-all-space ignore all white space"),
1010 N_("-B, --ignore-blank-lines ignore changes where lines are all blank"),
1011 N_("-I, --ignore-matching-lines=RE ignore changes where all lines match RE"),
1012 "",
1013 N_("-a, --text treat all files as text"),
1014 N_(" --strip-trailing-cr strip trailing carriage return on input"),
1015 #if O_BINARY
1016 N_(" --binary read and write data in binary mode"),
1017 #endif
1018 "",
1019 N_("-D, --ifdef=NAME output merged file with '#ifdef NAME' diffs"),
1020 N_(" --GTYPE-group-format=GFMT format GTYPE input groups with GFMT"),
1021 N_(" --line-format=LFMT format all input lines with LFMT"),
1022 N_(" --LTYPE-line-format=LFMT format LTYPE input lines with LFMT"),
1023 N_(" These format options provide fine-grained control over the output\n"
1024 " of diff, generalizing -D/--ifdef."),
1025 N_(" LTYPE is 'old', 'new', or 'unchanged'. GTYPE is LTYPE or 'changed'."),
1026 N_(" GFMT (only) may contain:\n\
1027 %< lines from FILE1\n\
1028 %> lines from FILE2\n\
1029 %= lines common to FILE1 and FILE2\n\
1030 %[-][WIDTH][.[PREC]]{doxX}LETTER printf-style spec for LETTER\n\
1031 LETTERs are as follows for new group, lower case for old group:\n\
1032 F first line number\n\
1033 L last line number\n\
1034 N number of lines = L-F+1\n\
1035 E F-1\n\
1036 M L+1\n\
1037 %(A=B?T:E) if A equals B then T else E"),
1038 N_(" LFMT (only) may contain:\n\
1039 %L contents of line\n\
1040 %l contents of line, excluding any trailing newline\n\
1041 %[-][WIDTH][.[PREC]]{doxX}n printf-style spec for input line number"),
1042 N_(" Both GFMT and LFMT may contain:\n\
1043 %% %\n\
1044 %c'C' the single character C\n\
1045 %c'\\OOO' the character with octal code OOO\n\
1046 C the character C (other characters represent themselves)"),
1047 "",
1048 N_("-d, --minimal try hard to find a smaller set of changes"),
1049 N_(" --horizon-lines=NUM keep NUM lines of the common prefix and suffix"),
1050 N_(" --speed-large-files assume large files and many scattered small changes"),
1051 N_(" --color[=WHEN] color output; WHEN is 'never', 'always', or 'auto';\n"
1052 " plain --color means --color='auto'"),
1053 N_(" --palette=PALETTE the colors to use when --color is active; PALETTE is\n"
1054 " a colon-separated list of terminfo capabilities"),
1055 "",
1056 N_(" --help display this help and exit"),
1057 N_("-v, --version output version information and exit"),
1058 "",
1059 N_("FILES are 'FILE1 FILE2' or 'DIR1 DIR2' or 'DIR FILE' or 'FILE DIR'."),
1060 N_("If --from-file or --to-file is given, there are no restrictions on FILE(s)."),
1061 N_("If a FILE is '-', read standard input."),
1062 N_("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."),
1063 nullptr
1064 };
1065
1066 static void
1067 usage (void)
1068 {
1069 printf (_("Usage: %s [OPTION]... FILES\n"), squote (0, program_name));
1070 printf ("%s\n\n", _("Compare FILES line by line."));
1071
1072 fputs (_("\
1073 Mandatory arguments to long options are mandatory for short options too.\n\
1074 "), stdout);
1075
1076 for (char const *const *p = option_help_msgid; *p; p++)
1077 {
1078 if (!**p)
1079 putchar ('\n');
1080 else
1081 {
1082 char const *msg = _(*p);
1083 for (char const *nl; (nl = strchr (msg, '\n')); msg = nl + 1)
1084 {
1085 fputs (" ", stdout);
1086 fwrite (msg, 1, nl + 1 - msg, stdout);
1087 }
1088
1089 if (*msg == ' ' || *msg == '-')
1090 fputs (" ", stdout);
1091 puts (msg);
1092 }
1093 }
1094 emit_bug_reporting_address ();
1095 }
1096
1097 /* Set VAR to VALUE, reporting an OPTION error if this is a
1098 conflict. */
1099 static void
1100 specify_value (char const **var, char const *value, char const *option)
1101 {
1102 if (*var && ! STREQ (*var, value))
1103 {
1104 error (0, 0, _("conflicting %s option value %s"), option, quote (value));
1105 try_help (nullptr, nullptr);
1106 }
1107 *var = value;
1108 }
1109
1110 /* Set the output style to STYLE, diagnosing conflicts. */
1111 static void
1112 specify_style (enum output_style style)
1113 {
1114 if (output_style != style)
1115 {
1116 if (output_style != OUTPUT_UNSPECIFIED)
1117 try_help ("conflicting output style options", nullptr);
1118 output_style = style;
1119 }
1120 }
1121
1122 /* Set the color mode. */
1123 static void
1124 specify_colors_style (char const *value)
1125 {
1126 if (value == nullptr || STREQ (value, "auto"))
1127 colors_style = AUTO;
1128 else if (STREQ (value, "always"))
1129 colors_style = ALWAYS;
1130 else if (STREQ (value, "never"))
1131 colors_style = NEVER;
1132 else
1133 try_help ("invalid color %s", quote (value));
1134 }
1135
1136
1137 /* True if PCMP's file F is a directory. */
1138 static bool
1139 dir_p (struct comparison const *pcmp, int f)
1140 {
1141 return S_ISDIR (pcmp->file[f].stat.st_mode) != 0;
1142 }
1143
1144 /* If openat with O_NOFOLLOW fails because the file is a symlink,
1145 this platform sets errno to NOFOLLOW_SYMLINK_ERRNO.
1146 Although POSIX says errno must be ELOOP in that situation,
1147 FreeBSD and NetBSD behave more usefully. */
1148 enum { NOFOLLOW_SYMLINK_ERRNO =
1149 #ifdef __FreeBSD__
1150 EMLINK
1151 #elif defined __NetBSD__
1152 EFTYPE
1153 #else
1154 ELOOP
1155 #endif
1156 };
1157
1158 /* Compare two files with parent comparison PARENT.
1159 The two files are described by CMP, which has been prepped to contain
1160 the files' stat results, file types, and possibly descriptors.
1161 If the files need to be opened, use OPEN_FLAGS. */
1162 static int
1163 compare_prepped_files (struct comparison const *parent,
1164 struct comparison *cmp, int open_flags)
1165 {
1166 /* If neither file "exists", there's nothing to compare. */
1167 if (cmp->file[0].desc == NONEXISTENT && cmp->file[1].desc == NONEXISTENT)
1168 return EXIT_SUCCESS;
1169
1170 bool same_files = (cmp->file[0].desc != NONEXISTENT
1171 && cmp->file[1].desc != NONEXISTENT
1172 && cmp->file[0].filetype == cmp->file[1].filetype
1173 && same_file (&cmp->file[0].stat, &cmp->file[1].stat));
1174
1175 /* If the two named files are actually the same physical file.
1176 we know they are identical without actually reading them. */
1177 if (same_files & no_diff_means_no_output)
1178 return EXIT_SUCCESS;
1179
1180 bool toplevel = parent == &noparent;
1181
1182 /* Compare the two hierarchies if both files are directories, or if
1183 diff is recursive and one file is a directory and the other
1184 pretends to be a directory full of empty files. But don't
1185 compare dir contents one level down unless -r was specified. */
1186 if (dir_p (cmp, 0) & dir_p (cmp, 1)
1187 || (recursive
1188 && ((new_file & dir_p (cmp, 1)
1189 && cmp->file[0].desc == NONEXISTENT)
1190 || (((new_file | unidirectional_new_file) & dir_p (cmp, 0))
1191 && cmp->file[1].desc == NONEXISTENT))))
1192 {
1193 if (output_style == OUTPUT_IFDEF)
1194 fatal ("-D option not supported with directories");
1195
1196 if (recursive | toplevel)
1197 return diff_dirs (cmp);
1198 else
1199 {
1200 /* See POSIX 1003.1-2017 for this format. */
1201 message ("Common subdirectories: %s and %s\n",
1202 squote (0, cmp->file[0].name),
1203 squote (1, cmp->file[1].name));
1204 return EXIT_SUCCESS;
1205 }
1206 }
1207
1208 /* Fail if only one file exists. */
1209 if ((cmp->file[0].desc == NONEXISTENT
1210 && ! (new_file | unidirectional_new_file))
1211 || (cmp->file[1].desc == NONEXISTENT && !new_file))
1212 {
1213 bool existing = cmp->file[0].desc == NONEXISTENT;
1214 char const *dname = parent->file[existing].name;
1215 char const *bname = last_component (cmp->file[existing].name);
1216
1217 /* See POSIX 1003.1-2017 for this format. */
1218 message ("Only in %s: %s\n", squote (0, dname), squote (1, bname));
1219 return EXIT_FAILURE;
1220 }
1221
1222 /* If the two files have different types, or have the same type but
1223 the type is unusual, then simply report their type.
1224 However, at the top level do this only if one file is a symlink
1225 and the other is not. */
1226 mode_t mode0 = cmp->file[0].stat.st_mode;
1227 mode_t mode1 = cmp->file[1].stat.st_mode;
1228 if (toplevel ? !S_ISLNK (mode0) != !S_ISLNK (mode1)
1229 : S_ISREG (mode0) ? !S_ISREG (mode1)
1230 : S_ISLNK (mode0) ? !S_ISLNK (mode1)
1231 : S_ISCHR (mode0) ? !S_ISCHR (mode1)
1232 : S_ISBLK (mode0) ? !S_ISBLK (mode1)
1233 : true)
1234 {
1235 /* POSIX 1003.1-2017 says any message will do, so long as it
1236 contains the file names. */
1237 message ("File %s is a %s while file %s is a %s\n",
1238 file_label[0] ? file_label[0] : squote (0, cmp->file[0].name),
1239 gettext (cmp->file[0].filetype),
1240 file_label[1] ? file_label[1] : squote (1, cmp->file[1].name),
1241 gettext (cmp->file[1].filetype));
1242
1243 return EXIT_FAILURE;
1244 }
1245
1246 /* If both files are symlinks, compare symlink contents. */
1247 if (S_ISLNK (mode0))
1248 {
1249 /* We get here only if we are not dereferencing symlinks. */
1250 dassert (no_dereference_symlinks);
1251
1252 int status = EXIT_SUCCESS;
1253 char *link_value[2]; link_value[1] = nullptr;
1254 char linkbuf[2][128];
1255
1256 for (bool f = false; ; f = true)
1257 {
1258 int linkfd = cmp->file[f].desc;
1259 int dirfd = parent->file[f].desc;
1260 char const *name = cmp->file[f].name;
1261 int dirarg = linkfd < 0 ? dirfd : linkfd;
1262 char const *namearg = (linkfd < 0
1263 ? (dirfd < 0 ? name : last_component (name))
1264 : "");
1265 link_value[f] = careadlinkat (dirarg, namearg,
1266 linkbuf[f], sizeof linkbuf[f],
1267 nullptr, readlinkat);
1268 if (!link_value[f])
1269 {
1270 perror_with_name (cmp->file[f].name);
1271 status = EXIT_TROUBLE;
1272 break;
1273 }
1274 if (f)
1275 {
1276 status = (STREQ (link_value[0], link_value[f])
1277 ? EXIT_SUCCESS : EXIT_FAILURE);
1278 break;
1279 }
1280 }
1281
1282 if (status == EXIT_FAILURE)
1283 message ("Symbolic links %s -> %s and %s -> %s differ\n",
1284 quote_n (0, cmp->file[0].name), quote_n (1, link_value[0]),
1285 quote_n (2, cmp->file[1].name), quote_n (3, link_value[1]));
1286
1287 for (int f = 0; f < 2; f++)
1288 if (link_value[f] != linkbuf[f])
1289 free (link_value[f]);
1290
1291 return status;
1292 }
1293
1294 /* When not at the top level, compare device numbers of special files,
1295 and report file types of all other non-regular files.
1296 POSIX 1003.1-2017 says any message will do,
1297 so long as it contains the file names. */
1298 if (!toplevel && !S_ISREG (mode0))
1299 {
1300 if (cmp->file[0].stat.st_rdev == cmp->file[1].stat.st_rdev)
1301 return EXIT_SUCCESS;
1302
1303 intmax_t num[] = {
1304 major (cmp->file[0].stat.st_rdev),
1305 minor (cmp->file[0].stat.st_rdev),
1306 major (cmp->file[1].stat.st_rdev),
1307 minor (cmp->file[1].stat.st_rdev)
1308 };
1309 enum { n_num = sizeof num / sizeof *num };
1310 char numbuf[n_num][INT_BUFSIZE_BOUND (intmax_t)];
1311 for (int i = 0; i < n_num; i++)
1312 sprintf (numbuf[i], "%"PRIdMAX, num[i]);
1313
1314 message ((S_ISCHR (mode0)
1315 ? ("Character special files %s (%s, %s)"
1316 " and %s (%s, %s) differ\n")
1317 : ("Block special files %s (%s, %s)"
1318 " and %s (%s, %s) differ\n")),
1319 quote_n (0, cmp->file[0].name), numbuf[0], numbuf[1],
1320 quote_n (2, cmp->file[1].name), numbuf[2], numbuf[3]);
1321
1322 return EXIT_FAILURE;
1323 }
1324
1325 if (files_can_be_treated_as_binary
1326 && S_ISREG (mode0)
1327 && S_ISREG (mode1)
1328 && cmp->file[0].stat.st_size != cmp->file[1].stat.st_size
1329 && 0 <= cmp->file[0].stat.st_size
1330 && 0 <= cmp->file[1].stat.st_size)
1331 {
1332 message ("Files %s and %s differ\n",
1333 file_label[0] ? file_label[0] : squote (0, cmp->file[0].name),
1334 file_label[1] ? file_label[1] : squote (1, cmp->file[1].name));
1335 return EXIT_FAILURE;
1336 }
1337
1338 /* Both files exist and neither is a directory or a symbolic link.
1339 Open the files and record their descriptors,
1340 if they are not already open. */
1341
1342 int status = EXIT_SUCCESS;
1343
1344 for (int f = 0; f < 2; f++)
1345 if (cmp->file[f].desc == UNOPENED)
1346 {
1347 if (f && same_files)
1348 cmp->file[f].desc = cmp->file[0].desc;
1349 else
1350 {
1351 int dirfd = parent->file[f].desc;
1352 char const *name = cmp->file[f].name;
1353 char const *nm = dirfd < 0 ? name : last_component (name);
1354 cmp->file[f].desc = openat (dirfd, nm, open_flags);
1355 if (cmp->file[f].desc < 0)
1356 {
1357 perror_with_name (name);
1358 status = EXIT_TROUBLE;
1359 }
1360 }
1361 }
1362 else if (cmp->file[f].desc == OPEN_FAILED)
1363 {
1364 error (0, cmp->file[f].openerr, "%s", squote (0, cmp->file[f].name));
1365 status = EXIT_TROUBLE;
1366 }
1367
1368 /* Compare the files' contents, if no error was found. */
1369
1370 if (status != EXIT_SUCCESS)
1371 return status;
1372 return diff_2_files (cmp);
1373 }
1374
1375
1376 /* Compare two files (or dirs) with parent comparison PARENT,
1377 directory entries of type DETYPE, and names NAME0 and NAME1.
1378 (If PARENT == &NOPARENT, then the first name is just NAME0, etc.)
1379 This is self-contained; it opens the files and closes them.
1380
1381 Names are relative to the original working directory. If a file
1382 appears in only one dir, the other name is a null pointer.
1383
1384 Value is EXIT_SUCCESS if files are the same, EXIT_FAILURE if
1385 different, EXIT_TROUBLE if there is a problem opening them. */
1386
1387 int
1388 compare_files (struct comparison const *parent, enum detype const detype[2],
1389 char const *name0,
1390 char const *name1)
1391 {
1392 /* If this is directory comparison, perhaps we have a file
1393 that exists only in one of the directories.
1394 If so, just print a message to that effect. */
1395
1396 if (! ((name0 && name1)
1397 || (unidirectional_new_file && name1)
1398 || new_file))
1399 {
1400 char const *name = name0 ? name0 : name1;
1401 char const *dir = parent->file[!name0].name;
1402
1403 /* See POSIX 1003.1-2017 for this format. */
1404 message ("Only in %s: %s\n", squote (0, dir), squote (1, name));
1405
1406 /* Return EXIT_FAILURE so that diff_dirs will return
1407 EXIT_FAILURE ("some files differ"). */
1408 return EXIT_FAILURE;
1409 }
1410
1411 struct comparison cmp = { .file[0].desc = name0 ? UNOPENED : NONEXISTENT,
1412 .file[1].desc = name1 ? UNOPENED : NONEXISTENT,
1413 .file[0].stat.st_size = name0 ? -1 : 0,
1414 .file[1].stat.st_size = name1 ? -1 : 0,
1415 .parent = parent };
1416
1417 /* Now record the full name of each file, including nonexistent ones. */
1418
1419 if (!name0)
1420 name0 = name1;
1421 if (!name1)
1422 name1 = name0;
1423
1424 char *free0;
1425 char *free1;
1426 bool toplevel = parent == &noparent;
1427
1428 if (toplevel)
1429 {
1430 free0 = nullptr;
1431 free1 = nullptr;
1432 cmp.file[0].name = name0;
1433 cmp.file[1].name = name1;
1434 }
1435 else
1436 {
1437 cmp.file[0].name = free0
1438 = file_name_concat (parent->file[0].name, name0, nullptr);
1439 cmp.file[1].name = free1
1440 = file_name_concat (parent->file[1].name, name1, nullptr);
1441 }
1442
1443 int oflags = ((binary ? O_BINARY : 0) | O_CLOEXEC
1444 | (no_dereference_symlinks ? O_NOFOLLOW : 0));
1445
1446 /* Stat the files if needed, possibly opening them first if that is
1447 safe or will be done anyway. */
1448
1449 for (int f = 0; f < 2; f++)
1450 {
1451 int fd = cmp.file[f].desc;
1452 if (fd != UNOPENED)
1453 continue;
1454
1455 if (f && file_name_cmp (cmp.file[f].name, cmp.file[0].name) == 0)
1456 {
1457 cmp.file[f].desc = cmp.file[0].desc;
1458 cmp.file[f].filetype = cmp.file[0].filetype;
1459 cmp.file[f].stat = cmp.file[0].stat;
1460 continue;
1461 }
1462
1463 int parentdesc = parent->file[f].desc;
1464 char const *name = cmp.file[f].name;
1465 char const *nm = parentdesc < 0 ? name : last_component (name);
1466 int err = 0;
1467
1468 if (STREQ (cmp.file[f].name, "-"))
1469 {
1470 fd = STDIN_FILENO;
1471 if (binary && ! isatty (fd))
1472 set_binary_mode (fd, O_BINARY);
1473 }
1474 else if (toplevel || detype[f] == DE_REG || detype[f] == DE_DIR
1475 || (O_PATH_DEFINED && detype[f] == DE_LNK
1476 && no_dereference_symlinks))
1477 {
1478 /* Either we would open the file anyway because it's the top level,
1479 or the file is known to be a type that is
1480 safe to open and is likely to be opened anyway.
1481 Open the file now, as openat+fstat avoids an fstatat+openat race
1482 and might be a bit faster. */
1483 int accmode = ((O_PATH_DEFINED && !toplevel && detype[f] == DE_LNK
1484 && no_dereference_symlinks)
1485 ? O_PATHSEARCH : O_RDONLY);
1486 fd = openat (parentdesc, nm, accmode | oflags);
1487 if (fd < 0)
1488 {
1489 err = get_errno ();
1490
1491 /* 'diff DIR FILE' needs read access to DIR if
1492 --ignore-file-name-case; otherwise O_PATHSEARCH suffices.
1493 But do not check for this if ---no-directory. */
1494 if (err == EACCES && toplevel
1495 && !ignore_file_name_case && !no_directory
1496 && (f == 0 || !dir_p (&cmp, 0)))
1497 {
1498 fd = openat (parentdesc, nm,
1499 O_PATHSEARCH | O_DIRECTORY | oflags);
1500 if (0 <= fd)
1501 err = 0;
1502 }
1503
1504 /* If it is a symlink, fstatat later. If it might be a
1505 symlink, play it safe and fstatat later. */
1506 if (err == NOFOLLOW_SYMLINK_ERRNO
1507 && (NOFOLLOW_SYMLINK_ERRNO != ELOOP
1508 || (no_dereference_symlinks
1509 && (detype[f] == DE_UNKNOWN
1510 || (detype[f] == DE_LNK
1511 && accmode == O_RDONLY)))))
1512 {
1513 fd = UNOPENED;
1514 err = 0;
1515 }
1516
1517 cmp.file[f].openerr = err;
1518 }
1519 }
1520
1521 /* Get the file's status unless an earlier error makes it unnecessary. */
1522 if (! (cmp.file[1 - f].err
1523 /* If openat failed as follows, fstatat would fail too. */
1524 || err == ENOENT || err == ENOTDIR || err == ELOOP
1525 || err == EOVERFLOW || err == ENAMETOOLONG))
1526 {
1527 if ((fd < 0
1528 ? fstatat (parentdesc, nm, &cmp.file[f].stat,
1529 no_dereference_symlinks ? AT_SYMLINK_NOFOLLOW : 0)
1530 : fstat (fd, &cmp.file[f].stat))
1531 < 0)
1532 err = get_errno ();
1533 else
1534 {
1535 err = 0;
1536 off_t size = stat_size (&cmp.file[f].stat);
1537
1538 if (0 <= size && fd == STDIN_FILENO)
1539 {
1540 off_t pos = lseek (fd, 0, SEEK_CUR);
1541 if (0 <= pos)
1542 size = MAX (0, size - pos);
1543 }
1544
1545 cmp.file[f].stat.st_size = size;
1546 cmp.file[f].filetype = c_file_type (&cmp.file[f].stat);
1547 }
1548 }
1549
1550 cmp.file[f].desc = fd;
1551 cmp.file[f].err = err;
1552 }
1553
1554 if (toplevel)
1555 {
1556 if (!no_directory && toplevel
1557 && !cmp.file[0].err && !cmp.file[1].err
1558 && dir_p (&cmp, 0) != dir_p (&cmp, 1))
1559 {
1560 /* If one is a directory, use the file in that dir with the
1561 other file's basename. */
1562
1563 int fnm_arg = dir_p (&cmp, 0);
1564 int dir_arg = 1 - fnm_arg;
1565 if (cmp.file[fnm_arg].desc == STDIN_FILENO)
1566 fatal ("cannot compare '-' to a directory");
1567 char const *fnm = cmp.file[fnm_arg].name;
1568 enum detype dir_detype;
1569 char const *filename = cmp.file[dir_arg].name = free0
1570 = find_dir_file_pathname (&cmp.file[dir_arg], last_component (fnm),
1571 &dir_detype);
1572 int dirfd = cmp.file[dir_arg].desc;
1573 if (dirfd < 0)
1574 dirfd = AT_FDCWD;
1575 char const *atname = dirfd < 0 ? filename : last_component (filename);
1576 cmp.file[dir_arg].desc = UNOPENED;
1577 noparent.file[dir_arg].desc = dirfd;
1578 cmp.file[dir_arg].desc
1579 = (dir_detype == DE_LNK && no_dereference_symlinks
1580 ? (errno = ELOOP, -1)
1581 : openat (dirfd, atname, O_RDONLY | oflags));
1582 if (O_PATH_DEFINED && cmp.file[dir_arg].desc < 0
1583 && (dir_detype == DE_LNK || dir_detype == DE_UNKNOWN)
1584 && no_dereference_symlinks && errno == NOFOLLOW_SYMLINK_ERRNO)
1585 cmp.file[dir_arg].desc = openat (dirfd, atname,
1586 O_PATHSEARCH | oflags);
1587 if (cmp.file[dir_arg].desc < 0
1588 ? (O_PATH_DEFINED || !no_dereference_symlinks
1589 || errno != NOFOLLOW_SYMLINK_ERRNO
1590 || (fstatat (dirfd, atname, &cmp.file[dir_arg].stat,
1591 AT_SYMLINK_NOFOLLOW)
1592 < 0))
1593 : fstat (cmp.file[dir_arg].desc, &cmp.file[dir_arg].stat) < 0)
1594 cmp.file[dir_arg].err = get_errno ();
1595 else
1596 {
1597 cmp.file[dir_arg].stat.st_size
1598 = stat_size (&cmp.file[dir_arg].stat);
1599 cmp.file[dir_arg].filetype
1600 = c_file_type (&cmp.file[dir_arg].stat);
1601 }
1602 }
1603
1604 /* Mark files as nonexistent as needed for -N and -P,
1605 if they do not exist but their counterparts do exist. */
1606 for (int f = 0; f < 2; f++)
1607 if ((new_file || (f == 0 && unidirectional_new_file))
1608 && (cmp.file[f].err == ENOENT || cmp.file[f].err == ENOTDIR)
1609 && ! (cmp.file[1 - f].err == ENOENT
1610 || cmp.file[1 - f].err == ENOTDIR))
1611 {
1612 cmp.file[f].desc = NONEXISTENT;
1613 cmp.file[f].err = 0;
1614 }
1615 }
1616
1617 for (int f = 0; f < 2; f++)
1618 if (cmp.file[f].desc == NONEXISTENT)
1619 {
1620 cmp.file[f].filetype = cmp.file[1 - f].filetype;
1621 cmp.file[f].stat.st_mode = cmp.file[1 - f].stat.st_mode;
1622 }
1623
1624 int status = EXIT_SUCCESS;
1625
1626 for (int f = 0; f < 2; f++)
1627 if (cmp.file[f].err)
1628 {
1629 error (0, cmp.file[f].err, "%s", squote (0, cmp.file[f].name));
1630 status = EXIT_TROUBLE;
1631 }
1632
1633 if (status == EXIT_SUCCESS)
1634 status = compare_prepped_files (parent, &cmp, O_RDONLY | oflags);
1635
1636 /* Close any input files. */
1637 for (int f = 0; f < 2; f++)
1638 if ((f == 0 || cmp.file[f].desc != cmp.file[0].desc)
1639 && (cmp.file[f].dirstream ? closedir (cmp.file[f].dirstream) < 0
1640 : 0 <= cmp.file[f].desc && close (cmp.file[f].desc) < 0))
1641 {
1642 perror_with_name (cmp.file[f].name);
1643 status = EXIT_TROUBLE;
1644 }
1645
1646 /* Now the comparison has been done, if no error prevented it,
1647 and STATUS is the value this function will return. */
1648
1649 if (status == EXIT_SUCCESS)
1650 {
1651 if (report_identical_files && !dir_p (&cmp, 0))
1652 message
1653 ("Files %s and %s are identical\n",
1654 file_label[0] ? file_label[0] : squote (0, cmp.file[0].name),
1655 file_label[1] ? file_label[1] : squote (1, cmp.file[1].name));
1656 }
1657 else
1658 {
1659 /* Flush stdout so that the user sees differences immediately.
1660 This can hurt performance, unfortunately. */
1661 if (fflush (stdout) != 0)
1662 pfatal_with_name (_("standard output"));
1663 }
1664
1665 free (free0);
1666 free (free1);
1667
1668 return status;
1669 }
1670
1671 /* Define variables declared in diff.h (which see). */
1672 FILE *outfile;
1673 bool brief;
1674 bool expand_tabs;
1675 bool files_can_be_treated_as_binary;
1676 bool ignore_blank_lines;
1677 bool ignore_case;
1678 bool ignore_file_name_case;
1679 bool initial_tab;
1680 bool left_column;
1681 bool minimal;
1682 bool no_dereference_symlinks;
1683 bool no_diff_means_no_output;
1684 bool paginate;
1685 bool presume_output_tty;
1686 bool sdiff_merge_assist;
1687 bool speed_large_files;
1688 bool strip_trailing_cr;
1689 bool suppress_blank_empty;
1690 bool suppress_common_lines;
1691 bool text;
1692 char *file_label[2];
1693 char *switch_string;
1694 char const *group_format[CHANGED + 1];
1695 char const *line_format[NEW + 1];
1696 char const *starting_file;
1697 char const *time_format;
1698 enum DIFF_white_space ignore_white_space;
1699 enum colors_style colors_style;
1700 enum output_style output_style;
1701 intmax_t sdiff_column2_offset;
1702 intmax_t sdiff_half_width;
1703 intmax_t tabsize;
1704 lin context;
1705 lin horizon_lines;
1706 struct comparison curr;
1707 struct comparison noparent;
1708 struct exclude *excluded;
1709 struct re_pattern_buffer function_regexp;
1710 struct re_pattern_buffer ignore_regexp;
1711 #ifndef localtz
1712 timezone_t localtz;
1713 #endif