Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec
CLAR_TEST_SUITES += u-trailer

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Phillip Wood wrote on the Git mailing list (how to reply to this email):

Hi Johannes

On 23/11/2026 22:13, Johannes Schindelin via GitGitGadget wrote:
> From: Johannes Schindelin <johannes.schindelin@gmx.de>
> 
> Accumulating the output count in `write_in_full()` can overflow because
> it counts via a `ssize_t` variable which can overflow for valid `size_t`
> sizes passed as input.
> 
> Since this function either completes the requested count or fails,
> callers already know how many bytes were written on success. Let's just
> return status instead, so the total transfer size need not fit in
> `ssize_t`.

This makes perfect sense and the changes in this patch all look good. Looking at how the callers of write_in_full() use the return value, there are a few we might want to tweak.

In config.c write_section() and write_pair() both return the result of write_in_full(). All of the callers of those functions are only interested in whether the return value was negative, so there is no problem with the change in behavior, but we might want to change the return value to an int to match the new prototype of write_in_full().

In entry.c:write_entry() and parallel-checkout.c:write_pc_item_to_fd() we're still using a ssize_t to store the return value even though it is now an int.

In odb/streaming.c:odb_stream_blob_to_fd() we're also storing the return value in a ssize_t. Unlike the cases above we can simply avoid storing the value at all.

One final note - in refs.c:transaction_hook_feed_stdin(), sequencer.c:pipe_from_strbuf() and transport.c:pre_push_hook_feed_stdin() we're storing the result in an int and then checking if it is negative, so this patch actually fixes potential bugs in those callers.

Thanks

Phillip



> Pointed out by Coverity.
> 
> Helped-by: Phillip Wood <phillip.wood@dunelm.org.uk>
> Assisted-by: GPT-6.1
> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
> ---
>   Makefile                        |  1 +
>   imap-send.c                     |  2 +-
>   notes-merge.c                   | 13 ++--------
>   t/meson.build                   |  1 +
>   t/unit-tests/u-reftable-stack.c |  2 +-
>   t/unit-tests/u-wrapper.c        | 42 +++++++++++++++++++++++++++++++++
>   wrapper.c                       |  6 ++---
>   wrapper.h                       |  7 ++++--
>   8 files changed, 55 insertions(+), 19 deletions(-)
>   create mode 100644 t/unit-tests/u-wrapper.c
> 
> diff --git a/Makefile b/Makefile
> index 4c84eea6e2..0687eb82d3 100644
> --- a/Makefile
> +++ b/Makefile
> @@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec
>   CLAR_TEST_SUITES += u-trailer
>   CLAR_TEST_SUITES += u-urlmatch-normalization
>   CLAR_TEST_SUITES += u-utf8-width
> +CLAR_TEST_SUITES += u-wrapper
>   CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X)
>   CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES))
>   CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
> diff --git a/imap-send.c b/imap-send.c
> index bf1d2cf74d..dccc2264de 100644
> --- a/imap-send.c
> +++ b/imap-send.c
> @@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len)
>   		n = SSL_write(sock->ssl, buf, len);
>   	else
>   #endif
> -		n = write_in_full(sock->fd[1], buf, len);
> +		n = write_in_full(sock->fd[1], buf, len) < 0 ? -1 : len;
>   	if (n != len) {
>   		socket_perror("write", sock, n);
>   		close(sock->fd[0]);
> diff --git a/notes-merge.c b/notes-merge.c
> index d361e70a48..991490a187 100644
> --- a/notes-merge.c
> +++ b/notes-merge.c
> @@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct object_id *obj,
>     	fd = xopen(path, O_WRONLY | O_EXCL | O_CREAT, 0666);
>   -	while (size > 0) {
> -		ssize_t ret = write_in_full(fd, buf, size);
> -		if (ret < 0) {
> -			/* Ignore epipe */
> -			if (errno == EPIPE)
> -				break;
> -			die_errno("notes-merge");
> -		}
> -		size -= ret;
> -		buf += ret;
> -	}
> +	if (write_in_full(fd, buf, size) < 0 && errno != EPIPE)
> +		die_errno("notes-merge");
>     	close(fd);
>   	free(path);
> diff --git a/t/meson.build b/t/meson.build
> index 1cf1d95f70..8938d4eb47 100644
> --- a/t/meson.build
> +++ b/t/meson.build
> @@ -27,6 +27,7 @@ clar_test_suites = [
>     'unit-tests/u-trailer.c',
>     'unit-tests/u-urlmatch-normalization.c',
>     'unit-tests/u-utf8-width.c',
> +  'unit-tests/u-wrapper.c',
>   ]
>     clar_sources = [
> diff --git a/t/unit-tests/u-reftable-stack.c b/t/unit-tests/u-reftable-stack.c
> index b6f1c6cc52..3e19f0466a 100644
> --- a/t/unit-tests/u-reftable-stack.c
> +++ b/t/unit-tests/u-reftable-stack.c
> @@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)
>     	cl_assert(fd > 0);
>   	n = write_in_full(fd, out, strlen(out));
> -	cl_assert_equal_i(n, strlen(out));
> +	cl_assert_equal_i(n, 0);
>   	err = close(fd);
>   	cl_assert(err >= 0);
>   diff --git a/t/unit-tests/u-wrapper.c b/t/unit-tests/u-wrapper.c
> new file mode 100644
> index 0000000000..713ac0df92
> --- /dev/null
> +++ b/t/unit-tests/u-wrapper.c
> @@ -0,0 +1,42 @@
> +#include "unit-test.h"
> +#include "tempfile.h"
> +
> +static struct tempfile *file;
> +static char data[128 * 1024], actual[sizeof(data)];
> +
> +void test_wrapper__initialize(void)
> +{
> +	file = mks_tempfile("wrapper-test-XXXXXX");
> +	cl_assert(file != NULL);
> +	for (size_t i = 0; i < sizeof(data); i++)
> +		data[i] = i % 127;
> +	memset(actual, 0, sizeof(actual));
> +}
> +
> +void test_wrapper__cleanup(void)
> +{
> +	delete_tempfile(&file);
> +}
> +
> +void test_wrapper__write_in_full(void)
> +{
> +	int fd = get_tempfile_fd(file);
> +
> +	cl_assert_equal_i(write_in_full(fd, data, sizeof(data)), 0);
> +	cl_assert(lseek(fd, 0, SEEK_SET) == 0);
> +	cl_assert(read_in_full(fd, actual, sizeof(actual)) ==
> +		  (ssize_t)sizeof(actual));
> +	cl_assert(!memcmp(data, actual, sizeof(data)));
> +}
> +
> +void test_wrapper__write_in_full_empty(void)
> +{
> +	cl_assert_equal_i(write_in_full(-1, NULL, 0), 0);
> +}
> +
> +void test_wrapper__write_in_full_error(void)
> +{
> +	errno = 0;
> +	cl_assert_equal_i(write_in_full(-1, data, 1), -1);
> +	cl_assert_equal_i(errno, EBADF);
> +}
> diff --git a/wrapper.c b/wrapper.c
> index 05a9cd369c..87e1b4bfd2 100644
> --- a/wrapper.c
> +++ b/wrapper.c
> @@ -302,10 +302,9 @@ ssize_t read_in_full(int fd, void *buf, size_t count)
>   	return total;
>   }
>   -ssize_t write_in_full(int fd, const void *buf, size_t count)
> +int write_in_full(int fd, const void *buf, size_t count)
>   {
>   	const char *p = buf;
> -	ssize_t total = 0;
>     	while (count > 0) {
>   		ssize_t written = xwrite(fd, p, count);
> @@ -317,10 +316,9 @@ ssize_t write_in_full(int fd, const void *buf, size_t count)
>   		}
>   		count -= written;
>   		p += written;
> -		total += written;
>   	}
>   -	return total;
> +	return 0;
>   }
>     ssize_t xwritev(int fd, struct iovec *iov, int iovcnt)
> diff --git a/wrapper.h b/wrapper.h
> index a6287d7f4d..726c5c2f6b 100644
> --- a/wrapper.h
> +++ b/wrapper.h
> @@ -45,7 +45,10 @@ int git_mkstemps_mode(char *pattern, int suffix_len, int mode);
>   int git_mkstemp_mode(char *pattern, int mode);
>     ssize_t read_in_full(int fd, void *buf, size_t count);
> -ssize_t write_in_full(int fd, const void *buf, size_t count);
> +
> +/* Return 0 on a complete write, or -1 with errno set on failure. */
> +int write_in_full(int fd, const void *buf, size_t count);
> +
>   ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset);
>     /*
> @@ -57,7 +60,7 @@ ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset);
>    */
>   ssize_t writev_in_full(int fd, struct iovec *iov, int iovcnt);
>   -static inline ssize_t write_str_in_full(int fd, const char *str)
> +static inline int write_str_in_full(int fd, const char *str)
>   {
>   	return write_in_full(fd, str, strlen(str));
>   }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi Phillip,

On Tue, 24 Nov 2026, Phillip Wood wrote:

