All of lore.kernel.org
 help / color / mirror / Atom feed
From: "Daniel P. Berrangé" <berrange@redhat.com>
To: Juan Quintela <quintela@redhat.com>
Cc: qemu-devel@nongnu.org
Subject: Re: [PATCH] Change the default for Mixed declarations.
Date: Thu, 23 Mar 2023 19:00:09 +0000	[thread overview]
Message-ID: <ZByhueDO9J9MLuSJ@redhat.com> (raw)
In-Reply-To: <20230214160738.88614-1-quintela@redhat.com>

On Tue, Feb 14, 2023 at 05:07:38PM +0100, Juan Quintela wrote:
> Hi
> 
> I want to enter a discussion about changing the default of the style
> guide.
> 
> There are several reasons for that:
> - they exist since C99 (i.e. all supported compilers support them)
> - they eliminate the posibility of an unitialized variable.

Actually they don't do that reliably. In fact, when combined
with usage of 'goto', they introduce uninitialized variables,
despite the declaration having an initialization present, and
thus actively mislead reviewers into thinking their code is
safe.

Consider this example:

#include <stdlib.h>
#include <stdio.h>

void foo(int something) {
  if (something == 8) {
    goto cleanup;
  }
  
  int nitems = 3;
  int *items = malloc(sizeof(int) *nitems);
       
  printf("Hello world %p\n", items);

 cleanup:
  printf("nitems=%d items=%p\n", nitems, items);
  if (nitems) {
    free(items);
  }
}

int main(int argc, char **argv) {
  foo(atoi(argv[1]));
  return 0;
}

Superficially everything looks awesome right - the variables are
all initialized at time of declaration after all.

$ gcc -Wall -o mixed mixed.c

$ ./mixed 3
Hello world 0x18ef2a0
nitems=3 items=0x18ef2a0

$ ./mixed 8
nitems=32677 items=0x7fa5a9209000
free(): invalid pointer
Aborted (core dumped)


What happens is that when you 'goto $LABEL' across a variable
declaration, the variable is in scope at your target label, but
its declared initializers never get run :-(

Luckily you can protect against that with gcc:

$ gcc -Wjump-misses-init -Wall -o mixed mixed.c
mixed.c: In function ‘foo’:
mixed.c:7:12: warning: jump skips variable initialization [-Wjump-misses-init]
    7 |            goto cleanup;
      |            ^~~~
mixed.c:15:5: note: label ‘cleanup’ defined here
   15 |     cleanup:
      |     ^~~~~~~
mixed.c:11:13: note: ‘items’ declared here
   11 |        int *items = malloc(sizeof(int) *nitems);
      |             ^~~~~
mixed.c:7:12: warning: jump skips variable initialization [-Wjump-misses-init]
    7 |            goto cleanup;
      |            ^~~~
mixed.c:15:5: note: label ‘cleanup’ defined here
   15 |     cleanup:
      |     ^~~~~~~
mixed.c:10:12: note: ‘nitems’ declared here
   10 |        int nitems = 3;
      |            ^~~~~~


however that will warn about *all* cases where we jump over a
declared variable, even if the variable we're jumping over is
not used at the target label location. IOW, it has significant
false positive rates. There are quite a few triggers for this
in the QEMU code already if we turn on this warning.

It also doesn't alter that the code initialization is misleading
to read.

> - (at least for me), declaring the index inside the for make clear
>   that index is not used outside the for.

I'll admit that declaring loop indexes in the for() is a nice
bit, but I'm not a fan in general of mixing the declarations
in the middle of code for projects that use the 'goto cleanup'
pattern.

> - Current documentation already declares that they are allowed in some
>   cases.
> - Lots of places already use them.
> 
> We can change the text to whatever you want, just wondering if it is
> valib to change the standard.
> 
> Doing a trivial grep through my local qemu messages (around 100k) it
> shows that some people are complaining that they are not allowed, and
> other saying that they are used all over the place.

IMHO the status quo is bad because it is actively dangerous when
combined with goto and we aren't using any compiler warnings to
help us.

Either we allow it, but use -Wjump-misses-init to prevent mixing
delayed declarations with gotos, and just avoid this when it triggers
a false positive.

Or we forbid it, rewrite current cases that use it, and then add
-Wdeclaration-after-statement to enforce it.


IMHO if we are concerned about uninitialized variables then I think
a better approach is to add -ftrivial-auto-var-init=zero, which will
make the compiler initialize all variables to 0 if they lack an
explicit initializer. 

> Discuss.
> ---
>  docs/devel/style.rst | 23 ++++++++++++++---------
>  1 file changed, 14 insertions(+), 9 deletions(-)
> 
> diff --git a/docs/devel/style.rst b/docs/devel/style.rst
> index 68aa776930..dc248aa9e4 100644
> --- a/docs/devel/style.rst
> +++ b/docs/devel/style.rst
> @@ -202,15 +202,20 @@ Furthermore, it is the QEMU coding style.
>  Declarations
>  ============
>  
> -Mixed declarations (interleaving statements and declarations within
> -blocks) are generally not allowed; declarations should be at the beginning
> -of blocks.
> -
> -Every now and then, an exception is made for declarations inside a
> -#ifdef or #ifndef block: if the code looks nicer, such declarations can
> -be placed at the top of the block even if there are statements above.
> -On the other hand, however, it's often best to move that #ifdef/#ifndef
> -block to a separate function altogether.
> +Declaring variables at first use has two advantages:
> +- we can see the right type of the variable just to the use
> +- we completely remove the posibility of using a variable that is
> +  unitialized.
> +
> +It is especially the case when we are in a for statement.
> +
> +for (int i = X; i++; ..) {
> +    ...
> +}
> +
> +Makes clear visually that this variable is not useed outside of the for.
> +
> +Mixing declarations an code has been allowed since the C99 standard.
>  
>  Conditional statements
>  ======================
> -- 
> 2.39.1
> 
> 

With regards,
Daniel
-- 
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|



  reply	other threads:[~2023-03-23 19:00 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2023-02-14 16:07 [PATCH] Change the default for Mixed declarations Juan Quintela
2023-03-23 19:00 ` Daniel P. Berrangé [this message]
2023-03-24  8:43   ` Philippe Mathieu-Daudé
2023-03-24 14:04   ` Alex Bennée
2023-03-24 17:39   ` Juan Quintela
2023-03-24 17:56     ` Alex Bennée
2023-03-27  9:12       ` Daniel P. Berrangé
2023-03-27 10:49       ` Markus Armbruster
2023-03-27  9:10     ` Daniel P. Berrangé
2023-03-27 10:45   ` Markus Armbruster

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=ZByhueDO9J9MLuSJ@redhat.com \
    --to=berrange@redhat.com \
    --cc=qemu-devel@nongnu.org \
    --cc=quintela@redhat.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.