2025-03-29  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Version 2.8
	* NEWS: Update.

2025-02-27  Petr Vaněk  <arkamar@gentoo.org>

	Regression in commit abe92e8010ab affecting MariaDB tests
	I have disovered a regression in commit abe92e8010ab ("Prefer idx_t,
	ptrdiff_t to lin") while I was running MariaDB tests. The regression is
	related to a diff file [1], where the patch fails to apply it with
	following error:

	  patch: **** '---' expected at line 2 of patch

	To illustrate the issue, I have attached a git patch containing a
	testcase with simplified reproducer.

	[1] https://github.com/MariaDB/server/blob/mariadb-10.6.21/mysql-test/suite/innodb/r/innodb-wl5522%2Cstrict_crc32.rdiff file

2025-02-27  Paul Eggert  <eggert@cs.ucla.edu>

	Count traditional diff pattern lines correctly
	This fixes a bug I introduced on Thu Sep 5 16:37:50 2024 -0700.
	Problem reported by Petr Vaněk in:
	https://lists.gnu.org/archive/html/bug-patch/2025-02/msg00017.html
	* src/pch.c (another_hunk): Fix method for counting number
	of lines in a traditional diff hunk.

2025-02-25  Paul Eggert  <eggert@cs.ucla.edu>

	patch: fix --no-backup-if-mismatch regression
	Problem reported by Sam James in:
	https://lists.gnu.org/archive/html/bug-patch/2025-02/msg00014.html
	https://bugs.gentoo.org/show_bug.cgi?id=949834
	* src/patch.c (backup_if_mismatch_specified): New static var.
	(get_some_switches): Set it.
	(main): Default backup_if_mismatch only if not set on command line.
	* tests/no-backup: New file.
	* tests/Makefile.am (TESTS): Add it.

2025-02-06  Sam James  <sam@gentoo.org>

	Fix dodgy assert with side-effects in insert_cached_dirfd
	Michał Górny <mgorny@gentoo.org> reported that patch was running out of
	FDs and that the `deep-directories` test was failing. This turns out
	to be because `hash_insert` isn't called at all with `-DNDEBUG` because
	`insert_cached_dirfd` only calls it in one case inside of an `assert`.

	See https://github.com/conda-forge/patch-feedstock/issues/11.

	This regressed in 025a54b789bd88ed15430f8633514e296826983e.

	* src/safe.c (insert_cached_dirfd): Don't use 'assert' for 'hash_insert'
	  call with side-effects.

2025-02-06  Bruno Haible  <bruno@clisp.org>

	Declare an expected test failure on Haiku.
	* bootstrap.conf (gnulib_modules): Add test-xfail.
	* tests/preserve-mode-and-timestamp: Add a comment regarding Haiku.
	* tests/Makefile.am (XFAIL_TESTS): On Haiku, add preserve-mode-and-timestamp.

2025-02-06  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	build: update gnulib submodule to latest

2025-02-05  Bruno Haible  <bruno@clisp.org>

	Fix two test failures on Haiku.
	On Haiku, all error numbers are negative, see
	<https://www.gnu.org/software/gnulib/manual/html_node/errno_002eh.html>.

	Bisected by Eli Schwartz <eschwartz@gentoo.org>.

	This partially reverts commit 043355371a76de8ea7d06f79a69fde905af7cc45.

	* src/inp.c (get_input_file):
	* src/patch.c (main):
	* src/safe.c (read_symlink):
	* src/util.c (move_file):
	Don't assume that all system-defined errno values are positive.

2025-01-08  Paul Eggert  <eggert@cs.ucla.edu>

	Check for newlines only when creating a file name
	Also, check only the last file name component.
	In other words, mimic operating systems that follow POSIX.1-2024’s
	encouragement to fail with EILSEQ when openat etc. create a file name.
	This is more conservative than the previous patch to prohibit
	newlines in file names.
	* src/patch.c (main, backup_file_name_option, get_some_switches):
	* src/util.c (parse_c_string, make_tempfile):
	Don’t check for newlines in a file name unless we are definitely
	creating a file, as it’s harmless to read and stat file with
	newlines in their names if the OS allows that.
	* src/safe.c (traverse_another_path, traverse_path): New arg
	REJECT_NL.  If set, reject any file name whose last component
	contains a newline.  Also, do not do traversal if unsafe.  All
	callers changed to pass true if they are creating the file name,
	false otherwise, and to not bother checking whether we are unsafe.
	(safe_open): Special case for when O_CREAT is set but O_EXCL is not.
	* src/util.c (pfatal): Report "Invalid byte sequence" for EILSEQ.
	This POSIX wording is less confusing than glibc's "Invalid or
	incomplete multibyte or wide character".  Also, this lets
	the test cases check for this wording.
	* tests/bad-filenames: Adjust to new diagnostic wording.

2025-01-05  Paul Eggert  <eggert@cs.ucla.edu>

	Gnulib renamed some modules
	* bootstrap.conf (gnulib_modules):
	Adjust to recent module renaming in Gnulib.

	maint: update bootstrap from gnulib

	build: update gnulib submodule to latest

	maint: make update-copyright

2024-11-20  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Set --no-backup-if-mismatch when in --posix mode
	When in POSIX mode, the --no-backup-if-mismatch option should be
	enabled.  However, this is only true when the POSIXLY_CORRECT
	environmant variable is set but not when the --posix command line
	option is given.  Fix that by setting backup_if_mismatch after
	evaluating the command line arguments.

2024-11-11  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Add missing feature tests to the test suite
	Check for chmod, hardlink, symlink, and special character support to
	prevent test suite failures in feature constrained environments.

	Thanks to Bruno Haible and Nelson H. F. Beebe for their testing and
	analysis.

	* tests/test-lib.sh: Add new feature tests.
	* tests/hardlinks: Split this hardlinks related test off from
	tests/remember-backup-files.
	* tests/Makefile.am (TESTS): Add new hardlinks test here.
	* tests/file-create-modes, tests/file-modes, tests/read-only-files,
	tests/preserve-mode-and-timestamp, tests/no-mode-change-git-diff: These
	tests require chmod support.
	* tests/hardlinks, tests/unmodified-files: These tests require hardlink
	support.
	* tests/symlinks: This test requires symlink support.
	* tests/quoted-filenames: This test requires special character support
	in filenames.

2024-10-11  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Disable release-prep
	* cfg.mk: Disable release-prep by overriding the release-prep-hook for
	now.  With that, "make release" succeeds for alpha releases.

2024-10-11  Eli Schwartz  <eschwartz@gentoo.org>

	Fix "make release" to handle alpha releases
	news-check-regexp to scan for unreleased changes, has to be set
	conditional on the release type. It has to be defined in cfg.mk, not
	Makefile.am, so key off of the RELEASE_TYPE as automake conditionals are
	not available.

2024-10-11  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Add announce-gen module for "make release"
	* bootstrap.conf (gnulib_modules): Add announce-gen.

2024-09-20  Paul Eggert  <eggert@cs.ucla.edu>

	Pacify gcc -fsanitize=address
	Some of this merely pacifies -fsanitize=address by pointing
	to storage rather than freeing it when we are about to exit anyway.
	Other parts of it keep track of storage more carefully so that it
	can be freed rather than leak.
	* src/common.h (struct outfile): New member ‘alloc’.
	* src/patch.c (files_to_output_root) [SANITIZE_ADDRESS]:
	New externally visible variable, to pacify -fsanitize=address.
	(main): Use new functions described below to remove
	files and free memory.
	(delete_files): Do not free the list as we go, as we are about
	to exit and -fsanitize=address doesn’t care about this storage.
	(output_file_later): Set and use new member ‘alloc’ to avoid
	memory leaks.
	(output_files): WIth -fsanitize=address, record the list head
	in files_to_output_root that the address sanitizer can see,
	so that it won’t complain when we don’t free storage just before exit.
	Free only when not exiting, and free using ‘alloc’ rather than ‘name’.
	(perfile_cleanup_remove): New function.
	(cleanup_remove): Rename from ‘cleanup’.  All uses changed.
	Reimplement in terms of perfile_cleanup_remove.
	(free_outfile_name, perfile_cleanup_free): New functions.
	* src/util.c (make_tempfile): Set new member ‘alloc’.

	Fix memory leak when malformed unidiff patch
	* src/pch.c (another_hunk): Fix memory leak when scanning a
	unidiff patch malformed due to a line that does not begin with
	‘ ’, ‘-’, ‘+’, or ‘=’.

	Port to clang address sanitizer
	* src/patch.c (FREE_BEFORE_EXIT): Port to clang, which
	uses __has_feature (address_sanitizer) instead of
	defined __SANITIZE_ADDRESS__.  Also, rename this to
	SANITIZE_ADDRESS since it is really about -fsanitize=address
	rather than freeing before exit and as subsequent patches
	will show there are simpler ways to pacify -fsanitize=address.
	All uses changed.

	Refactor argc+argv processing
	* src/patch.c (Argc, Argv): Remove these confusing static variables.
	They date back to before the code used getopt_long,
	and are no longer needed.  All uses changed.
	(get_some_switches): New args argc+argv, which are now used
	instead of the static vars.  All uses changed.

	Omit needless get_some_switches code
	* src/patch.c (get_some_switches): Remove unnecessary
	initialization and testing.

2024-09-18  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Revert "Remove obsolete require_gnu_diff function"
	Oops, function require_gnu_diff is still needed in two places.

	This reverts commit 8cae4fc2213649e36e8f9a4cf21c28a82de3705c.

2024-09-18  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Remove obsolete require_gnu_diff function
	* tests/test-lib.sh (require_gnu_diff): Remove.

2024-09-18  Paul Eggert  <eggert@cs.ucla.edu>

	savebuf can return a null pointer
	* src/util.h (savebuf): Do not declare with ATTRIBUTE_RETURNS_NONNULL.
	Bug caught by gcc -fsanitize=undefined.

	Spelling fixes

	Port other reject-format test to non-GNU diff
	* tests/reject-format: Also don’t assume GNU diff
	for the ab.diff file.  Problem discovered on Solaris 11.4.

	Don’t be fooled by NUL bytes in diff directives
	* src/pch.c (get_line, pget_line): New arg ALLOW_NUL.
	It is true when getting data lines, which can contain NUL,
	but false when getting ‘diff’ directives, which cannot.
	All uses changed.
	* tests/bad-filenames: Check that ‘patch’ rejects
	directives containing NUL.

	Don’t be fooled by "\000" in file name
	* src/util.c (parse_c_string): Don’t be tricked by perverse
	C-style quoted strings containing backslash, '0', '0', '0'.
	* tests/quoted-filenames: Test this.

	Port to quasi-GNU diff
	Problem reported by Jim Meyering: ‘diff’ acted like GNU diff,
	and generated correct output, but the output differed slightly
	from what the test wanted.  As the output of ‘diff’ is not
	completely determined from its input, it’s better to put
	the desired ‘diff’ output directly in the test when the test
	depends on the exact output.
	* tests/preserve-c-function-names, tests/reject-format:
	Do not require GNU diff or use ‘diff’.
	Instead, cat the desired ‘diff’ output.

2024-09-17  Paul Eggert  <eggert@cs.ucla.edu>

	In previous patch, make w_q static

	Pacify -Wunterminated-string-initialization
	Problem reported by Jim Meyering.
	* src/pch.c (do_ed_script): Pacify bleeding-edge GCC
	-Wunterminated-string-initialization.

2024-09-17  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Spelling fixes
	Prefer 'timestamp' over 'time stamp'.

	Remove double semicolon
	* src/safe.c (remove_cached_dirfd): Remove a stray double semicolon.

	Prefer angle bracket headers
	* src/util.h: Prefer angle brackets for gnulib header files.

	Update more old copyright notices
	* configure.ac: Replace the old copyright notice with the current
	version from COPYING.
	* ChangeLog-2011: Likewise.

2024-09-17  Paul Eggert  <eggert@cs.ucla.edu>

	Simplify memory allocation of files to delete
	This pacifies ‘make sc_cast_of_argument_to_free’, which otherwise
	complains about the ‘free ((void *) elt)’ in dispose_file_to_delete.
	Rather than worry about pacifying that ‘make’ rule,
	simplify memory allocation by doing the linked list by hand,
	with a ‘next’ member the way our grandfathers did it.
	This reduces the number of source code lines by 23,
	removes the need for Gnulib’s linked-list and xlist modules,
	and makes the code type-safer (as opposed to going through void *).
	* bootstrap.conf (gnulib_modules): Remove linked-list, xlist.
	* src/patch.c: Do not include gl_linked_list.h, gl_xlist.h.
	(struct file_to_delete): New member ‘next’.
	(files_to_delete): Now struct file_to_delete *, not gl_list_t.
	(dispose_file_to_delete, init_files_to_delete):
	Remove; no longer needed.
	(files_to_delete_tail): New static var.
	(delete_file_later): Append the new file by hand.
	(delete_files): Iterate and free by hand.

	Report patch read errors more immediately
	* src/pch.c (open_patch_file): Cache patch file descriptor.
	When reading a patch, report read errors right away rather
	than possibly waiting until end of input.

	Port fflush usage to OpenBSD 7.5
	* src/inp.c (scan_input): Accept file descriptor, not stream.
	All callers changed.
	* src/patch.c (main): Do not obtain a stream for the patch
	file descriptor, as scan_input merely needs a file descriptor.
	This removes the need to call Fclose, which calls fflush,
	which fails on OpenBSD 7.5 which (contra POSIX) does not
	let you fflush an input stream.

2024-09-17  Andreas Gruenbacher  <andreas.gruenbacher@gmail.com>

	Update old copyright notices
	* NEWS: Replace the old copyright notice with the current version from
	COPYING.
	* m4/setmode.m4: Likewise.

2024-09-16  Paul Eggert  <eggert@cs.ucla.edu>

	Fix gl_gcc_warnings typo in ‘configure’
	* configure.ac (gl_gcc_warnings): Always set before using,
	fixing a typo I introduced Sat Aug 24 08:28:18 2024 -0700.

	build: update gnulib submodule to latest

	Remove some dependencies no longer needed
	* bootstrap.conf (gnulib_modules): Remove clock-time,
	nstrftime, stdc_bit_ceil, time.
	* src/inp.c: Do not include stdbit.h.

	Update NEWS as per recent changes

	Update POSIX citations

	Use “Gruenbacher” in international contexts
	* patch.man: “Grünbacher” → “Gruenbacher”,
	as per 2024-08-30 email from Andreas.

	Adjust libs to match recent Gnulib
	* src/Makefile.am (patch_LDADD): Add $(CLOCK_TIME_LIB) (replacing
	$(LIB_CLOCK_GETTIME)), $(EUIDACCESS_LIBGEN) (replacing
	$(LIB_EACCESS), $(GETRANDOM_LIB), $(HARD_LOCALE_LIB), $(LIBINTL),
	$(MBRTOWC_LIB), $(SETLOCALE_NULL_LIB).  This matches recent
	Gnulib and is needed for AIX 7.1 which requires linking
	with -lpthread.

	Pacify clang -Wbitwise-conditional-parentheses
	* src/util.c (copy_attr): Pacify clang 18.1.3 (1ubuntu1).

	Remove “support” for nested critical sections
	It was a bit racy, and it’s no longer needed now that
	we have shrunk critical sections.
	* src/util.c (signals_are_deferred): Rename from signal_deferring_level.
	Now effectively a boolean, instead of being a counter.
	All uses changed.

	Simplify critical section code in util fns
	* src/util.c (move_file, create_file, copy_file):
	Do not worry about whether the file is temporary
	when deciding whether to make a section of code critical.
	Just do it.  There’s no need for optimization now
	that we don’t need syscalls around critical sections.

	Shrink critical sections
	* src/patch.c (main):
	Do not put calls to output_files in critical sections,
	as it can now deal with signals.
	(struct file_to_output): ‘from’ member is now struct outfile, not
	char volatile *volatile.  All uses changed.
	(output_file_later): Append new structure to list in a critical section.
	(output_files): Redo so that calls need not be in a critical section.
	Instead, put critical sections around small subsidiary parts.

	Defer signals by hand with sigatomic_t
	Refactor by using a sig_atomic_t variable instead of a sigprocmask
	call to defer signals.  This should be good enough for a
	single-thread app where we write all the code that needs critical
	sections, and where the signal handler merely cleans up and exits.
	The resulting code should have the same behavior (including
	signal-handling races!) as the original.
	* bootstrap.conf (gnulib_modules): Remove sigaction, sigprocmask.
	Instead, use sigaction only if it’s supported natively,
	as the Gnulib emulation of sigaction drags in code we no longer need.
	* configure.ac: Check for sigaction, sigfillset.
	* src/patch.c (fatal_cleanup): New async-signal-safe function,
	which does the cleanup that the old fatal_exit (SIG) did when SIG
	was nonzero.
	(fatal_exit): Do what the old fatal_exit (SIG) did when SIG was zero.
	Omit SIG arg.  All callers changed.  This function is no longer
	called from signal handlers, and so no longer needs to be
	async-signal-safe under some circumstances.  However, it now
	defers signals.
	* src/util.c (signal_received): New static var.
	(signal_deferring_level): Now sig_atomic_t.
	(fatal_cleanup_and_terminate, handle_signal): New functions.
	(defer_signals, undefer_signals): Reimplement by
	using sigatomic_t volatile vars, not by using sigprocmask.
	(init_signals): Don’t assume SIGPIPE since we don’t use the
	Gnulib sigpipe module.  Use simple sigfillset signal mask
	so that we needn’t use sigprocmask to inquire about the
	current signal mask.  Have a fallback for old platforms
	that lack sigaction and sigfillset, since we no longer use
	Gnulib’s sigaction module.
	(exit_with_signal): Remove; no longer needed.

	output_file_later avoid a malloc+free pair
	* src/patch.c (output_file_later, output_files):
	Combine two malloc calls into one, and likewise for free.
	Rename local to ‘f’ to make the code easier to follow.

	Defend against closed stdin/stdout/stderr
	Various parts of ‘patch’ can misbehave when stdin, stdout, stderr
	are closed.  For example, ‘dup’ can yield 0, 1, or 2 and the
	resulting file descriptor will be misused.  Although POSIX
	requires that ‘patch’ be invoked with stdin/stdout/stderror open,
	it’s better to defend against the possbility that they’re not
	open.  Use Gnulib’s xstdopen module to defend against this.
	* bootstrap.conf (gnulib_modules): Add xstdopen.
	* src/patch.c: Include xstdopen.h.
	(main): Call xstdopen before doing I/O.

	Stop using Gnulib ‘execute’ module
	This is motivated by wanting to remove dependencies on
	Gnulib’s sigprocmask etc. modules, in later patches.
	* bootstrap.conf (gnulib_modules): Remove execute.
	* src/pch.c: Don’t include execute.h.
	(do_ed_script): Use ‘quote_system_arg’ and ‘systemic’, not
	‘execute’, to run the editor command while avoiding
	quoting vulnerabilities.
	* src/util.c (quote_system_arg): Now extern.

	Move defer_signals up
	* src/util.c (signal_deferring_level, defer_signals, undefer_signals):
	Refactor by moving up.  This should simplify later patches.

	Make sigs, NUM_SIGS local
	* src/util.c (sigs, NUM_SIGS): Refactor by moving these static
	constants into the only function that uses them.

	Rename block_signals
	This refactoring prepares for a new algorithm that does not use
	SIG_BLOCK, and where the name ‘block_signals’ would be misleading.
	* src/util.c (signal_deferring_level, defer_signals, undefer_signals):
	Rename from signal_blocking_level, block_signals, unblock_signals.
	All uses changed.

	Trade a bit of space for time in parse_c_string
	* src/util.c (parse_c_string): Omit unnecessary realloc.

	Allocate first patchbuf statically
	This way we avoid the need to call malloc first thing.
	Usually there will no need to call malloc at all, for patchbuf.
	* src/common.h (patchbuf, patchbufsize): Move extern decls from here ...
	* src/pch.h: ... to here.
	* src/patch.c (patchbuf, patchbufsize): Move defns from here ...
	* src/pch.c: ... to here, and initialize patchbuf statically.
	* src/patch.c (main): No need to initialize patchbuf.
	* src/pch.c (initial_patchbuf): New static vbar.
	(grow_patchbuf): New function.
	(pget_line): Use grow_patchbuf rather than growing by hand.
	* src/util.c: Include pch.h, for patchbuf.
	(ask): Return patchbuf, not void, so that callers need not
	include pch.h merely to access patchbuf.  All callers changed.

	Use bigger buffer size by default
	This idea is taken from GNU coreutils.
	* src/patch.c (patchbufsize): Initialize statically rather than
	dynamically.
	* src/util.c (IO_MAX): Remove.  All uses replaced by IO_BUFSIZE.
	* src/util.h (IO_BUFSIZE): New constant, taken from coreutils.

	Preinitialize fatal_act.sa_hander
	* src/util.c (fatal_act): Initialize .sa_handler statically ...
	(init_signals): ... rather than dynamically.

	Prefer EXIT_SUCCESS etc. to literal integers
	* src/patch.c (main, usage, get_some_switches, fatal_exit):
	* src/pch.c (do_ed_script):
	* src/util.c (exit_with_signal):
	Prefer EXIT_SUCCESS, EXIT_FAILURE, EXIT_TROUBLE to 0, 1, 2.
	* src/util.h (EXIT_TROUBLE): New constant.

	Fix some signal handling races
	Also, when a signal arrives, clean up temporary files that were
	not put in /tmp.
	* src/patch.c (main): Block signals around every call to output_files
	and to remove_if_needed.
	(struct file_to_output): ‘from’ and ‘to’ are now volatile,
	as they are accessed in signal handler.
	(files_to_output): Now volatile, and done by hand instead of
	using gl_list_t so that it can be volatile.  All uses changed.
	(files_to_output_tail): New var, which points to pointer to last
	object in list (if any).  Volatile so it can be accessed by
	signal handler.  All updates of list changed.
	(dispose_file_to_output, init_files_to_output, gl_list_clear):
	Remove; no longer used now that we are doing this list by hand.
	(output_files): 2nd arg is now int, not bool; -1 means we
	are in a signal handler.  When exiting due to a signal handler,
	merely unlink (not safe_unlink) the source, and do not use
	‘free’; this way, the code is async-signal-safe.
	(fatal_exit): Arrange for signals to be blocked, when not
	invoked as a signal handler.  Call output_files even when
	signaled, as it will now do something sensible by deleting
	temp files without renaming them.

	Fix --set-utc TZ setting
	* src/patch.c (main): Set TZ to "UTC0", which older POSIX requires
	support for, as opposed to "UTC", which even POSIX.1-2024 arguably
	does not require support for.  Also, check for setenv failure.

	Improve logic for when rename removes source
	* src/util.c (move_file): Don’t test outfrom when it’s already
	known to be non-null.  Don’t worry about destination link count
	if we created the source.

	Fix signal race when renaming file
	* src/util.c (move_file): Fix race if a signal arives between
	the time we rename a file and we mark the source as not existing.

	Simplify traverse_another_path via last_component
	* src/safe.c: Include basename-lgpl.h.
	(traverse_another_path): Simplify by using last_component.

	Stop using Gnulib dirname module
	We don’t need its dir_name and base_name functions, since we
	merely copy the strings elsewhere.  Instead, use some of the
	modules that dirname uses.
	* bootstrap.conf (gnulib_modules): Add basename-lgpl, filename.
	Remove dirname.
	* src/pch.c, src/util.c:
	Include basename-lgpl.h and filename.h instead of dirname.h.
	* src/pch.c (best_name):
	* src/util.c (version_controller):
	Use last_component instead of the dirname module’s functions.
	* src/safe.c: Include filename.h instead of dirname.h.
	* src/util.c (make_tempfile): No need to break the file name
	into directory and basename; just use the whole file name.

	Fix implausible overflow when reading symlinks
	* src/safe.c (read_symlink): Check for integer overflow
	in bufferi size calculation.

	Access checks should use effective, not real
	* src/safe.c (safe_access): Use effective user and group ID,
	not real user and group ID.

	Don’t assume AT_FDCWD != -1
	* src/safe.h (DIRFD_INVALID): New constant.
	* src/safe.c (traverse_another_path, traverse_path, safe_xstat)
	(safe_open, safe_rename, safe_mkdir, safe_rmdir, safe_unlink)
	(safe_symlink, safe_chmod, safe_lchown, safe_lutimens)
	(safe_readlink, safe_access):
	Use it to port to perverse platforms where AT_FDCWD == -1.

	Copy input to output attributes via fd if possible
	* src/inp.c (scan_input): New arg ifp.  It is now the
	caller’s responsibility to open and close the input.
	Caller changed.
	* src/patch.c (main): Open the input file for scan_input, and use
	its file descriptor, if available, to avoid some races while
	setting output file attributes.

	Simplify timestamp epoch checking
	* src/util.c (fetchname): Simplify timestamp calculations.
	Also, add a comment saying why they are buggy in obscure
	cases that have little practical implication.

	Check for ftello failures
	Also, use Gnulib modules fseeko, ftello, and rely on off_t,
	fseeko, ftello as they are safe to use nowadays.
	* bootstrap.conf (gnulib_modules): Add fseeko, ftello.
	This is needed only for very old platforms, plus MSVC.
	* src/common.h (file_offset, file_seek, file_tell): Remove.
	All uses replaced with off_t, fseek, ftell.
	* src/util.c (Fseeko): Rename from Fseek.  All uses changed.
	(Ftello): New function.  All ftello callers that rely on
	nonnegative results changed to Ftello.

	Remove format_linenum
	* src/util.c (format_linenum):
	* src/util.h (LINENUM_LENGTH_BOUND):
	Remove.  They are no longer needed now that line numbers can be
	printed with %td.  All uses replaced by printf with %td.

	Fix "with multiple words" line number
	* src/pch.c (intuit_diff_type): Fix typo in diagnostic,
	which output a file offset as if it were a line number.

	Drop Plan B
	‘patch’ dates back to when porting to 16-bit machines still
	mattered, and where it was therefore useful to support files that
	did not fit in RAM.  So ‘patch’ had two operating modes, Plan A
	and Plan B.  In Plan A the input was simply read into memory, but
	if memory was exhausted ‘patch’ fell back onto Plan B where input
	was transformed into a temporary file that holds the input lines.
	The idea was to not use any malloc calls during the main part of
	the ‘patch’ run, so that ‘patch’ could not exhaust memory if Plan
	A succeeded.  Over the years, though, that approach has not always
	been observed, as malloc is called for sundry reasons and ‘patch’
	immediately fails when malloc fails other than during the Plan A
	initial phase.  In practice this misbehavior has not been a
	problem, as ‘patch’ now invariably runs on machines where source
	file contents fit into RAM so Plan B is never used.  The GNU
	Coding Standards says not to worry about supporting machines too
	small to read file contents, and now’s a good time to remove the
	Plan B code, as it is making further maintenance a pain.
	* bootstrap.conf (gnulib_modules): Remove ialloc.
	All uses of ialloc.h and its API removed, and replaced by
	xalloc.h API as needed.
	* src/common.h (lin, LINENUM_MIN, LINENUM_MAX): Remove.
	All uses of ‘lin’ replaced by idx_t if known to be nonnegative,
	ptrdiff_t otherwise.  All uses of LINENUM_MAX replaced by IDX_MAX.
	LINENUM_MIN was not used.
	* src/inp.c (tibufsize, TIBUFSIZE_MINIMUM, tifd, tibuf, tiline)
	(lines_per_buf, tireclen, last_line_size, too_many_lines)
	(lines_too_long, plan_a, plan_b): Remove.  All uses removed.
	(scan_input): Do just what plan_a used to do, except report a fatal
	error on memory exhaustion.
	Do not worry about file types other than regular file or symlink
	as they are not possible.  All uses changed.
	(ifetch): Omit WHICHBUF arg, which is no longer needed now that
	we always use Plan A.  All uses changed.
	* src/patch.c (tmpin): Remove.  All uses removed.
	* src/pch.c (grow_hunkmax, pget_line): Use xpalloc rather than
	doing the equivalent by hand.
	(grow_hunkmax): Always succeed.  All uses changed.
	(another_hunk): Return bool not signed char, since -1 is
	no longer possible.  All uses changed.
	Use ximemdup0 instead of savestr when that is more convenient.
	(get_line, pget_line): Return idx_t, not ptrdiff_t, since -1
	is no longer possible.  All uses changed.
	* src/util.c (savebuf): Always succeed.  All callers changed.
	Simplify.
	(Write): Now static.

	Prefer ximemdup0 to xmemdup0
	This is natural, as the args are all nonnegative ptrdiff_t, not size_t.
	It also removes the need for Gnulib’s xmemdup0 module.
	* bootstrap.conf (gnulib_modules): Remove xmemdup0.
	* src/pch.c, src/util.c: Do not include xmemdup0.h.
	All calls to xmemdup0 replaced by ximemdup0.

	Refactor ifetch API
	* src/inp.c (ifetch): Return struct iline, instead of
	returning a pointer and storing through a pointer.
	All callers changed.
	* src/inp.h (struct iline): New type.

	Do not attempt huge I/Os
	Also, simplify I/O error checking by moving some of it into
	new functions Read and Write.
	* bootstrap.conf (gnulib_modules): Remove full-write.
	* src/inp.c (plan_a, plan_b, ifetch):
	* src/util.c (move_file, copy_to_fd):
	Use Read or Write instead of checking for I/O errors by hand.
	* src/util.c: Do not include full-write.h.
	(IO_MAX): New constant.
	(ifetch): Diagnose temp file shrinkage.
	(ask): Do not attempt a read of more than IO_MAX bytes.
	Use xpalloc to reallocate, instead of doing it by hand.
	(Read, Write): New functions.

	Use outfd when setting file attributes
	* src/patch.c (main): Check for output error when closing outfd.
	Use outfd when setting file attributes, to fix some races.
	This means delaying closing until after setting file attributes.
	(spew_output): Don’t close output stream; that is now the
	caller’s responsibility.  Caller changed.

	Don’t assume Linux-like S_IFREG
	* boostrap.conf (gnulib_modules): Add assert-h.
	* src/pch.c (fetchmode): Convert Git type to local file type.

	Use STDOUT_FILENO etc
	* src/patch.c (open_outfile):
	* src/pch.c (do_ed_script): Prefer macros like STDOUT_FILENO to
	expressions like 1 or fileno (stdout).

	Fix unlikely glitch with ed diffs
	* src/patch.c (main): If tmpout can’t be created, don’t
	continue when diff_type == ED_DIFF.

	Use fds to copy attrs in create_backup_copy
	* src/util.c (create_backup_copy): Let the new copy_file set file
	attributes, as this can be done more straightforwardly via
	file descriptors.
	(copy_to_fd): Return the source file descriptor instead of closing
	it, so that the caller can use it before closing.  All callers changed.
	(copy_file): New arg ATTR.  Set the destination’s attributes
	accordingly.  All callers changed.

	Be more careful about (time_t) -1
	* src/patch.c (main):
	* src/pch.c (intuit_diff_type):
	* src/util.c (fetchname):
	Mark an invalid timespec with both .tv_sec = (time_t) -1
	and with .tv_nsec = -1.  This is more reliable in case
	time_t is unsigned and narrower than int, in which case
	(time_t) -1 != -1.  It’s also more reliable in the unusual case
	where (time_t) -1 is a valid timestamp.  All uses changed.

	X == -1 → X < 0
	* src/inp.c (get_input_file, plan_b, ifetch):
	* src/patch.c (main, get_some_switches, open_outfile)
	(init_reject, output_file_now):
	* src/pch.c (open_patch_file, there_is_another_patch)
	(another_hunk, do_ed_script):
	* src/safe.c (read_symlink, traverse_another_path):
	* src/util.c (move_file):
	Prefer X < 0 to X == -1 when either comparison will do.
	This lets us focus better on oddball cases like uid_t and time_t
	when converted from -1.

	Let set_file_attributes use fds not names
	Although this ability is currently not used, so this commit is
	merely refactoring, the patch should help ‘patch’ avoid some race
	conditions in followup commits.
	* bootstrap.conf (gnulib_modules): Add futimens.
	* src/util.c: Include utimens.h.
	(lacks_appropriate_privileges, copy_fdattr_error): New functions.
	(copy_attr): New args src_fd, dst_fd.  All uses changed.
	(set_file_attributes): New args tofd, fromfd.  All uses changed.

	Port to narrow unsigned uid_t
	* src/util.c (set_file_attributes): Work even if uid_t or gid_t
	is unsigned and narrower than int, so that (uid_t) -1 != -1.

	Check for output errors more systematically
	* bootstrap.conf (gnulib_modules): Add closeout.
	* src/merge.c (print_linerange, merge_result, merge_hunk):
	* src/patch.c (main, usage, get_some_switches)
	(print_unidiff_range, abort_hunk_unified, abort_hunk_context)
	(apply_hunk, copy_till, spew_output):
	* src/pch.c (open_patch_file, there_is_another_patch)
	(another_hunk, pch_write_line, do_ed_script):
	* src/safe.c (traverse_another_path):
	* src/util.c (putline, vsay, ask, systemic):
	* src/version.c (version):
	Check for output errors more systematically.
	* src/patch.c: Include closeout.h.
	(main): Invoke close_stdout at exit.
	* src/util.c (fatal): Use fputc, not putc; no need for speed here.
	(pfatal): Use fprintf, not putline, to avoid recursion loop
	on write error.
	(Fclose, Fflush, Fprintf, Fputc, Fputs, Fwrite):
	New functions, to go with Fseek.
	* src/version.c: Include util.h, for Fprintf.

2024-09-16  Paul Eggert  <eggert@cs.ucla.edu>

	Report input error right away
	* src/inp.c (plan_b):
	* src/pch.c (incomplete_line):
	When getc fails due to an input error, report the error right away.

	Simplify EOF testing

2024-09-16  Paul Eggert  <eggert@cs.ucla.edu>

	Simplify EOF testing
	* src/inp.c (plan_b):
	* src/patch.c (apply_hunk, copy_till):
	* src/pch.c (skip_to, pget_line, incomplete_line, do_ed_script):
	Just check whether a value is negative, rather than exactly EOF.
	This simplifies the code a bit, and speeds it up very slightly.

	Prefer other types to ‘int’
	* src/merge.c (merge_result, merge_hunk):
	Hunk number is intmax_t, not int, fixing an unlikely overflow.
	* src/patch.c (invc): Now signed char, not int.
	(numeric_string): Use bool, not int, for sign.
	* src/pch.c (p_says_nonexistent, sha1_says_nonexistent)
	(pch_says_nonexistent): Now char, not int.  All uses changed.
	(p_rfc834_nesting, pget_line): Use idx_t, not int,
	fixing an unlikely overflow.  All uses changed.
	(another_hunk): Now signed char, not int.  All uses changed.
	* src/util.c (format_linenum): Remove unnecessary casts to int.

	Detect unlikely integer overflow in size calcs
	* src/pch.c (set_hunkmax, grow_hunkmax): Check for unlikely
	integer overflow in size calculations, by using ireallocarray
	rather than realloc and similarly for xireallocarray vs xmalloc.
	(grow_hunkmax): Rely on C89 guarantee that when realloc fails, the
	old storage is still available.  We need not worry any more about
	ancient hosts where that was not true.  Grow by a factor of
	1.5, as per xpalloc, instead of by a factor of 2.

	Prefer idx_t, ptrdiff_t to lin
	Prefer idx_t and ptrdiff_t to lin when counting lines in main
	memory.  This is mostly for clarity, though it should help
	efficiency slightly in obsolescent 32-bit platforms.
	* src/inp.c (ifetch):
	* src/merge.c (locate_merge, merge_hunk, count_context_lines)
	(context_matches_file, compute_changes):
	* src/patch.c (main, locate_hunk, mangled_patch)
	(print_unidiff_range, abort_hunk_unified, abort_hunk_context)
	(apply_hunk, patch_match):
	* src/pch.c (p_ptrn_lines, p_repl_lines, p_end, p_max)
	(p_prefix_content, p_suffix_content, hunkmax, p_efake, p_bfake)
	(another_hunk, pch_swap, pch_ptrn_lines, pch_repl_lines)
	(pch_end, pch_prefix_context, pch_suffix_context, pch_line_len)
	(pch_char, pfetch, pch_write_line, pch_normalize):
	Prefer idx_t to lin for object sizes.
	Prefer ptrdiff_t to lin for pointer differences.
	All uses changed.
	* src/merge.c (compute_changes): Check for integer overflow
	when combining file with memory counts, when the result
	must fit into memory.

	Fix compatibility issue with blanks in patches
	* src/util.c (remove_prefix): Remove; no longer used.
	* src/pch.c (intuit_diff_type, scan_linenum, another_hunk):
	Allow a nonempty sequence of blanks in places where POSIX requires
	support for these sequences.
	(another_hunk): Parse the "0,0" instead of comparing it literally,
	since there can be blanks around the comma.
	* tests/Makefile.am (TESTS): Add unusual-blanks.
	* tests/unusual-blanks: New file.

	pch_swap return type cleanup
	* src/pch.c (pch_swap): Return void not bool, since it always
	returns true if it returns at all.  All uses changed.

	Fix unlikely int overflow in hunk counts
	* src/patch.c (main): Don’t assume hunk counts fit in int.

	Use char for char in plan_a
	* src/inp.c (plan_a): Use char, not int, for local.

	Cache cwd_is_root dev, ino
	* src/util.c (cwd_is_root): Cache stat results.

	Avoid ‘unsigned’ in safe.c
	* src/safe.c (MAX_SAFE_COMPONENTS): Now an enum instead of unsigned.
	(dirfd_cache_misses): Now intmax_t instead of unsigned.
	All uses changed.
	(count_path_components): Return idx_t, not unsigned, to
	avoid issues with file names with more than INT_MAX components.
	All uses changed.

	Simplify get_sha1
	* src/pch.c (get_sha1): Return the new string instead of storing
	through a pointer.  All uses changed.  Use xmemdup0 instead of
	duplicating its logic.

	Avoid casts in patch.c
	* src/patch.c (main, get_some_switches, abort_hunk_context):
	Redo to avoid casts.
	(main): Use %#o rather than 0%o for octal output, to avoid
	unnecessary leading 0.

	Prefer idx_t in util.c
	* src/util.c (file_id_hasher): Avoid unlikely signed integer
	overflow when adding e->ino and e->dev.
	(create_backup, copy_to_fd, quote_system_arg, version_controller)
	(savebuf, remove_prefix, removedirs): Prefer idx_t to size_t.

	Prefer idx_t in pch.c
	* src/pch.c (p_len, p_indent, open_patch_file, intuit_diff_type)
	(prefix_components, best_name, another_hunk, get_line, pget_line)
	(pch_swap, pch_line_len):
	Prefer idx_t or ptrdiff_t to size_t.  All uses changed.
	(intuit_diff_type): Rename local distance_from_minimum to
	above_minimum, and make it 1 or 0 which is all that is needed.
	This avoids integer overflow when the distance exceeds INT_MAX.

	Prefer idx_t in patch.c
	* src/patch.c (patchbufsize, main, similar):
	Prefer idx_t to size_t.  All uses changed.
	* src/pch.c (pget_line):
	* src/util.c: Include ialloc.h.
	(ask): Avoid bad behavior on unlikely size overflow.
	When converting from size_t to idx_t,
	prefer reallocation growth by 50% not 100%, to match xpalloc.

	Prefer idx_t in list.h
	* src/list.h (list_entry): Prefer idx_t to size_t.

	Prefer idx_t in inp.c
	Prefer signed to unsigned types for object sizes,
	as they have better checking (e.g., gcc -fsanitize=undefined).
	* bootstrap.conf (gnulib_modules): Add idx (already being used
	indirectly) and stdc_bit_ceil.
	* src/common.h: Include idx.h.
	* src/inp.c: Include stdbit.h.
	(tibufsize, tireclen, last_line_size, plan_a, ifetch):
	Prefer idx_t to size_t for object sizes.  All uses changed.
	(lines_per_buf): Prefer idx_t to lin when it's talking about
	object sizes.
	(plan_b): Check for idx_t overflow too.  Use stdc_bit_ceil
	instead of doing it by hand.

	build: update gnulib submodule to latest

	Don’t limit strip counts etc. to INT_MAX
	* src/patch.c (debug): Now unsigned short int, not int, since
	it is used as a mask and only the bottom 9 bits matter.
	(patch_get, strippath, maxfuzz): Now intmax_t, not int.
	(numeric_string): Return intmax_t, not int.
	On overflow return an extremum rather than reporting an error,
	since the resulting values are effectively infinity anyway.
	All uses changed.
	* src/util.c (success, fetchname, parse_name): Accept intmax_t, not int.

	Fix unlikely integer overflows in patch.c
	* src/patch.c (numeric_string): Use stdckdint instead of
	by-hand overflow checks that might not work.

	Fix unlikely integer overflows in pch.c
	* src/pch.c (scan_linenum): Use stdckdint instead of by-hand
	overflow checks that might not work.  Fix already-existing
	use of ckd_add that wasn’t done quite correctly.

	Fix unlikely integer overflows in inp.c
	* bootstrap.conf (gnulib_modules): Add ialloc.
	* src/inp.c: Include ialloc.h.
	(plan_a, plan_b): Prefer idx_t and ssize_t to size_t.
	Use stdckdint instead of by-hand overflow checks that might not work.

	Promote minmax.h to common.h
	* src/common.h: Include minmax.h here ...
	* src/merge.c, src/patch.c, src/safe.c: ... instead of here.

	Avoid some memory allocation by not using ‘const’
	* src/common.h (struct outfile.exists):
	* src/safe.c (struct symlink.path):
	Member is no longer pointer to const.  All uses changed.
	* src/inp.c (get_input_file, plan_a, plan_b):
	* src/patch.c (delete_file_later):
	* src/pch.c (do_ed_script):
	* src/safe.c (safe_xstat, safe_stat, safe_lstat, safe_open)
	(safe_rename, safe_mkdir, safe_rmdir, safe_unlink, safe_symlink)
	(safe_chmod, safe_lchown, safe_lutimens, safe_readlink)
	(safe_access):
	* src/util.c (volatilize set_file_attributes, create_backup_copy)
	(create_backup, copy_to_fd, copy_file, append_to_file, trystat)
	(version_get, stat_file):
	Arg no longer points to const.  All callers changed.
	* src/safe.c (openat_cached):
	Make a copy of arg, to simplify API.
	Arg now points to const, since it no longer needs write access.
	(traverse_next, traverse_another_path, traverse_path):
	Arg points to pointer that is no longer pointer to const.
	Temporarily change argument string instead of duplicating it and
	changing the copy.  All uses changed.
	* src/util.c (volatilize): Result is no longer pointer to const.

	Remove unnecessary char * casts in inp.c
	* src/inp.c (plan_a): Remove unnecessary casts to char *.

	Pacify gcc -Wunused-parameter when !USE_XATTR
	* src/common.h (struct outfile.exists):
	Now char const volatile *volatile, not bool volatile,
	so that we follow the C standard more strictly.
	All uses changed.
	* src/util.c (UTIL_INLINE): New macro.
	(volatilize): New function.
	* src/util.h: Use _GL_INLINE_HEADER_BEGIN, UTIL_INLINE.
	(devolatilize): New function.

	Pacify gcc -Wunused-parameter when !USE_XATTR
	* src/util.c (copy_attr) [!USE_XATTR]: Mark args with MAYBE_UNUSED.

	maint: stop using alloca
	It means unbounded allocation on the stack, which is trouble
	on some platforms.  Also, gcc-12 on Pop!_OS 22.04 LTS complains.
	* bootstrap.conf (gnulib_modules): Remove alloca.
	* src/pch.c, src/safe.c: Don’t include alloca.h.
	* src/pch.c (do_ed_script):
	Use designated initializer instead of fixed-size alloca.
	* src/safe.c (new_cached_dirfd, openat_cached):
	Name arg is now allocated on heap by caller, and is now char * not
	char const *.  All callers changed.
	(openat_cached, traverse_next): Redo to avoid gotos.
	(traverse_next, traverse_another_path):
	Use ximemdup0 instead of alloca, to allocate on the heap rather than
	unboundedly on the stack.

	Don’t assume O_RDONLY == 0
	* src/safe.c (O_PATHSEARCH): New constant.
	(openat_cached): Use it, so as to not assume that
[--snip--]