> On 23/11/2026 22:13, Johannes Schindelin via GitGitGadget wrote:
> > From: Johannes Schindelin <johannes.schindelin@gmx.de>
> > 
> > Accumulating the output count in `write_in_full()` can overflow because
> > it counts via a `ssize_t` variable which can overflow for valid `size_t`
> > sizes passed as input.
> > 
> > Since this function either completes the requested count or fails,
> > callers already know how many bytes were written on success. Let's just
> > return status instead, so the total transfer size need not fit in
> > `ssize_t`.
> 
> This makes perfect sense and the changes in this patch all look good. Looking
> at how the callers of write_in_full() use the return value, there are a few we
> might want to tweak.
> 
> In config.c write_section() and write_pair() both return the result of
> write_in_full(). All of the callers of those functions are only interested in
> whether the return value was negative, so there is no problem with the change
> in behavior, but we might want to change the return value to an int to match
> the new prototype of write_in_full().
> 
> In entry.c:write_entry() and parallel-checkout.c:write_pc_item_to_fd() we're
> still using a ssize_t to store the return value even though it is now an int.
> 
> In odb/streaming.c:odb_stream_blob_to_fd() we're also storing the return value
> in a ssize_t. Unlike the cases above we can simply avoid storing the value at
> all.
> 
> One final note - in refs.c:transaction_hook_feed_stdin(),
> sequencer.c:pipe_from_strbuf() and transport.c:pre_push_hook_feed_stdin()
> we're storing the result in an int and then checking if it is negative, so
> this patch actually fixes potential bugs in those callers.

Great call-out! I adjusted the callers accordingly.

Thank you,
Johannes

> Thanks
> 
> Phillip
> 
> 
> 
> > Pointed out by Coverity.
> > 
> > Helped-by: Phillip Wood <phillip.wood@dunelm.org.uk>
> > Assisted-by: GPT-6.1
> > Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
> > ---
> >   Makefile                        |  1 +
> >   imap-send.c                     |  2 +-
> >   notes-merge.c                   | 13 ++--------
> >   t/meson.build                   |  1 +
> >   t/unit-tests/u-reftable-stack.c |  2 +-
> >   t/unit-tests/u-wrapper.c        | 42 +++++++++++++++++++++++++++++++++
> >   wrapper.c                       |  6 ++---
> >   wrapper.h                       |  7 ++++--
> >   8 files changed, 55 insertions(+), 19 deletions(-)
> >   create mode 100644 t/unit-tests/u-wrapper.c
> > 
> > diff --git a/Makefile b/Makefile
> > index 4c84eea6e2..0687eb82d3 100644
> > --- a/Makefile
> > +++ b/Makefile
> > @@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec
> >   CLAR_TEST_SUITES += u-trailer
> >   CLAR_TEST_SUITES += u-urlmatch-normalization
> >   CLAR_TEST_SUITES += u-utf8-width
> > +CLAR_TEST_SUITES += u-wrapper
> >   CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X)
> >   CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES))
> >   CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
> > diff --git a/imap-send.c b/imap-send.c
> > index bf1d2cf74d..dccc2264de 100644
> > --- a/imap-send.c
> > +++ b/imap-send.c
> > @@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const
> > char *buf, int len)
> >    	n = SSL_write(sock->ssl, buf, len);
> >   	else
> >   #endif
> > -		n = write_in_full(sock->fd[1], buf, len);
> > +		n = write_in_full(sock->fd[1], buf, len) < 0 ? -1 : len;
> >    if (n != len) {
> >     socket_perror("write", sock, n);
> >     close(sock->fd[0]);
> > diff --git a/notes-merge.c b/notes-merge.c
> > index d361e70a48..991490a187 100644
> > --- a/notes-merge.c
> > +++ b/notes-merge.c
> > @@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct
> > object_id *obj,
> >   
> >    fd = xopen(path, O_WRONLY | O_EXCL | O_CREAT, 0666);
> >   -	while (size > 0) {
> > -		ssize_t ret = write_in_full(fd, buf, size);
> > -		if (ret < 0) {
> > -			/* Ignore epipe */
> > -			if (errno == EPIPE)
> > -				break;
> > -			die_errno("notes-merge");
> > -		}
> > -		size -= ret;
> > -		buf += ret;
> > -	}
> > +	if (write_in_full(fd, buf, size) < 0 && errno != EPIPE)
> > +		die_errno("notes-merge");
> >   
> >    close(fd);
> >    free(path);
> > diff --git a/t/meson.build b/t/meson.build
> > index 1cf1d95f70..8938d4eb47 100644
> > --- a/t/meson.build
> > +++ b/t/meson.build
> > @@ -27,6 +27,7 @@ clar_test_suites = [
> >     'unit-tests/u-trailer.c',
> >     'unit-tests/u-urlmatch-normalization.c',
> >     'unit-tests/u-utf8-width.c',
> > +  'unit-tests/u-wrapper.c',
> > ]
> >   
> >   clar_sources = [
> > diff --git a/t/unit-tests/u-reftable-stack.c
> > b/t/unit-tests/u-reftable-stack.c
> > index b6f1c6cc52..3e19f0466a 100644
> > --- a/t/unit-tests/u-reftable-stack.c
> > +++ b/t/unit-tests/u-reftable-stack.c
> > @@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)
> >   
> >    cl_assert(fd > 0);
> >    n = write_in_full(fd, out, strlen(out));
> > -	cl_assert_equal_i(n, strlen(out));
> > +	cl_assert_equal_i(n, 0);
> >    err = close(fd);
> >    cl_assert(err >= 0);
> >   diff --git a/t/unit-tests/u-wrapper.c b/t/unit-tests/u-wrapper.c
> > new file mode 100644
> > index 0000000000..713ac0df92
> > --- /dev/null
> > +++ b/t/unit-tests/u-wrapper.c
> > @@ -0,0 +1,42 @@
> > +#include "unit-test.h"
> > +#include "tempfile.h"
> > +
> > +static struct tempfile *file;
> > +static char data[128 * 1024], actual[sizeof(data)];
> > +
> > +void test_wrapper__initialize(void)
> > +{
> > +	file = mks_tempfile("wrapper-test-XXXXXX");
> > +	cl_assert(file != NULL);
> > +	for (size_t i = 0; i < sizeof(data); i++)
> > +		data[i] = i % 127;
> > +	memset(actual, 0, sizeof(actual));
> > +}
> > +
> > +void test_wrapper__cleanup(void)
> > +{
> > +	delete_tempfile(&file);
> > +}
> > +
> > +void test_wrapper__write_in_full(void)
> > +{
> > +	int fd = get_tempfile_fd(file);
> > +
> > +	cl_assert_equal_i(write_in_full(fd, data, sizeof(data)), 0);
> > +	cl_assert(lseek(fd, 0, SEEK_SET) == 0);
> > +	cl_assert(read_in_full(fd, actual, sizeof(actual)) ==
> > +		  (ssize_t)sizeof(actual));
> > +	cl_assert(!memcmp(data, actual, sizeof(data)));
> > +}
> > +
> > +void test_wrapper__write_in_full_empty(void)
> > +{
> > +	cl_assert_equal_i(write_in_full(-1, NULL, 0), 0);
> > +}
> > +
> > +void test_wrapper__write_in_full_error(void)
> > +{
> > +	errno = 0;
> > +	cl_assert_equal_i(write_in_full(-1, data, 1), -1);
> > +	cl_assert_equal_i(errno, EBADF);
> > +}
> > diff --git a/wrapper.c b/wrapper.c
> > index 05a9cd369c..87e1b4bfd2 100644
> > --- a/wrapper.c
> > +++ b/wrapper.c
> > @@ -302,10 +302,9 @@ ssize_t read_in_full(int fd, void *buf, size_t count)
> >   	return total;
> >   }
> >   
> > -ssize_t write_in_full(int fd, const void *buf, size_t count)
> > +int write_in_full(int fd, const void *buf, size_t count)
> >   {
> >   	const char *p = buf;
> > -	ssize_t total = 0;
> >   
> >    while (count > 0) {
> >   		ssize_t written = xwrite(fd, p, count);
> > @@ -317,10 +316,9 @@ ssize_t write_in_full(int fd, const void *buf, size_t
> > count)
> >     }
> >     count -= written;
> >     p += written;
> > -		total += written;
> >    }
> >   -	return total;
> > +	return 0;
> >   }
> >   
> >   ssize_t xwritev(int fd, struct iovec *iov, int iovcnt)
> > diff --git a/wrapper.h b/wrapper.h
> > index a6287d7f4d..726c5c2f6b 100644
> > --- a/wrapper.h
> > +++ b/wrapper.h
> > @@ -45,7 +45,10 @@ int git_mkstemps_mode(char *pattern, int suffix_len, int
> > mode);
> >   int git_mkstemp_mode(char *pattern, int mode);
> >   
> >   ssize_t read_in_full(int fd, void *buf, size_t count);
> > -ssize_t write_in_full(int fd, const void *buf, size_t count);
> > +
> > +/* Return 0 on a complete write, or -1 with errno set on failure. */
> > +int write_in_full(int fd, const void *buf, size_t count);
> > +
> >   ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset);
> >   
> >   /*
> > @@ -57,7 +60,7 @@ ssize_t pread_in_full(int fd, void *buf, size_t count,
> > off_t offset);
> >   */
> >   ssize_t writev_in_full(int fd, struct iovec *iov, int iovcnt);
> >   
> > -static inline ssize_t write_str_in_full(int fd, const char *str)
> > +static inline int write_str_in_full(int fd, const char *str)
> >   {
> >   	return write_in_full(fd, str, strlen(str));
> >   }
> 
> 

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:

