Re: [PATCH] tag: avoid NULL pointer arithmetic
- From
SZEDER Gábor <szeder.dev@gmail.com>
- Date
- Oct 3, 2017, 10:22 UTC
- Message-ID
- <20171003102215.9952-1-szeder.dev@gmail.com>
- In-Reply-To
- <99e56671-bdf9-a59f-ae7b-758f1b7a8f14@web.de>
Show 10 quoted lines
> lookup_blob() etc. can return NULL if the referenced object isn't of the > expected type. In theory it's wrong to reference the object member in > that case. In practice it's OK because it's located at offset 0 for all > types, so the pointer arithmetic (NULL + 0) is optimized out by the > compiler. The issue is reported by Clang's AddressSanitizer, though. > > Avoid the ASan error by casting the results of the lookup functions to > struct object pointers. That works fine with NULL pointers as well. We > already rely on the object member being first in all object types in > other places in the code.
This sounds like the main goal of the patch is to avoid an ASan error, but I think it's more important to avoid (and to be more explicit about avoiding) the undefined behavior. I.e. along the lines of s/In theory it's wrong/It's undefined behavior/ and s/ASan error/undefined behavior/
Furthermore, fsck.c:fsck_walk_tree() does the same "immediately reference the object member in lookup_blob()'s and lookup_tree()'s return value" thing. I think those should receive the same treatment as well.
Show 30 quoted lines
> Signed-off-by: Rene Scharfe <l.s.r@web.de>
> ---
> tag.c | 8 ++++----
> 1 file changed, 4 insertions(+), 4 deletions(-)
>
> diff --git a/tag.c b/tag.c
> index 7e10acfb6e..fcbe012f7a 100644
> --- a/tag.c
> +++ b/tag.c
> @@ -142,13 +142,13 @@ int parse_tag_buffer(struct tag *item, const void *data, unsigned long size)
> bufptr = nl + 1;
>
> if (!strcmp(type, blob_type)) {
> - item->tagged = &lookup_blob(&oid)->object;
> + item->tagged = (struct object *)lookup_blob(&oid);
> } else if (!strcmp(type, tree_type)) {
> - item->tagged = &lookup_tree(&oid)->object;
> + item->tagged = (struct object *)lookup_tree(&oid);
> } else if (!strcmp(type, commit_type)) {
> - item->tagged = &lookup_commit(&oid)->object;
> + item->tagged = (struct object *)lookup_commit(&oid);
> } else if (!strcmp(type, tag_type)) {
> - item->tagged = &lookup_tag(&oid)->object;
> + item->tagged = (struct object *)lookup_tag(&oid);
> } else {
> error("Unknown type %s", type);
> item->tagged = NULL;
> --
> 2.14.2
>