Subject: Re: [PATCH v4 12/27] object-file: mark cached object buffers as const

From: Junio C Hamano <[email-masked]>
Date: Thu, 06 Jun 2024 09:25:20 -0700

Junio C Hamano <[email-masked]> writes:

> Indeed, that seems to be the case.  With the attached at the tip of
> the branch and rebuilding 'seen' seems to pass these 6130, 7010, 8002
> tests with SANTIZE=leak.
>
> From f307bbf7bd317d90db29bd1589b49e84b9e37e88 Mon Sep 17 00:00:00 2001
> From: Junio C Hamano <[email-masked]>
> Date: Wed, 5 Jun 2024 23:03:34 -0700
> Subject: [PATCH] fixup! object-file: mark cached object buffers as const
>
> ---
>  object-file.c | 4 +++-
>  1 file changed, 3 insertions(+), 1 deletion(-)
>
> diff --git a/object-file.c b/object-file.c
> index b5b5a59dc6..2d5bd3a211 100644
> --- a/object-file.c
> +++ b/object-file.c
> @@ -1785,8 +1785,10 @@ int pretend_object_file(void *buf, unsigned long len, enum object_type type,
>  
>  	hash_object_file(the_hash_algo, buf, len, type, oid);
>  	if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
> -	    find_cached_object(oid))
> +	    find_cached_object(oid)) {
> +		free(co_buf);
>  		return 0;
> +	}
>  	ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
>  	co = &cached_objects[cached_object_nr++];
>  	co->size = len;

Wait.  Why do we need to allocate co_buf that early in the first
place?  IOW, shouldn't the fixup be more like this?

 object-file.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git c/object-file.c w/object-file.c
index b5b5a59dc6..0b58751f94 100644
--- c/object-file.c
+++ w/object-file.c
@@ -1780,9 +1780,6 @@ int pretend_object_file(void *buf, unsigned long len, enum object_type type,
 	struct cached_object *co;
 	char *co_buf;
 
-	co_buf = xmalloc(len);
-	memcpy(co_buf, buf, len);
-
 	hash_object_file(the_hash_algo, buf, len, type, oid);
 	if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
 	    find_cached_object(oid))
@@ -1791,6 +1788,8 @@ int pretend_object_file(void *buf, unsigned long len, enum object_type type,
 	co = &cached_objects[cached_object_nr++];
 	co->size = len;
 	co->type = type;
+	co_buf = xmalloc(len);
+	memcpy(co_buf, buf, len);
 	co->buf = co_buf;
 	oidcpy(&co->oid, oid);
 	return 0;