> From: Johannes Schindelin <johannes.schindelin@gmx.de>
>
> Accumulating the output count in `write_in_full()` can overflow because
> it counts via a `ssize_t` variable which can overflow for valid `size_t`
> sizes passed as input.
>
> Since this function either completes the requested count or fails,
> callers already know how many bytes were written on success. Let's just
> return status instead, so the total transfer size need not fit in
> `ssize_t`.

This is a great simplification.

"git grep write_in_full(" shows quite a lot of hits.

 - Surprising number of them are totally unchecked, calledin the void
   context.

 - Many are in the form:

	if (write_in_full(...) < 0)

   and presumably this update to return -1 on error should be safe on them.

And the rest would need to be audited and updated, like this one:

> diff --git a/imap-send.c b/imap-send.c
> index bf1d2cf74d..dccc2264de 100644
> --- a/imap-send.c
> +++ b/imap-send.c
> @@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len)
>  		n = SSL_write(sock->ssl, buf, len);
>  	else
>  #endif
> -		n = write_in_full(sock->fd[1], buf, len);
> +		n = write_in_full(sock->fd[1], buf, len) < 0 ? -1 : len;
>  	if (n != len) {

which looks correct.

> diff --git a/notes-merge.c b/notes-merge.c
> index d361e70a48..991490a187 100644
> --- a/notes-merge.c
> +++ b/notes-merge.c
> @@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct object_id *obj,
>  
>  	fd = xopen(path, O_WRONLY | O_EXCL | O_CREAT, 0666);
>  
> -	while (size > 0) {
> -		ssize_t ret = write_in_full(fd, buf, size);
> -		if (ret < 0) {
> -			/* Ignore epipe */
> -			if (errno == EPIPE)
> -				break;
> -			die_errno("notes-merge");
> -		}
> -		size -= ret;
> -		buf += ret;
> -	}
> +	if (write_in_full(fd, buf, size) < 0 && errno != EPIPE)
> +		die_errno("notes-merge");

Hmph, what is going on here.  Did the original not know write_in_full()
would not return until it fails or writes everything?  It comes from
809f38c8ab (git notes merge: Manual conflict resolution, part 1/2,
2010-11-09) that is ancient, and was touched by Peff in 634eb82b1a
(notes-merge: use ssize_t for write_in_full() return value, 2017-09-13)
to correct the type from "long ret" to "ssize_t ret".  I guess nobody
noticed when these two patches was reviewed.

I didn't check what is *not* touched by the patch, trusting your LLM did
the heavylifting for you ;-).

Thanks.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Phillip Wood wrote on the Git mailing list (how to reply to this email):

On 25/11/2026 23:47, Junio C Hamano wrote:
> "Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:
> 
>> From: Johannes Schindelin <johannes.schindelin@gmx.de>
>>
>> Accumulating the output count in `write_in_full()` can overflow because
>> it counts via a `ssize_t` variable which can overflow for valid `size_t`
>> sizes passed as input.
>>
>> Since this function either completes the requested count or fails,
>> callers already know how many bytes were written on success. Let's just
>> return status instead, so the total transfer size need not fit in
>> `ssize_t`.
> 
> This is a great simplification.

Yes, it's a much nicer api

> I didn't check what is *not* touched by the patch, trusting your LLM did
> the heavylifting for you ;-).
When I reviewed the last round, I grepped for '= *write_in_full' and 'return write_in_full'. This round fixes all the issues I found with that.

Thanks

Phillip

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi,

On Thu, 26 Nov 2026, Phillip Wood wrote:

> On 25/11/2026 23:47, Junio C Hamano wrote:
> > "Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:
> > 
> > > From: Johannes Schindelin <johannes.schindelin@gmx.de>
> > >
> > > Accumulating the output count in `write_in_full()` can overflow because
> > > it counts via a `ssize_t` variable which can overflow for valid `size_t`
> > > sizes passed as input.
> > >
> > > Since this function either completes the requested count or fails,
> > > callers already know how many bytes were written on success. Let's just
> > > return status instead, so the total transfer size need not fit in
> > > `ssize_t`.
> > 
> > This is a great simplification.
> 
> Yes, it's a much nicer api
> 
> > I didn't check what is *not* touched by the patch, trusting your LLM did
> > the heavylifting for you ;-).
> When I reviewed the last round, I grepped for '= *write_in_full' and 'return
> write_in_full'. This round fixes all the issues I found with that.

Yes, I also grepped for `write_in_full` and didn't spot anything else to
address.

Ciao,
Johannes

CLAR_TEST_SUITES += u-urlmatch-normalization
CLAR_TEST_SUITES += u-utf8-width
CLAR_TEST_SUITES += u-wrapper
CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X)
CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES))
CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
Expand Down
2 changes: 2 additions & 0 deletions archive-tar.c
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen)
i--;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:

> From: Johannes Schindelin <johannes.schindelin@gmx.de>
>
> The `get_path_prefix()` function uses a `do ... while()` loop that
> unconditionally decrements the `size_t` index variable before checking
> the loop condition. When that variable is 0 on entry, the decrement
> wraps to `SIZE_MAX`, and `path[SIZE_MAX]` is an out-of-bounds read.
>
> The current caller (`write_tar_entry()`) only invokes this function when
> `pathlen > sizeof(header.name)` i.e. when `pathlen` is at least 100.
> Therefore, the bug is unreachable in practice.

There is an off-by-one here.  Because header.name is 100 bytes in struct
ustar_header, `pathlen > sizeof(header.name)` means pathlen is at least
101.

It indeed is unreachable in practice ;-)

> diff --git a/archive-tar.c b/archive-tar.c
> index a1c66024d4..2da6e55484 100644
> --- a/archive-tar.c
> +++ b/archive-tar.c
> @@ -210,6 +210,8 @@ static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen)
>  		i--;
>  	if (i > maxlen)
>  		i = maxlen;
> +	if (!i)
> +		return 0;
>  	do {
>  		i--;
>  	} while (i > 0 && path[i] != '/');

Guarding against 'i == 0' after capping to 'maxlen' protects against
both zero 'pathlen' and zero 'maxlen' before entering the 'do ... while'
decrement, while leaving 'pathlen == 1' (e.g., "/") and all longer paths
unchanged.

Looks good to me.  Thanks.

if (i > maxlen)
i = maxlen;
if (!i)
return 0;
do {
i--;
} while (i > 0 && path[i] != '/');
Expand Down
2 changes: 1 addition & 1 deletion builtin/blame.c
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,7 @@ static void parse_default_ignore_revs_file(struct blame_scoreboard *sb,
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:

> From: Johannes Schindelin <johannes.schindelin@gmx.de>

Thanks.  In this step, I only saw a few minor nits.

> Callers of the `read_in_full()` function want to read all requested
> bytes, or get an error. However, limiting the return value type to
> `ssize_t` is insufficient, as file sizes can easily exceed that type's
> range.
>
> For those callers that do not require the return value to report the
> number of read bytes, add a new function, `read_in_full_or_error()`,
> that returns a Boolean to indicate success or faiure.

It returns an int to indicate success or failure.  It is moral parallel
to returning a Boolean, but the polarity is reversed (0 is success, a
negative is failure, following our usual convention).

> Callers that do need to know that byte count can still call
> `read_in_full()`, but will now error out early if the requested byte
> count exceeds what `ssize_t` can represent.

"error out early" -> "abort to signal a programming error".

read_in_full() aborts with BUG() when the requested byte count exceeds
ssize_t max, instead of erroring out.  We declare that our API contract
is that count passed to read_in_full() must fit in ssize_t, so that any
positive return value from the function reliably means a successful
read, and in such a world, passing overly large count is a programming
error (i.e., the caller must be written to check) and aborting with
BUG() is perfetly fine.  Let's document that design decision here in the
log message.

Looking at the whole working tree after applying this series, all
remaining callers of read_in_full() are small or explicitly bounded
(setup.c, object-file.c, http-backend.c, pkt-line.c, odb/streaming.c).

Except that worktree.c:should_prune_worktree() passes size_t len that is
computed as xsize_t(st.st_size) for a .git gitdir file.  While gitdir
files are tiny in practice, converting it to read_in_full_or_error()
would be consistent with the other st.st_size conversions.

> +/*
> + * Read until count bytes have been read or EOF. On success, store the number
> + * read in out if non-NULL. Return false on an I/O error, with errno set.
> + */
> +static bool read_in_full_1(int fd, void *buf, size_t count, size_t *out)
>  {
>  	char *p = buf;
> -	ssize_t total = 0;
> +	size_t remaining = count;
>  
> -	while (count > 0) {
> -		ssize_t loaded = xread(fd, p, count);
> +	while (remaining) {
> +		ssize_t loaded = xread(fd, p, remaining);
>  		if (loaded < 0)
> -			return -1;
> -		if (loaded == 0)
> -			return total;
> -		count -= loaded;
> +			return false;
> +		if (!loaded)
> +			break;
> +		remaining -= loaded;
>  		p += loaded;
> -		total += loaded;
>  	}
>  
> -	return total;
> +	if (out)
> +		*out = count - remaining;

All two callers of this file-scope static helper passes &total, so this
reporting of the total count can and should be done unconditionally.

> +	return true;
> +}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:

> From: Johannes Schindelin <johannes.schindelin@gmx.de>
>
> Callers of the `read_in_full()` function want to read all requested
> bytes, or get an error. However, limiting the return value type to
> `ssize_t` is insufficient, as file sizes can easily exceed that type's
> range.
>
> For those callers that do not require the return value to report the
> number of read bytes, add a new function, `read_in_full_or_error()`,
> that returns a Boolean to indicate success or faiure.

It returns an int to indicate success or failure (not "faiure").  It is
moral parallel to returning a Boolean, but the polarity is reversed (0
is success, a negative is failure, following our usual convention).

> +static bool read_in_full_1(int fd, void *buf, size_t count, size_t *out)
>  {
>  	char *p = buf;
> -	ssize_t total = 0;
> +	size_t remaining = count;
>  
> -	while (count > 0) {
> -		ssize_t loaded = xread(fd, p, count);
> +	while (remaining) {
> +		ssize_t loaded = xread(fd, p, remaining);
>  		if (loaded < 0)
> -			return -1;
> -		if (loaded == 0)
> -			return total;
> -		count -= loaded;
> +			return false;
> +		if (!loaded)
> +			break;
> +		remaining -= loaded;
>  		p += loaded;
> -		total += loaded;
>  	}
>  
> -	return total;
> +	if (out)
> +		*out = count - remaining;
> +	return true;
> +}

All two callers of this file-scope static helper passes &total, so this
reporting of the total count can and should be done unconditionally.

Looking at the whole working tree after applying this series, all
remaining callers of read_in_full() are small or explicitly bounded.

The only exception is worktree.c:should_prune_worktree().

It passes size_t len that is computed as xsize_t(st.st_size) for a .git
gitdir file.  While gitdir files are tiny in practice, converting it to
read_in_full_or_error() would be consistent with the other st.st_size
conversions.

Thanks.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi,

On Wed, 25 Nov 2026, Junio C Hamano wrote:

> "Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:
> 
> > From: Johannes Schindelin <johannes.schindelin@gmx.de>
> >
> > Callers of the `read_in_full()` function want to read all requested
> > bytes, or get an error. However, limiting the return value type to
> > `ssize_t` is insufficient, as file sizes can easily exceed that type's
> > range.
> >
> > For those callers that do not require the return value to report the
> > number of read bytes, add a new function, `read_in_full_or_error()`,
> > that returns a Boolean to indicate success or faiure.
> 
> It returns an int to indicate success or failure (not "faiure").  It is
> moral parallel to returning a Boolean, but the polarity is reversed (0
> is success, a negative is failure, following our usual convention).

Yes. And well-spotted, I fixed the typo.

> > +static bool read_in_full_1(int fd, void *buf, size_t count, size_t *out)
> >  {
> >  	char *p = buf;
> > -	ssize_t total = 0;
> > +	size_t remaining = count;
> >  
> > -	while (count > 0) {
> > -		ssize_t loaded = xread(fd, p, count);
> > +	while (remaining) {
> > +		ssize_t loaded = xread(fd, p, remaining);
> >  		if (loaded < 0)
> > -			return -1;
> > -		if (loaded == 0)
> > -			return total;
> > -		count -= loaded;
> > +			return false;
> > +		if (!loaded)
> > +			break;
> > +		remaining -= loaded;
> >  		p += loaded;
> > -		total += loaded;
> >  	}
> >  
> > -	return total;
> > +	if (out)
> > +		*out = count - remaining;
> > +	return true;
> > +}
> 
> All two callers of this file-scope static helper passes &total, so this
> reporting of the total count can and should be done unconditionally.

Thank you for catching this. I don't know how that slipped through.

> Looking at the whole working tree after applying this series, all
> remaining callers of read_in_full() are small or explicitly bounded.
> 
> The only exception is worktree.c:should_prune_worktree().
> 
> It passes size_t len that is computed as xsize_t(st.st_size) for a .git
> gitdir file.  While gitdir files are tiny in practice, converting it to
> read_in_full_or_error() would be consistent with the other st.st_size
> conversions.

Yes. It _is_ a change in behavior because it now no longer reports a short
read, but an I/O error.

On the other hand, it simplifies the code, and that's always a good thing,
right? So I made that change.

Ciao,
Johannes

size = xsize_t(st.st_size);
buf = xmalloc(size);
if (read_in_full(fd, buf, size) == (ssize_t)size)
if (!read_in_full_or_error(fd, buf, size))
oidset_parse_buffer_carefully(&sb->ignore_list, buf, size,
sb->repo->hash_algo,
peel_to_commit_oid, sb);
Expand Down
6 changes: 1 addition & 5 deletions combine-diff.c
Original file line number Diff line number Diff line change
Expand Up @@ -1073,7 +1073,6 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent,
free_filespec(df);
} else if (0 <= (fd = open(elem->path, O_RDONLY))) {
size_t len = xsize_t(st.st_size);
ssize_t done;
int is_file, i;

elem->mode = canon_mode(st.st_mode);
Expand All @@ -1089,11 +1088,8 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent,
result_size = len;
result = xmallocz(len);

done = read_in_full(fd, result, len);
if (done < 0)
if (read_in_full_or_error(fd, result, len) < 0)
die_errno("read error '%s'", elem->path);
else if (done < len)
die("early EOF '%s'", elem->path);

/* If not a fake symlink, apply filters, e.g. autocrlf */
if (is_file) {
Expand Down
14 changes: 7 additions & 7 deletions config.c
Original file line number Diff line number Diff line change
Expand Up @@ -2768,24 +2768,24 @@ static struct strbuf store_create_section(const char *key,
return sb;
}

static ssize_t write_section(int fd, const char *key,
const struct config_store_data *store)
static int write_section(int fd, const char *key,
const struct config_store_data *store)
{
struct strbuf sb = store_create_section(key, store);
ssize_t ret;
int ret;

ret = write_in_full(fd, sb.buf, sb.len);
strbuf_release(&sb);

return ret;
}

static ssize_t write_pair(int fd, const char *key, const char *value,
const char *comment,
const struct config_store_data *store)
static int write_pair(int fd, const char *key, const char *value,
const char *comment,
const struct config_store_data *store)
{
int i;
ssize_t ret;
int ret;
const char *quote = "";
struct strbuf sb = STRBUF_INIT;

Expand Down
44 changes: 35 additions & 9 deletions date.c
Original file line number Diff line number Diff line change
Expand Up @@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
while (tl->type) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com>
writes:

> On platforms where `time_t` is unsigned (and where the pre-processor
> allows us to determine this fact), reject counts that are too large and
> report a parse error. Narrowing them first could otherwise produce
> negative or truncated values that become bogus offsets. Leave signed
> `time_t` count parsing unchanged.

Does this mean that "git log -p" in a project that were made on
reasonably sized platforms and then cloned to my box may cause the
history traversal to stop with an error when a commit has author or
committer timestamp that would not fit the time_t on my box?

It would have been horrible regression than showing the entire
history with patches with bogus timestamp if it were the case.

But I do not think that is what happens.  approxidate_careful() is
only used to parse input by local user (e.g., "git commit
--date="...", "git log @{...}"), and the changes in this patch would
not affect behaviours of other uses of timestamps, so we are safe.

> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
> ---
>  date.c | 26 ++++++++++++++++++++++++--
>  1 file changed, 24 insertions(+), 2 deletions(-)
>
> diff --git a/date.c b/date.c
> index 014065b419..0d65804d2f 100644
> --- a/date.c
> +++ b/date.c
> @@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
>  	while (tl->type) {
>  		size_t len = strlen(tl->type);
>  		if (match_string(date, tl->type) >= len-1) {
> -			update_tm(tm, now, tl->length * *num);
> +			time_t length = tl->length, num_t = *num;
> +			time_t seconds;
> +#ifndef is_unsigned_type
> +			seconds = length * num_t;
> +#else
> +			time_t max_val = is_unsigned_type(length)
> +				? maximum_unsigned_value_of_type(length)
> +				: maximum_signed_value_of_type(length);
> +			seconds = mult_overflows(length, num_t)
> +				? max_val : length * num_t;
> +#endif
> +			update_tm(tm, now, seconds);
>  			*num = 0;
>  			*touched = 1;
>  			return end;
> @@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
>  	}
>  
>  	/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
> -	if (date[0] != '0' || end - date <= 2)
> +	if (date[0] != '0' || end - date <= 2) {
> +#ifdef is_unsigned_type
> +		if (is_unsigned_type((time_t)0) &&
> +		    (number > INT_MAX ||
> +		     number > maximum_unsigned_value_of_type((time_t)0)))
> +			return NULL;
> +#endif
>  		*num = number;
> +	}
>  	return end;
>  }
>  
> @@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,
>  		if (isdigit(c)) {
>  			pending_number(&tm, &number);
>  			date = approxidate_digit(date-1, &tm, &number, time_sec);
> +			if (!date) {
> +				*error_ret = 1;
> +				return 0;
> +			}
>  			touched = 1;
>  			continue;
>  		}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Phillip Wood wrote on the Git mailing list (how to reply to this email):

Hi Johannes

On 14/10/2026 07:09, Johannes Schindelin via GitGitGadget wrote:
> From: Johannes Schindelin <johannes.schindelin@gmx.de>
> > The `approxidate_alpha()` function multiplies a time unit length (e.g.,
> 604800 for weeks) by a user-supplied number to compute a time offset in
> seconds. Both operands are `int`, and the product is passed to
> `update_tm()` as `time_t`. For inputs like "99999 weeks ago", the int
> multiplication overflows (604800 * 99999 is roughly 60 billion, far
> beyond `INT_MAX`), producing a wrapped value that results in a wrong
> date.

Signed integer overflow is undefined so we don't necessarily get a wrapped value - the whole program is invalid.

It looks like "length" is always positive, can the user supplied number ever be negative?

> Use the checked `time_t` multiplication so oversized products do not
> overflow or wrap around.

This is only true when compiling with gcc or clang though because mult_overflows() always returns 0 on other compilers, so we're still exposed to undefined behavior when compiling with a different compiler on platforms where time_t is signed. I wonder if it would be better to perform the multiplication on a known type and then check that the result can be losslessly converted to time_t

	intmax_t length tl->length, num_t = *num, result;

	if (signed_mult_overflows(length, num_t))
		// error
	result = length * num_t;
	if ((intmax_t)((time_t)result) != result ||
	    (result < 0 && (time_t)result > 0))
		// error

that would avoid overflow on all platforms, regardless of the compiler and regardless of the type of time_t. Having mult_overflows() only implemented for gcc seems like a footgun waiting to happen when we're typically checking for overflow to avoid some form of bad behavior.

> On platforms where `time_t` is unsigned (and where the pre-processor
> allows us to determine this fact), reject counts that are too large and
> report a parse error. Narrowing them first could otherwise produce
> negative or truncated values that become bogus offsets. Leave signed
> `time_t` count parsing unchanged.

I'm a bit confused what this is trying to do - why can't we check this when time_t is signed?

	if ((timestamp_t)((int)number) != number)
		return NULL

	return *val = value;

Ensures "value" fits in "val" without truncation, we could also add a check that value is positive when time_t is unsigned if we wanted.

Thanks

Phillip
> Pointed out by Coverity.
> > Assisted-by: Claude Opus 4.6 and GPT-6.1 Sol
> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
> ---
>   date.c | 26 ++++++++++++++++++++++++--
>   1 file changed, 24 insertions(+), 2 deletions(-)
> > diff --git a/date.c b/date.c
> index 014065b419..0d65804d2f 100644
> --- a/date.c
> +++ b/date.c
> @@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
>   	while (tl->type) {
>   		size_t len = strlen(tl->type);
>   		if (match_string(date, tl->type) >= len-1) {
> -			update_tm(tm, now, tl->length * *num);
> +			time_t length = tl->length, num_t = *num;
> +			time_t seconds;
> +#ifndef is_unsigned_type
> +			seconds = length * num_t;
> +#else
> +			time_t max_val = is_unsigned_type(length)
> +				? maximum_unsigned_value_of_type(length)
> +				: maximum_signed_value_of_type(length);
> +			seconds = mult_overflows(length, num_t)
> +				? max_val : length * num_t;
> +#endif
> +			update_tm(tm, now, seconds);
>   			*num = 0;
>   			*touched = 1;
>   			return end;
> @@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
>   	}
>   >   	/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
> -	if (date[0] != '0' || end - date <= 2)
> +	if (date[0] != '0' || end - date <= 2) {
> +#ifdef is_unsigned_type
> +		if (is_unsigned_type((time_t)0) &&
> +		    (number > INT_MAX ||
> +		     number > maximum_unsigned_value_of_type((time_t)0)))
> +			return NULL;
> +#endif
>   		*num = number;
> +	}
>   	return end;
>   }
>   > @@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,
>   		if (isdigit(c)) {
>   			pending_number(&tm, &number);
>   			date = approxidate_digit(date-1, &tm, &number, time_sec);
> +			if (!date) {
> +				*error_ret = 1;
> +				return 0;
> +			}
>   			touched = 1;
>   			continue;
>   		}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi Phillip,

On Thu, 15 Oct 2026, Phillip Wood wrote:

> On 14/10/2026 07:09, Johannes Schindelin via GitGitGadget wrote:
> > From: Johannes Schindelin <johannes.schindelin@gmx.de>
> > 
> > The `approxidate_alpha()` function multiplies a time unit length (e.g.,
> > 604800 for weeks) by a user-supplied number to compute a time offset in
> > seconds. Both operands are `int`, and the product is passed to
> > `update_tm()` as `time_t`. For inputs like "99999 weeks ago", the int
> > multiplication overflows (604800 * 99999 is roughly 60 billion, far
> > beyond `INT_MAX`), producing a wrapped value that results in a wrong
> > date.
> 
> Signed integer overflow is undefined so we don't necessarily get a wrapped
> value - the whole program is invalid.
> 
> It looks like "length" is always positive, can the user supplied number ever
> be negative?

Indeed, length cannot be negative. My entire approach was overzealous.
I've simply replaced the logic with much easier-to-review manual overflow
checks.

> > Use the checked `time_t` multiplication so oversized products do not
> > overflow or wrap around.
> 
> This is only true when compiling with gcc or clang though because
> mult_overflows() always returns 0 on other compilers, so we're still exposed
> to undefined behavior when compiling with a different compiler on platforms
> where time_t is signed. I wonder if it would be better to perform the
> multiplication on a known type and then check that the result can be
> losslessly converted to time_t
> 
> 	intmax_t length tl->length, num_t = *num, result;
> 
> 	if (signed_mult_overflows(length, num_t))
> 		// error
> 	result = length * num_t;
> 	if ((intmax_t)((time_t)result) != result ||
> 	    (result < 0 && (time_t)result > 0))
> 		// error
> 
> that would avoid overflow on all platforms, regardless of the compiler and
> regardless of the type of time_t. Having mult_overflows() only implemented for
> gcc seems like a footgun waiting to happen when we're typically checking for
> overflow to avoid some form of bad behavior.

Yes, this GCC-only logic wasn't very smart of me.

> > On platforms where `time_t` is unsigned (and where the pre-processor
> > allows us to determine this fact), reject counts that are too large and
> > report a parse error. Narrowing them first could otherwise produce
> > negative or truncated values that become bogus offsets. Leave signed
> > `time_t` count parsing unchanged.
> 
> I'm a bit confused what this is trying to do - why can't we check this when
> time_t is signed?
> 
> 	if ((timestamp_t)((int)number) != number)
> 		return NULL
> 
> 	return *val = value;
> 
> Ensures "value" fits in "val" without truncation, we could also add a check
> that value is positive when time_t is unsigned if we wanted.

I simply did `if (number > INT_MAX) return NULL`.

Thank you for your thorough review!
Johannes

> 
> Thanks
> 
> Phillip
> > Pointed out by Coverity.
> > 
> > Assisted-by: Claude Opus 4.6 and GPT-6.1 Sol
> > Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
> > ---
> >   date.c | 26 ++++++++++++++++++++++++--
> >   1 file changed, 24 insertions(+), 2 deletions(-)
> > 
> > diff --git a/date.c b/date.c
> > index 014065b419..0d65804d2f 100644
> > --- a/date.c
> > +++ b/date.c
> > @@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char
> > *date, struct tm *tm, struct tm
> >    while (tl->type) {
> >     size_t len = strlen(tl->type);
> >     if (match_string(date, tl->type) >= len-1) {
> > -			update_tm(tm, now, tl->length * *num);
> > +			time_t length = tl->length, num_t = *num;
> > +			time_t seconds;
> > +#ifndef is_unsigned_type
> > +			seconds = length * num_t;
> > +#else
> > +			time_t max_val = is_unsigned_type(length)
> > +				? maximum_unsigned_value_of_type(length)
> > +				: maximum_signed_value_of_type(length);
> > +			seconds = mult_overflows(length, num_t)
> > +				? max_val : length * num_t;
> > +#endif
> > +			update_tm(tm, now, seconds);
> >      *num = 0;
> >      *touched = 1;
> >      return end;
> > @@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char
> > *date, struct tm *tm, int *num,
> >    }
> >   
> >   	/* Accept zero-padding only for small numbers ("Dec 02", never "Dec
> > 0002") */
> > -	if (date[0] != '0' || end - date <= 2)
> > +	if (date[0] != '0' || end - date <= 2) {
> > +#ifdef is_unsigned_type
> > +		if (is_unsigned_type((time_t)0) &&
> > +		    (number > INT_MAX ||
> > +		     number > maximum_unsigned_value_of_type((time_t)0)))
> > +			return NULL;
> > +#endif
> >   		*num = number;
> > +	}
> >   	return end;
> >   }
> >   
> > @@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,
> >     if (isdigit(c)) {
> >      pending_number(&tm, &number);
> >      date = approxidate_digit(date-1, &tm, &number, time_sec);
> > +			if (!date) {
> > +				*error_ret = 1;
> > +				return 0;
> > +			}
> >      touched = 1;
> >      continue;
> >     }
> 
> 
> 

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Phillip Wood wrote on the Git mailing list (how to reply to this email):

Hi Johannes

On 23/11/2026 22:13, Johannes Schindelin via GitGitGadget wrote:
> From: Johannes Schindelin <johannes.schindelin@gmx.de>
> 
> Parsing relative dates can overflow `int` when multiplying a value by a
> unit length, before converting the result to `time_t`. Signed overflow
> is undefined behavior, therefore checking the converted value is too
> late.
> 
> Reject quantities above `INT_MAX` before narrowing to `int` on all
> platforms. The inputs are non-negative, meaning that checking unsigned
> arithmetic is sufficient. The product must also fit the native `time_t`
> range. Report arithmetic or conversion failures as parse errors rather
> than saturating the offset.

This looks good and is much simpler than the previous version.

Thanks

Phillip

> Pointed out by Coverity.
> 
> Helped-by: Phillip Wood <phillip.wood@dunelm.org.uk>
> Assisted-by: Claude Opus 4.6 and GPT-6.1
> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
> ---
>   date.c          | 26 ++++++++++++++++++++------
>   t/t0006-date.sh | 13 +++++++++++++
>   2 files changed, 33 insertions(+), 6 deletions(-)
> 
> diff --git a/date.c b/date.c
> index c50f45d310..3cbfe20b37 100644
> --- a/date.c
> +++ b/date.c
> @@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
>   	while (tl->type) {
>   		size_t len = strlen(tl->type);
>   		if (match_string(date, tl->type) >= len-1) {
> -			update_tm(tm, now, tl->length * *num);
> +			uintmax_t length = tl->length, num_t = *num, seconds;
> +
> +			if (unsigned_mult_overflows(length, num_t))
> +				return NULL;
> +			seconds = length * num_t;
> +			if (date_overflows(seconds))
> +				return NULL;
> +			update_tm(tm, now, (time_t)seconds);
>   			*num = 0;
>   			*touched = 1;
>   			return end;
> @@ -1377,8 +1384,11 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
>   	}
>     	/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
> -	if (date[0] != '0' || end - date <= 2)
> +	if (date[0] != '0' || end - date <= 2) {
> +		if (number > INT_MAX)
> +			return NULL;
>   		*num = number;
> +	}
>   	return end;
>   }
>   @@ -1404,14 +1414,18 @@ static timestamp_t approxidate_str(const char *date,
>   		if (!c)
>   			break;
>   		date++;
> -		if (isdigit(c)) {
> +		if (isalpha(c))
> +			date = approxidate_alpha(date-1, &tm, &now,
> +						 &number, &touched);
> +		else if (isdigit(c)) {
>   			pending_number(&tm, &number);
>   			date = approxidate_digit(date-1, &tm, &number, time_sec);
>   			touched = 1;
> -			continue;
>   		}
> -		if (isalpha(c))
> -			date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
> +		if (!date) {
> +			*error_ret = 1;
> +			return 0;
> +		}
>   	}
>   	pending_number(&tm, &number);
>   	if (!touched)
> diff --git a/t/t0006-date.sh b/t/t0006-date.sh
> index 6e63130ea2..2a33aaa327 100755
> --- a/t/t0006-date.sh
> +++ b/t/t0006-date.sh
> @@ -211,6 +211,19 @@ check_approxidate 3.weeks.ago '2009-08-09 19:20:00'
>   check_approxidate 3.months.ago '2009-05-30 19:20:00'
>   check_approxidate 2.years.3.months.ago '2007-05-30 19:20:00'
>   +test_expect_success HAVE_64BIT_TIME 'parse a large number of weeks' '
> +	echo "Jan 1 2099 4000 weeks ago -> 1651778400" >expect &&
> +	test-tool date timestamp "Jan 1 2099 4000 weeks ago" >actual &&
> +	test_cmp expect actual
> +'
> +
> +test_expect_success TIME_IS_64BIT 'reject a quantity that does not fit in int' '
> +	git reflog expire --dry-run --all --expire="1 day 1 second ago" &&
> +	test_must_fail git reflog expire --dry-run --all \
> +		--expire="1 day 18446744073709551615 seconds ago" 2>err &&
> +	test_grep "invalid timestamp" err
> +'
> +
>   check_approxidate '6am yesterday' '2009-08-29 06:00:00'
>   check_approxidate '6pm yesterday' '2009-08-29 18:00:00'
>   check_approxidate '3:00' '2009-08-30 03:00:00'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:

> diff --git a/date.c b/date.c
> index c50f45d310..3cbfe20b37 100644
> --- a/date.c
> +++ b/date.c
> @@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
>  	while (tl->type) {
>  		size_t len = strlen(tl->type);
>  		if (match_string(date, tl->type) >= len-1) {
> -			update_tm(tm, now, tl->length * *num);
> +			uintmax_t length = tl->length, num_t = *num, seconds;
> +
> +			if (unsigned_mult_overflows(length, num_t))
> +				return NULL;
> +			seconds = length * num_t;
> +			if (date_overflows(seconds))
> +				return NULL;
> +			update_tm(tm, now, (time_t)seconds);
>  			*num = 0;
>  			*touched = 1;
>  			return end;

This looks pedanticly paranoid ;-)

Doesn't a similar issue exist, however, immediately after this tl->type
loop, where we handle weekday names?

	for (i = 0; i < 7; i++) {
		int match = match_string(date, weekday_names[i]);
		if (match >= 3) {
			int diff, n = *num -1;
			*num = 0;

			diff = tm->tm_wday - i;
			if (diff <= 0)
				n++;
			diff += 7*n;

			update_tm(tm, now, diff * 24 * 60 * 60);
			*touched = 1;
			return end;
		}
	}

Like "40000 Mondays" gives *num == 40000, diff becomes 280000,
multiplied by 86000 would exceed 24 billion, overflowing 32-bit signed
int.  I guess you can use the same uintmax_t overflow check used in the
previous block?

Thanks.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi Junio,

On Wed, 25 Nov 2026, Junio C Hamano wrote:

> "Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:
> 
> > diff --git a/date.c b/date.c
> > index c50f45d310..3cbfe20b37 100644
> > --- a/date.c
> > +++ b/date.c
> > @@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
> >  	while (tl->type) {
> >  		size_t len = strlen(tl->type);
> >  		if (match_string(date, tl->type) >= len-1) {
> > -			update_tm(tm, now, tl->length * *num);
> > +			uintmax_t length = tl->length, num_t = *num, seconds;
> > +
> > +			if (unsigned_mult_overflows(length, num_t))
> > +				return NULL;
> > +			seconds = length * num_t;
> > +			if (date_overflows(seconds))
> > +				return NULL;
> > +			update_tm(tm, now, (time_t)seconds);
> >  			*num = 0;
> >  			*touched = 1;
> >  			return end;
> 
> This looks pedanticly paranoid ;-)

It does, but rightfully so: That `*num` is user-specified input.

> Doesn't a similar issue exist, however, immediately after this tl->type
> loop, where we handle weekday names?
> 
> 	for (i = 0; i < 7; i++) {
> 		int match = match_string(date, weekday_names[i]);
> 		if (match >= 3) {
> 			int diff, n = *num -1;
> 			*num = 0;
> 
> 			diff = tm->tm_wday - i;
> 			if (diff <= 0)
> 				n++;
> 			diff += 7*n;
> 
> 			update_tm(tm, now, diff * 24 * 60 * 60);
> 			*touched = 1;
> 			return end;
> 		}
> 	}
> 
> Like "40000 Mondays" gives *num == 40000, diff becomes 280000,
> multiplied by 86000 would exceed 24 billion, overflowing 32-bit signed
> int.  I guess you can use the same uintmax_t overflow check used in the
> previous block?

You're absolutely right! And as a consequence, this part is now also
pedantically paranoid.

:-P

Ciao,
Johannes

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aniket Gupta wrote on the Git mailing list (how to reply to this email):

> The product must also fit the native `time_t` range. Report
> arithmetic or conversion failures as parse errors rather than
> saturating the offset.

A result before 1970 is not caught. It wraps around because
update_tm() returns a negative time_t and approxidate_str() casts it to
timestamp_t. An explicit time at the epoch, east of UTC, is enough to
hit it:

    $ TZ=Asia/Kolkata git log --since="1970-01-01 00:00:00"

lists nothing, while UTC lists everything.

This is not caused by this series. Duy sent a patch that dies in this
case in 2011 [1], but it was not picked up. Returning 0 when the result
is negative fixes it for me. Would you like to add this here?

[1] https://lore.kernel.org/git/20111031231320.GA3857@do/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi Aniket,

On Thu, 26 Nov 2026, Aniket Gupta wrote:

> > The product must also fit the native `time_t` range. Report
> > arithmetic or conversion failures as parse errors rather than
> > saturating the offset.
> 
> A result before 1970 is not caught. It wraps around because
> update_tm() returns a negative time_t and approxidate_str() casts it to
> timestamp_t. An explicit time at the epoch, east of UTC, is enough to
> hit it:
> 
>     $ TZ=Asia/Kolkata git log --since="1970-01-01 00:00:00"
> 
> lists nothing, while UTC lists everything.
> 
> This is not caused by this series. Duy sent a patch that dies in this
> case in 2011 [1], but it was not picked up. Returning 0 when the result
> is negative fixes it for me. Would you like to add this here?
> 
> [1] https://lore.kernel.org/git/20111031231320.GA3857@do/

Great catch! But as I only am trying to appease Coverity here, I would
like to leave this out of the series.

Ciao,
Johannes

size_t len = strlen(tl->type);
if (match_string(date, tl->type) >= len-1) {
update_tm(tm, now, tl->length * *num);
uintmax_t length = tl->length, n = *num, seconds;

if (unsigned_mult_overflows(length, n))
return NULL;
seconds = length * n;
if (date_overflows(seconds))
return NULL;
update_tm(tm, now, (time_t)seconds);
*num = 0;
*touched = 1;
return end;
Expand All @@ -1318,15 +1325,27 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm
for (i = 0; i < 7; i++) {
int match = match_string(date, weekday_names[i]);
if (match >= 3) {
int diff, n = *num -1;
int diff;
uintmax_t n = *num -1;
*num = 0;

diff = tm->tm_wday - i;
if (diff <= 0)
n++;
diff += 7*n;

update_tm(tm, now, diff * 24 * 60 * 60);
if (unsigned_mult_overflows(7, n))
return NULL;
n *= 7;

if (n > INT_MAX - diff)
return NULL;
diff += n;

if (diff > INT_MAX / (24 * 60 * 60) ||
diff < INT_MIN / (24 * 60 * 60))
return NULL;

update_tm(tm, now, (time_t)(diff * 24 * 60 * 60));
*touched = 1;
return end;
}
Expand Down Expand Up @@ -1377,8 +1396,11 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
}

/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
if (date[0] != '0' || end - date <= 2)
if (date[0] != '0' || end - date <= 2) {
if (number > INT_MAX)
return NULL;
*num = number;
}
return end;
}

Expand All @@ -1404,14 +1426,18 @@ static timestamp_t approxidate_str(const char *date,
if (!c)
break;
date++;
if (isdigit(c)) {
if (isalpha(c))
date = approxidate_alpha(date-1, &tm, &now,
&number, &touched);
else if (isdigit(c)) {
pending_number(&tm, &number);
date = approxidate_digit(date-1, &tm, &number, time_sec);
touched = 1;
continue;
}
if (isalpha(c))
date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
if (!date) {
*error_ret = 1;
return 0;
}
}
pending_number(&tm, &number);
if (!touched)
Expand Down
2 changes: 1 addition & 1 deletion dir.c
Original file line number Diff line number Diff line change
Expand Up @@ -1190,7 +1190,7 @@ static int add_patterns(const char *fname, const char *base, int baselen,
return 0;
}
buf = xmallocz(size);
if (read_in_full(fd, buf, size) != size) {
if (read_in_full_or_error(fd, buf, size) < 0) {
free(buf);
close(fd);
return -1;
Expand Down
2 changes: 1 addition & 1 deletion entry.c
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ static int write_entry(struct cache_entry *ce, char *path, struct conv_attrs *ca
char *new_blob;
struct strbuf buf = STRBUF_INIT;
size_t size;
ssize_t wrote;
int wrote;
size_t newsize = 0;
struct stat st;
const struct submodule *sub;
Expand Down
2 changes: 1 addition & 1 deletion grep.c
Original file line number Diff line number Diff line change
Expand Up @@ -1964,7 +1964,7 @@ static int grep_source_load_file(struct grep_source *gs)
if (i < 0)
goto err_ret;
data = xmallocz(size);
if (st.st_size != read_in_full(i, data, size)) {
if (read_in_full_or_error(i, data, size) < 0) {
error_errno(_("'%s': short read"), filename);
close(i);
free(data);
Expand Down
2 changes: 1 addition & 1 deletion http.c
Original file line number Diff line number Diff line change
Expand Up @@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Patrick Steinhardt wrote on the Git mailing list (how to reply to this email):

On Wed, Oct 14, 2026 at 06:09:28AM +0000, Johannes Schindelin via GitGitGadget wrote:
> diff --git a/http.c b/http.c
> index 4af3c29c76..809471f436 100644
> --- a/http.c
> +++ b/http.c
> @@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
>  {
>  	unsigned char expn[4096];
>  	size_t size = eltsize * nmemb;
> -	int posn = 0;
> +	size_t posn = 0;
>  	struct http_object_request *freq = data;
>  	struct active_request_slot *slot = freq->slot;

Right. This is how we access the variable:

	do {
		ssize_t retval = xwrite(freq->localfile,
					(char *) ptr + posn, size - posn);
		if (retval < 0)
			return posn / eltsize;
		posn += retval;
	} while (posn < size);

So it's clear that it doesn't have to be signed either, as we only ever
add positive values to it.

Patrick

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

Patrick Steinhardt <ps@pks.im> writes:

> On Wed, Oct 14, 2026 at 06:09:28AM +0000, Johannes Schindelin via GitGitGadget wrote:
>> diff --git a/http.c b/http.c
>> index 4af3c29c76..809471f436 100644
>> --- a/http.c
>> +++ b/http.c
>> @@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
>>  {
>>  	unsigned char expn[4096];
>>  	size_t size = eltsize * nmemb;
>> -	int posn = 0;
>> +	size_t posn = 0;
>>  	struct http_object_request *freq = data;
>>  	struct active_request_slot *slot = freq->slot;
>
> Right. This is how we access the variable:
>
> 	do {
> 		ssize_t retval = xwrite(freq->localfile,
> 					(char *) ptr + posn, size - posn);
> 		if (retval < 0)
> 			return posn / eltsize;
> 		posn += retval;
> 	} while (posn < size);
>
> So it's clear that it doesn't have to be signed either, as we only ever
> add positive values to it.

I agree that changing the type of posn from int to size_t is the
right move.

But I wondered what happens when (size - posn) is larger than half
the range of the ssize_t type early in the loop.  After all, the
proposed commit log message worries about the case where HTTP
response body exceeds 2GB.

Shouldn't the loop clamp the bytecount passed to xwrite() below
whatever would fit in ssize_t when successful?  It may end up making
two calls of xwrite, writing 1.5GB each, to write out 3GB payload,
but that would be better than attempting to write 3GB, succeed, and
be fooled by ssize_t that is narrower by size_t by at least one bit
that we got a negative return from xwrite() and return an error from
here, when in reality we have written them all?

    ... goes and looks ... 

Ah, nevermind.  The big comment in git-compat-util.h before
MAX_IO_SIZE clarifies all of the above.  In short, xwrite() takes
care of clamping, so its callers including this code do not have to
worry about it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simon Richter wrote on the Git mailing list (how to reply to this email):

Hi,

On 10/16/26 23:30, Junio C Hamano wrote:

> I agree that changing the type of posn from int to size_t is the
> right move.

It is a position in a file that is being read as binary data[1], so off_t would be the best choice I think.

That is still signed, but it can't overflow, because opening large files requires O_LARGEFILE, which is available only if large file support is enabled, which conveniently makes sure that off_t is 64 bit.

   Simon

[1] to make a distinction from the use case for fpos_t

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

Simon Richter <Simon.Richter@hogyros.de> writes:

>> I agree that changing the type of posn from int to size_t is the
>> right move.
>
> It is a position in a file that is being read as binary data[1], so 
> off_t would be the best choice I think.

Hmm, interesting.  The function writes out eltsize * nmemb (both are
of type size_t) bytes, so the total could theoretically exceed the
range that fits size_t.

But the thing is that posn is used this way

		ssize_t retval = xwrite(freq->localfile,
					(char *) ptr + posn, size - posn);

to offset into a contiguous in-core region that starts at ptr.  I am
not sure if (ptr + posn) is still valid for posn that is too large
to fit in size_t, though.

To put it differently, we are writing out what is in the contiguous
in-core region and posn runs up to the allocation size of that
region, which should be measured in size_t, no?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

Simon Richter <Simon.Richter@hogyros.de> writes:

>> I agree that changing the type of posn from int to size_t is the
>> right move.
>
> It is a position in a file that is being read as binary data[1], so 
> off_t would be the best choice I think.

Interesting.

The function writes out eltsize * nmemb bytes (both of type
size_t), which means the product could theoretically exceed the
range of size_t.  However, posn is used in xwrite() to offset
into a contiguous in-core buffer starting at ptr:

        ssize_t retval = xwrite(freq->localfile,
                                (char *) ptr + posn,
                                size - posn);

Because we are indexing into an allocated in-core region, any
valid offset must fit within size_t.  If posn were to exceed
the bounds of size_t, the pointer arithmetic ptr + posn would
already be invalid.  As posn only runs up to the allocation
size of the region, it indeed should be measured in size_t, no?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:

> From: Johannes Schindelin <johannes.schindelin@gmx.de>
>
> The `fwrite_sha1_file()` function tracks the number of bytes written via
> an `int` variable, but the total size to write is of type `size_t`. When
> the HTTP response body exceeds INT_MAX (~2GB), this causes an overflow
> and a heap under-read, then writes that data to the local object file.
>
> The hash check afterward would reject the corrupt object (so no bad data
> enters the object store), but the under-read itself could leak adjacent
> heap contents to the temporary file. In practice this is unlikely
> because curl delivers data in small chunks (typically 16KB per callback
> invocation), so in practice, the total size is far below INT_MAX in a
> single call. However, the function interface accepts arbitrary sizes,
> and the accumulation across the loop means that the `int` variable grows
> across calls within a single invocation, not across callbacks.

The second paragraph also repeats "In practice ... so in practice".

I had to read the two paragraphs a few times to convince myself that
they are not delivering contradictory messages.  In fwrite_sha1_file(),
'posn' is a local variable reset to 0 on every invocation, so a
multi-gigabyte HTTP response body delivered in normal chunks will never
overflow 'posn'.  Only a single invocation whose eltsize * nmemb is
larger than INT_MAX would overflow it, as the second paragraph notes.

Perhaps shorten the thing (while removing the repetition) along the
lines of something like...

    The fwrite_sha1_file() function tracks the number of bytes written
    during a single invocation in an int variable ('posn'), even though
    the buffer length size = eltsize * nmemb has type size_t.  If a
    caller or callback ever passed more than INT_MAX bytes in a single
    call, 'posn' could overflow and wrap negative, causing (char *)ptr +
    posn to under-read the buffer.  While curl delivers data in small
    chunks in practice, matching the variable type to 'size' avoids the
    defect.

perhaps?

> diff --git a/http.c b/http.c
> index d79678d01f..2879eb3874 100644
> --- a/http.c
> +++ b/http.c
> @@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
>  {
>  	unsigned char expn[4096];
>  	size_t size = eltsize * nmemb;
> -	int posn = 0;
> +	size_t posn = 0;
>  	struct http_object_request *freq = data;
>  	struct active_request_slot *slot = freq->slot;

And of course, this single line change itself is good.

xwrite() clamps per-call I/O to MAX_IO_SIZE, and posn/eltsize division
avoids signed-to-unsigned promotion on the value this function returns.

Looking good.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Johannes Schindelin wrote on the Git mailing list (how to reply to this email):

Hi Junio,

On Tue, 24 Nov 2026, Junio C Hamano wrote:

> "Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:
> 
> > From: Johannes Schindelin <johannes.schindelin@gmx.de>
> >
> > The `fwrite_sha1_file()` function tracks the number of bytes written via
> > an `int` variable, but the total size to write is of type `size_t`. When
> > the HTTP response body exceeds INT_MAX (~2GB), this causes an overflow
> > and a heap under-read, then writes that data to the local object file.
> >
> > The hash check afterward would reject the corrupt object (so no bad data
> > enters the object store), but the under-read itself could leak adjacent
> > heap contents to the temporary file. In practice this is unlikely
> > because curl delivers data in small chunks (typically 16KB per callback
> > invocation), so in practice, the total size is far below INT_MAX in a
> > single call. However, the function interface accepts arbitrary sizes,
> > and the accumulation across the loop means that the `int` variable grows
> > across calls within a single invocation, not across callbacks.
> 
> The second paragraph also repeats "In practice ... so in practice".
> 
> I had to read the two paragraphs a few times to convince myself that
> they are not delivering contradictory messages.  In fwrite_sha1_file(),
> 'posn' is a local variable reset to 0 on every invocation, so a
> multi-gigabyte HTTP response body delivered in normal chunks will never
> overflow 'posn'.  Only a single invocation whose eltsize * nmemb is
> larger than INT_MAX would overflow it, as the second paragraph notes.
> 
> Perhaps shorten the thing (while removing the repetition) along the
> lines of something like...
> 
>     The fwrite_sha1_file() function tracks the number of bytes written
>     during a single invocation in an int variable ('posn'), even though
>     the buffer length size = eltsize * nmemb has type size_t.  If a
>     caller or callback ever passed more than INT_MAX bytes in a single
>     call, 'posn' could overflow and wrap negative, causing (char *)ptr +
>     posn to under-read the buffer.  While curl delivers data in small
>     chunks in practice, matching the variable type to 'size' avoids the
>     defect.
> 
> perhaps?

I'll use that.

Thanks!
Johannes

> 
> > diff --git a/http.c b/http.c
> > index d79678d01f..2879eb3874 100644
> > --- a/http.c
> > +++ b/http.c
> > @@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
> >  {
> >  	unsigned char expn[4096];
> >  	size_t size = eltsize * nmemb;
> > -	int posn = 0;
> > +	size_t posn = 0;
> >  	struct http_object_request *freq = data;
> >  	struct active_request_slot *slot = freq->slot;
> 
> And of course, this single line change itself is good.
> 
> xwrite() clamps per-call I/O to MAX_IO_SIZE, and posn/eltsize division
> avoids signed-to-unsigned promotion on the value this function returns.
> 
> Looking good.
> 
> 

unsigned char expn[4096];
size_t size = eltsize * nmemb;
int posn = 0;
size_t posn = 0;
struct http_object_request *freq = data;
struct active_request_slot *slot = freq->slot;

Expand Down
2 changes: 1 addition & 1 deletion imap-send.c
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len)
n = SSL_write(sock->ssl, buf, len);
else
#endif
n = write_in_full(sock->fd[1], buf, len);
n = write_in_full(sock->fd[1], buf, len) < 0 ? -1 : len;
if (n != len) {
socket_perror("write", sock, n);
close(sock->fd[0]);
Expand Down
13 changes: 2 additions & 11 deletions notes-merge.c
Original file line number Diff line number Diff line change
Expand Up @@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct object_id *obj,

fd = xopen(path, O_WRONLY | O_EXCL | O_CREAT, 0666);

while (size > 0) {
ssize_t ret = write_in_full(fd, buf, size);
if (ret < 0) {
/* Ignore epipe */
if (errno == EPIPE)
break;
die_errno("notes-merge");
}
size -= ret;
buf += ret;
}
if (write_in_full(fd, buf, size) < 0 && errno != EPIPE)
die_errno("notes-merge");

close(fd);
free(path);
Expand Down
6 changes: 2 additions & 4 deletions odb/streaming.c
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ int odb_stream_blob_to_fd(struct object_database *odb,
goto close_and_exit;
for (;;) {
char buf[1024 * 16];
ssize_t wrote, holeto;
ssize_t holeto;
ssize_t readlen = odb_stream_read(st, buf, sizeof(buf));

if (readlen < 0)
Expand All @@ -268,9 +268,7 @@ int odb_stream_blob_to_fd(struct object_database *odb,
goto close_and_exit;
else
kept = 0;
wrote = write_in_full(fd, buf, readlen);

if (wrote < 0)
if (write_in_full(fd, buf, readlen) < 0)
goto close_and_exit;
}
if (kept && (lseek(fd, kept - 1, SEEK_CUR) == (off_t) -1 ||
Expand Down
2 changes: 1 addition & 1 deletion parallel-checkout.c
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ static int write_pc_item_to_fd(struct parallel_checkout_item *pc_item, int fd,
struct strbuf buf = STRBUF_INIT;
char *blob;
size_t size;
ssize_t wrote;
int wrote;

/* Sanity check */
ASSERT(is_eligible_for_parallel_checkout(pc_item->ce, &pc_item->ca));
Expand Down
4 changes: 1 addition & 3 deletions refs/packed-backend.c
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,6 @@ static int refname_contains_nul(struct strbuf *refname)

static int allocate_snapshot_buffer(struct snapshot *snapshot, int fd, struct stat *st)
{
ssize_t bytes_read;
size_t size;

size = xsize_t(st->st_size);
Expand All @@ -552,8 +551,7 @@ static int allocate_snapshot_buffer(struct snapshot *snapshot, int fd, struct st

if (mmap_strategy == MMAP_NONE || size <= SMALL_FILE_SIZE) {
snapshot->buf = xmalloc(size);
bytes_read = read_in_full(fd, snapshot->buf, size);
if (bytes_read < 0 || bytes_read != size)
if (read_in_full_or_error(fd, snapshot->buf, size) < 0)
die_errno("couldn't read %s", snapshot->refs->path);
snapshot->mmapped = 0;
} else {
Expand Down
10 changes: 7 additions & 3 deletions strbuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,12 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)

strbuf_grow(sb, hint ? hint : 8192);
for (;;) {
ssize_t want = sb->alloc - sb->len - 1;
ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
size_t want = sb->alloc - sb->len - 1;
ssize_t got;

if ((uintmax_t)want > maximum_signed_value_of_type(ssize_t))
want = maximum_signed_value_of_type(ssize_t);
got = read_in_full(fd, sb->buf + sb->len, want);

if (got < 0) {
if (oldalloc == 0)
Expand All @@ -548,7 +552,7 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
return -1;
}
sb->len += got;
if (got < want)
if ((size_t)got < want)
break;
strbuf_grow(sb, 8192);
}
Expand Down
1 change: 1 addition & 0 deletions t/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ clar_test_suites = [
'unit-tests/u-trailer.c',
'unit-tests/u-urlmatch-normalization.c',
'unit-tests/u-utf8-width.c',
'unit-tests/u-wrapper.c',
]

clar_sources = [
Expand Down
13 changes: 13 additions & 0 deletions t/t0006-date.sh
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,19 @@ check_approxidate 3.weeks.ago '2009-08-09 19:20:00'
check_approxidate 3.months.ago '2009-05-30 19:20:00'
check_approxidate 2.years.3.months.ago '2007-05-30 19:20:00'

test_expect_success HAVE_64BIT_TIME 'parse a large number of weeks' '
echo "Jan 1 2099 4000 weeks ago -> 1651778400" >expect &&
test-tool date timestamp "Jan 1 2099 4000 weeks ago" >actual &&
test_cmp expect actual
'

test_expect_success TIME_IS_64BIT 'reject a quantity that does not fit in int' '
git reflog expire --dry-run --all --expire="1 day 1 second ago" &&
test_must_fail git reflog expire --dry-run --all \
--expire="1 day 18446744073709551615 seconds ago" 2>err &&
test_grep "invalid timestamp" err
'

check_approxidate '6am yesterday' '2009-08-29 06:00:00'
check_approxidate '6pm yesterday' '2009-08-29 18:00:00'
check_approxidate '3:00' '2009-08-30 03:00:00'
Expand Down
2 changes: 1 addition & 1 deletion t/unit-tests/u-reftable-stack.c
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)

cl_assert(fd > 0);
n = write_in_full(fd, out, strlen(out));
cl_assert_equal_i(n, strlen(out));
cl_assert_equal_i(n, 0);
err = close(fd);
cl_assert(err >= 0);

Expand Down
Loading
Loading