diff mbox series

[v9,02/10] scripts: Coccinelle script to use ERRP_AUTO_PROPAGATE()

Message ID 20200312085936.9552-3-vsementsov@virtuozzo.com (mailing list archive)
State New, archived
Headers show
Series error: auto propagated local_err part I | expand

Commit Message

Vladimir Sementsov-Ogievskiy March 12, 2020, 8:59 a.m. UTC
Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
does corresponding changes in code (look for details in
include/qapi/error.h)

Usage example:
spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
 --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
 --max-width 80 FILES...

Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
---

Cc: Eric Blake <eblake@redhat.com>
Cc: Kevin Wolf <kwolf@redhat.com>
Cc: Max Reitz <mreitz@redhat.com>
Cc: Greg Kurz <groug@kaod.org>
Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
Cc: Stefano Stabellini <sstabellini@kernel.org>
Cc: Anthony Perard <anthony.perard@citrix.com>
Cc: Paul Durrant <paul@xen.org>
Cc: Stefan Hajnoczi <stefanha@redhat.com>
Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Stefan Berger <stefanb@linux.ibm.com>
Cc: Markus Armbruster <armbru@redhat.com>
Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
Cc: qemu-devel@nongnu.org
Cc: qemu-block@nongnu.org
Cc: xen-devel@lists.xenproject.org

 scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
 include/qapi/error.h                          |   3 +
 MAINTAINERS                                   |   1 +
 3 files changed, 331 insertions(+)
 create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci

Comments

Markus Armbruster March 12, 2020, 4:36 p.m. UTC | #1
I may have a second look tomorrow with fresher eyes, but let's get this
out now as is.

Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
> does corresponding changes in code (look for details in
> include/qapi/error.h)
>
> Usage example:
> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>  --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>  --max-width 80 FILES...
>
> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
> ---
>
> Cc: Eric Blake <eblake@redhat.com>
> Cc: Kevin Wolf <kwolf@redhat.com>
> Cc: Max Reitz <mreitz@redhat.com>
> Cc: Greg Kurz <groug@kaod.org>
> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
> Cc: Stefano Stabellini <sstabellini@kernel.org>
> Cc: Anthony Perard <anthony.perard@citrix.com>
> Cc: Paul Durrant <paul@xen.org>
> Cc: Stefan Hajnoczi <stefanha@redhat.com>
> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Cc: Gerd Hoffmann <kraxel@redhat.com>
> Cc: Stefan Berger <stefanb@linux.ibm.com>
> Cc: Markus Armbruster <armbru@redhat.com>
> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
> Cc: qemu-devel@nongnu.org
> Cc: qemu-block@nongnu.org
> Cc: xen-devel@lists.xenproject.org
>
>  scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>  include/qapi/error.h                          |   3 +
>  MAINTAINERS                                   |   1 +
>  3 files changed, 331 insertions(+)
>  create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>
> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
> new file mode 100644
> index 0000000000..7dac2dcfa4
> --- /dev/null
> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
> @@ -0,0 +1,327 @@
> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
> +//
> +// Copyright (c) 2020 Virtuozzo International GmbH.
> +//
> +// This program is free software; you can redistribute it and/or
> +// modify it under the terms of the GNU General Public License as
> +// published by the Free Software Foundation; either version 2 of the
> +// License, or (at your option) any later version.
> +//
> +// This program is distributed in the hope that it will be useful,
> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +// GNU General Public License for more details.
> +//
> +// You should have received a copy of the GNU General Public License
> +// along with this program.  If not, see
> +// <http://www.gnu.org/licenses/>.
> +//
> +// Usage example:
> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
> +//  --macro-file scripts/cocci-macro-file.h --in-place \
> +//  --no-show-diff --max-width 80 FILES...
> +//
> +// Note: --max-width 80 is needed because coccinelle default is less
> +// than 80, and without this parameter coccinelle may reindent some
> +// lines which fit into 80 characters but not to coccinelle default,
> +// which in turn produces extra patch hunks for no reason.

This is about unwanted reformatting of parameter lists due to the ___
chaining hack.  --max-width 80 makes that less likely, but not
impossible.

We can search for unwanted reformatting of parameter lists.  I think
grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
tree, I get one false positive (not a parameter list), and one hit:

    @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
         }
     }

    -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
    +void object_apply_global_props(Object *obj, const GPtrArray *props,
    +                               Error **errp)
     {
    +    ERRP_AUTO_PROPAGATE();
         int i;

         if (!props) {

Reformatting, but not unwanted.

The --max-width 80 hack is good enough for me.

It does result in slightly long transformed lines, e.g. this one in
replication.c:

    @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
             s->mode = REPLICATION_MODE_PRIMARY;
             top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
             if (top_id) {
    -            error_setg(&local_err, "The primary side does not support option top-id");
    +            error_setg(errp, "The primary side does not support option top-id");
                 goto fail;
             }
         } else if (!strcmp(mode, "secondary")) {

v8 did break this line (that's how I found it).  However, v9 still
shortens the line, just not below the target.  All your + lines look
quite unlikely to lengthen lines.  Let's not worry about this.

> +// Switch unusual Error ** parameter names to errp
> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
> +//
> +// Disable optional_qualifier to skip functions with
> +// "Error *const *errp" parameter.
> +//
> +// Skip functions with "assert(_errp && *_errp)" statement, because
> +// that signals unusual semantics, and the parameter name may well
> +// serve a purpose. (like nbd_iter_channel_error()).
> +//
> +// Skip util/error.c to not touch, for example, error_propagate() and
> +// error_propagate_prepend().
> +@ depends on !(file in "util/error.c") disable optional_qualifier@
> +identifier fn;
> +identifier _errp != errp;
> +@@
> +
> + fn(...,
> +-   Error **_errp
> ++   Error **errp
> +    ,...)
> + {
> +(
> +     ... when != assert(_errp && *_errp)
> +&
> +     <...
> +-    _errp
> ++    errp
> +     ...>
> +)
> + }
> +
> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
> +// necessary
> +//
> +// Note, that without "when any" the final "..." does not mach
> +// something matched by previous pattern, i.e. the rule will not match
> +// double error_prepend in control flow like in
> +// vfio_set_irq_signaling().
> +//
> +// Note, "exists" says that we want apply rule even if it matches not
> +// on all possible control flows (otherwise, it will not match
> +// standard pattern when error_propagate() call is in if branch).
> +@ disable optional_qualifier exists@
> +identifier fn, local_err;
> +symbol errp;
> +@@
> +
> + fn(..., Error **errp, ...)
> + {
> ++   ERRP_AUTO_PROPAGATE();
> +    ...  when != ERRP_AUTO_PROPAGATE();
> +(
> +(
> +    error_append_hint(errp, ...);
> +|
> +    error_prepend(errp, ...);
> +|
> +    error_vprepend(errp, ...);
> +)
> +    ... when any
> +|
> +    Error *local_err = NULL;
> +    ...
> +(
> +    error_propagate_prepend(errp, local_err, ...);
> +|
> +    error_propagate(errp, local_err);
> +)
> +    ...
> +)
> + }
> +
> +
> +// Match functions with propagation of local error to errp.
> +// We want to refer these functions in several following rules, but I
> +// don't know a proper way to inherit a function, not just its name
> +// (to not match another functions with same name in following rules).
> +// Not-proper way is as follows: rename errp parameter in functions
> +// header and match it in following rules. Rename it back after all
> +// transformations.
> +//
> +// The simplest case of propagation scheme is single definition of
> +// local_err with at most one error_propagate_prepend or
> +// error_propagate on each control-flow. Still, we want to match more
> +// complex schemes too. We'll warn them with help of further rules.

I think what we actually want is to examine instances of this pattern to
figure out whether and how we want to transform them.  Perhaps:

    // The common case is a single definition of local_err with at most one
    // error_propagate_prepend() or error_propagate() on each control-flow
    // path. Instances of this case we convert with this script. Functions
    // with multiple definitions or propagates we want to examine
    // manually. Later rules emit warnings to guide us to them.

> +@rule1 disable optional_qualifier exists@
> +identifier fn, local_err;
> +symbol errp;
> +@@
> +
> + fn(..., Error **
> +-    errp
> ++    ____
> +    , ...)
> + {
> +     ...
> +     Error *local_err = NULL;
> +     ...
> +(
> +     error_propagate_prepend(errp, local_err, ...);
> +|
> +     error_propagate(errp, local_err);
> +)
> +     ...
> + }
> +
> +
> +// Warn several Error * definitions.
> +@check1 disable optional_qualifier exists@
> +identifier fn = rule1.fn, local_err, local_err2;

Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
particular reason for the difference?

With the ___ chaining hack, I doubt we still need "= rule1.fn" or
"rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
everywhere, then apply the script to the complete tree, I get the same
result.

> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     ...
> +     Error *local_err = NULL;
> +     ... when any
> +     Error *local_err2 = NULL;
> +     ... when any
> + }
> +
> +@ script:python @
> +fn << check1.fn;
> +@@
> +
> +print('Warning: function {} has several definitions of '
> +      'Error * local variable'.format(fn))
> +
> +// Warn several propagations in control flow.
> +@check2 disable optional_qualifier exists@
> +identifier fn = rule1.fn;
> +symbol errp;
> +position p1, p2;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     ...
> +(
> +     error_propagate_prepend(errp, ...);@p1
> +|
> +     error_propagate(errp, ...);@p1
> +)
> +     ...
> +(
> +     error_propagate_prepend(errp, ...);@p2
> +|
> +     error_propagate(errp, ...);@p2
> +)
> +     ... when any
> + }
> +

Hmm, we don't catch the example I used in review of v8:

    extern foo(int, Error **);
    extern bar(int, Error **);

    void frob(Error **errp)
    {
        Error *local_err = NULL;
        int arg;

        foo(arg, errp);
        bar(arg, &local_err);
        error_propagate(errp, local_err);
        bar(arg + 1, &local_err);
        error_propagate(errp, local_err);
    }

I believe this is because rule1 does not match here.

If I change the rule as follows, it catches the example:

    @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '

     // Warn several propagations in control flow.
     @check2 disable optional_qualifier exists@
    -identifier fn = rule1.fn;
    -symbol errp;
    +identifier fn, _errp;
     position p1, p2;
     @@

    - fn(..., Error ** ____, ...)
    + fn(..., Error **_errp, ...)
      {
          ...
     (
    -     error_propagate_prepend(errp, ...);@p1
    +     error_propagate_prepend(_errp, ...);@p1
     |
    -     error_propagate(errp, ...);@p1
    +     error_propagate(_errp, ...);@p1
     )
          ...
     (
    -     error_propagate_prepend(errp, ...);@p2
    +     error_propagate_prepend(_errp, ...);@p2
     |
    -     error_propagate(errp, ...);@p2
    +     error_propagate(_errp, ...);@p2
     )
          ... when any
      }

To my mild surprise, it still doesn't find anything in our tree.

Should we decouple the previous rule from rule1, too?  I tested the
following on the whole tree:

    @@ -136,10 +136,10 @@ symbol errp;

     // Warn several Error * definitions.
     @check1 disable optional_qualifier exists@
    -identifier fn = rule1.fn, local_err, local_err2;
    +identifier fn, _errp, local_err, local_err2;
     @@

    - fn(..., Error ** ____, ...)
    + fn(..., Error **_errp, ...)
      {
          ...
          Error *local_err = NULL;

Warnings remain unchanged.

> +@ script:python @
> +fn << check2.fn;
> +p1 << check2.p1;
> +p2 << check2.p2;
> +@@
> +
> +print('Warning: function {} propagates to errp several times in '
> +      'one control flow: at {}:{} and then at {}:{}'.format(
> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> +
> +// Convert special case with goto separately.
> +// I tried merging this into the following rule the obvious way, but
> +// it made Coccinelle hang on block.c
> +//
> +// Note interesting thing: if we don't do it here, and try to fixup
> +// "out: }" things later after all transformations (the rule will be
> +// the same, just without error_propagate() call), coccinelle fails to
> +// match this "out: }".
> +@ disable optional_qualifier@
> +identifier rule1.fn, rule1.local_err, out;

As explained above, I doubt the need for rule1.fn.  We do need
rule1.local_err to avoid unwanted transformations.  More of the same
below.

> +symbol errp;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     <...
> +-    goto out;
> ++    return;
> +     ...>
> +- out:
> +-    error_propagate(errp, local_err);
> + }
> +
> +// Convert most of local_err related stuff.
> +//
> +// Note, that we update everything related to matched by rule1
> +// function name and local_err name. We may match something not
> +// related to the pattern matched by rule1. For example, local_err may
> +// be defined with the same name in different blocks inside one
> +// function, and in one block follow the propagation pattern and in
> +// other block doesn't. Or we may have several functions with the same
> +// name (for different configurations).
> +//
> +// Note also that errp-cleaning functions
> +//   error_free_errp
> +//   error_report_errp
> +//   error_reportf_errp
> +//   warn_report_errp
> +//   warn_reportf_errp
> +// are not yet implemented. They must call corresponding Error* -
> +// freeing function and then set *errp to NULL, to avoid further
> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
> +// For example, error_free_errp may look like this:
> +//
> +//    void error_free_errp(Error **errp)
> +//    {
> +//        error_free(*errp);
> +//        *errp = NULL;
> +//    }
> +@ disable optional_qualifier exists@
> +identifier rule1.fn, rule1.local_err;
> +expression list args;
> +symbol errp;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     <...
> +(
> +-    Error *local_err = NULL;
> +|
> +
> +// Convert error clearing functions
> +(
> +-    error_free(local_err);
> ++    error_free_errp(errp);
> +|
> +-    error_report_err(local_err);
> ++    error_report_errp(errp);
> +|
> +-    error_reportf_err(local_err, args);
> ++    error_reportf_errp(errp, args);
> +|
> +-    warn_report_err(local_err);
> ++    warn_report_errp(errp);
> +|
> +-    warn_reportf_err(local_err, args);
> ++    warn_reportf_errp(errp, args);
> +)
> +?-    local_err = NULL;
> +
> +|
> +-    error_propagate_prepend(errp, local_err, args);
> ++    error_prepend(errp, args);
> +|
> +-    error_propagate(errp, local_err);
> +|
> +-    &local_err
> ++    errp
> +)
> +     ...>
> + }
> +
> +// Convert remaining local_err usage. For example, different kinds of
> +// error checking in if conditionals. We can't merge this into
> +// previous hunk, as this conflicts with other substitutions in it (at
> +// least with "- local_err = NULL").
> +@ disable optional_qualifier@
> +identifier rule1.fn, rule1.local_err;
> +symbol errp;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     <...
> +-    local_err
> ++    *errp
> +     ...>
> + }
> +
> +// Always use the same pattern for checking error
> +@ disable optional_qualifier@
> +identifier rule1.fn;
> +symbol errp;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     <...
> +-    *errp != NULL
> ++    *errp
> +     ...>
> + }
> +
> +// Revert temporary ___ identifier.
> +@ disable optional_qualifier@
> +identifier rule1.fn;
> +@@
> +
> + fn(..., Error **
> +-   ____
> ++   errp
> +    , ...)
> + {
> +     ...
> + }
> diff --git a/include/qapi/error.h b/include/qapi/error.h
> index 30140d9bfe..56c133520d 100644
> --- a/include/qapi/error.h
> +++ b/include/qapi/error.h
> @@ -214,6 +214,9 @@
>   *         }
>   *         ...
>   *     }
> + *
> + * For mass-conversion use script
> + *   scripts/coccinelle/auto-propagated-errp.cocci
>   */
>  
>  #ifndef ERROR_H
> diff --git a/MAINTAINERS b/MAINTAINERS
> index 857f969aa1..047f1b9714 100644
> --- a/MAINTAINERS
> +++ b/MAINTAINERS
> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>  F: qapi/error.json
>  F: util/error.c
>  F: util/qemu-error.c
> +F: scripts/coccinelle/*err*.cocci
>  
>  GDB stub
>  M: Alex Bennée <alex.bennee@linaro.org>
Vladimir Sementsov-Ogievskiy March 13, 2020, 6:38 a.m. UTC | #2
12.03.2020 19:36, Markus Armbruster wrote:
> I may have a second look tomorrow with fresher eyes, but let's get this
> out now as is.
> 
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>> does corresponding changes in code (look for details in
>> include/qapi/error.h)
>>
>> Usage example:
>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>   --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>   --max-width 80 FILES...
>>
>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>> ---
>>
>> Cc: Eric Blake <eblake@redhat.com>
>> Cc: Kevin Wolf <kwolf@redhat.com>
>> Cc: Max Reitz <mreitz@redhat.com>
>> Cc: Greg Kurz <groug@kaod.org>
>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>> Cc: Anthony Perard <anthony.perard@citrix.com>
>> Cc: Paul Durrant <paul@xen.org>
>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>> Cc: Laszlo Ersek <lersek@redhat.com>
>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>> Cc: Markus Armbruster <armbru@redhat.com>
>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>> Cc: qemu-devel@nongnu.org
>> Cc: qemu-block@nongnu.org
>> Cc: xen-devel@lists.xenproject.org
>>
>>   scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>   include/qapi/error.h                          |   3 +
>>   MAINTAINERS                                   |   1 +
>>   3 files changed, 331 insertions(+)
>>   create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>
>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>> new file mode 100644
>> index 0000000000..7dac2dcfa4
>> --- /dev/null
>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>> @@ -0,0 +1,327 @@
>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>> +//
>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>> +//
>> +// This program is free software; you can redistribute it and/or
>> +// modify it under the terms of the GNU General Public License as
>> +// published by the Free Software Foundation; either version 2 of the
>> +// License, or (at your option) any later version.
>> +//
>> +// This program is distributed in the hope that it will be useful,
>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +// GNU General Public License for more details.
>> +//
>> +// You should have received a copy of the GNU General Public License
>> +// along with this program.  If not, see
>> +// <http://www.gnu.org/licenses/>.
>> +//
>> +// Usage example:
>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>> +//  --no-show-diff --max-width 80 FILES...
>> +//
>> +// Note: --max-width 80 is needed because coccinelle default is less
>> +// than 80, and without this parameter coccinelle may reindent some
>> +// lines which fit into 80 characters but not to coccinelle default,
>> +// which in turn produces extra patch hunks for no reason.
> 
> This is about unwanted reformatting of parameter lists due to the ___
> chaining hack.  --max-width 80 makes that less likely, but not
> impossible.
> 
> We can search for unwanted reformatting of parameter lists.  I think
> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
> tree, I get one false positive (not a parameter list), and one hit:
> 
>      @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>           }
>       }
> 
>      -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>      +void object_apply_global_props(Object *obj, const GPtrArray *props,
>      +                               Error **errp)
>       {
>      +    ERRP_AUTO_PROPAGATE();
>           int i;
> 
>           if (!props) {
> 
> Reformatting, but not unwanted.

Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
ERRP_AUTO_PROPAGATE addition even for non-automatic patch.

> 
> The --max-width 80 hack is good enough for me.
> 
> It does result in slightly long transformed lines, e.g. this one in
> replication.c:
> 
>      @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>               s->mode = REPLICATION_MODE_PRIMARY;
>               top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>               if (top_id) {
>      -            error_setg(&local_err, "The primary side does not support option top-id");
>      +            error_setg(errp, "The primary side does not support option top-id");
>                   goto fail;
>               }
>           } else if (!strcmp(mode, "secondary")) {
> 
> v8 did break this line (that's how I found it).  However, v9 still
> shortens the line, just not below the target.  All your + lines look
> quite unlikely to lengthen lines.  Let's not worry about this.
> 
>> +// Switch unusual Error ** parameter names to errp
>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>> +//
>> +// Disable optional_qualifier to skip functions with
>> +// "Error *const *errp" parameter.
>> +//
>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>> +// that signals unusual semantics, and the parameter name may well
>> +// serve a purpose. (like nbd_iter_channel_error()).
>> +//
>> +// Skip util/error.c to not touch, for example, error_propagate() and
>> +// error_propagate_prepend().
>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>> +identifier fn;
>> +identifier _errp != errp;
>> +@@
>> +
>> + fn(...,
>> +-   Error **_errp
>> ++   Error **errp
>> +    ,...)
>> + {
>> +(
>> +     ... when != assert(_errp && *_errp)
>> +&
>> +     <...
>> +-    _errp
>> ++    errp
>> +     ...>
>> +)
>> + }
>> +
>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>> +// necessary
>> +//
>> +// Note, that without "when any" the final "..." does not mach
>> +// something matched by previous pattern, i.e. the rule will not match
>> +// double error_prepend in control flow like in
>> +// vfio_set_irq_signaling().
>> +//
>> +// Note, "exists" says that we want apply rule even if it matches not
>> +// on all possible control flows (otherwise, it will not match
>> +// standard pattern when error_propagate() call is in if branch).
>> +@ disable optional_qualifier exists@
>> +identifier fn, local_err;
>> +symbol errp;
>> +@@
>> +
>> + fn(..., Error **errp, ...)
>> + {
>> ++   ERRP_AUTO_PROPAGATE();
>> +    ...  when != ERRP_AUTO_PROPAGATE();
>> +(
>> +(
>> +    error_append_hint(errp, ...);
>> +|
>> +    error_prepend(errp, ...);
>> +|
>> +    error_vprepend(errp, ...);
>> +)
>> +    ... when any
>> +|
>> +    Error *local_err = NULL;
>> +    ...
>> +(
>> +    error_propagate_prepend(errp, local_err, ...);
>> +|
>> +    error_propagate(errp, local_err);
>> +)
>> +    ...
>> +)
>> + }
>> +
>> +
>> +// Match functions with propagation of local error to errp.
>> +// We want to refer these functions in several following rules, but I
>> +// don't know a proper way to inherit a function, not just its name
>> +// (to not match another functions with same name in following rules).
>> +// Not-proper way is as follows: rename errp parameter in functions
>> +// header and match it in following rules. Rename it back after all
>> +// transformations.
>> +//
>> +// The simplest case of propagation scheme is single definition of
>> +// local_err with at most one error_propagate_prepend or
>> +// error_propagate on each control-flow. Still, we want to match more
>> +// complex schemes too. We'll warn them with help of further rules.
> 
> I think what we actually want is to examine instances of this pattern to
> figure out whether and how we want to transform them.  Perhaps:
> 
>      // The common case is a single definition of local_err with at most one
>      // error_propagate_prepend() or error_propagate() on each control-flow
>      // path. Instances of this case we convert with this script. Functions

For me, sounds a bit like "other things we don't convert".
Actually we convert other things too.

>      // with multiple definitions or propagates we want to examine
>      // manually. Later rules emit warnings to guide us to them.
> 
>> +@rule1 disable optional_qualifier exists@
>> +identifier fn, local_err;
>> +symbol errp;
>> +@@
>> +
>> + fn(..., Error **
>> +-    errp
>> ++    ____
>> +    , ...)
>> + {
>> +     ...
>> +     Error *local_err = NULL;
>> +     ...
>> +(
>> +     error_propagate_prepend(errp, local_err, ...);
>> +|
>> +     error_propagate(errp, local_err);
>> +)
>> +     ...
>> + }
>> +
>> +
>> +// Warn several Error * definitions.
>> +@check1 disable optional_qualifier exists@
>> +identifier fn = rule1.fn, local_err, local_err2;
> 
> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
> particular reason for the difference?

I didn't find other way to ref check1.fn in next python rule. It just don't
work if I write here just rule1.fn.

> 
> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
> everywhere, then apply the script to the complete tree, I get the same
> result.

I think, it's more efficient to reuse names from previous rules. I think it should
work faster (more information, less extra matching).

> 
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     ...
>> +     Error *local_err = NULL;
>> +     ... when any
>> +     Error *local_err2 = NULL;
>> +     ... when any
>> + }
>> +
>> +@ script:python @
>> +fn << check1.fn;
>> +@@
>> +
>> +print('Warning: function {} has several definitions of '
>> +      'Error * local variable'.format(fn))
>> +
>> +// Warn several propagations in control flow.
>> +@check2 disable optional_qualifier exists@
>> +identifier fn = rule1.fn;
>> +symbol errp;
>> +position p1, p2;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     ...
>> +(
>> +     error_propagate_prepend(errp, ...);@p1
>> +|
>> +     error_propagate(errp, ...);@p1
>> +)
>> +     ...
>> +(
>> +     error_propagate_prepend(errp, ...);@p2
>> +|
>> +     error_propagate(errp, ...);@p2
>> +)
>> +     ... when any
>> + }
>> +
> 
> Hmm, we don't catch the example I used in review of v8:
> 
>      extern foo(int, Error **);
>      extern bar(int, Error **);
> 
>      void frob(Error **errp)
>      {
>          Error *local_err = NULL;
>          int arg;
> 
>          foo(arg, errp);
>          bar(arg, &local_err);
>          error_propagate(errp, local_err);
>          bar(arg + 1, &local_err);
>          error_propagate(errp, local_err);
>      }
> 
> I believe this is because rule1 does not match here.

Yes, rule1 wants at least one code flow with non-doubled propagation.

> 
> If I change the rule as follows, it catches the example:
> 
>      @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
> 
>       // Warn several propagations in control flow.
>       @check2 disable optional_qualifier exists@
>      -identifier fn = rule1.fn;
>      -symbol errp;
>      +identifier fn, _errp;
>       position p1, p2;
>       @@
> 
>      - fn(..., Error ** ____, ...)
>      + fn(..., Error **_errp, ...)
>        {
>            ...
>       (
>      -     error_propagate_prepend(errp, ...);@p1
>      +     error_propagate_prepend(_errp, ...);@p1
>       |
>      -     error_propagate(errp, ...);@p1
>      +     error_propagate(_errp, ...);@p1
>       )
>            ...
>       (
>      -     error_propagate_prepend(errp, ...);@p2
>      +     error_propagate_prepend(_errp, ...);@p2
>       |
>      -     error_propagate(errp, ...);@p2
>      +     error_propagate(_errp, ...);@p2
>       )
>            ... when any
>        }
> 
> To my mild surprise, it still doesn't find anything in our tree.
> 
> Should we decouple the previous rule from rule1, too?  I tested the
> following on the whole tree:

I don't think so. Why to check what we are not going to convert? If we want
to check side things, it's better to do it in other coccinelle script..

> 
>      @@ -136,10 +136,10 @@ symbol errp;
> 
>       // Warn several Error * definitions.
>       @check1 disable optional_qualifier exists@
>      -identifier fn = rule1.fn, local_err, local_err2;
>      +identifier fn, _errp, local_err, local_err2;
>       @@
> 
>      - fn(..., Error ** ____, ...)
>      + fn(..., Error **_errp, ...)
>        {
>            ...
>            Error *local_err = NULL;
> 
> Warnings remain unchanged.
> 
>> +@ script:python @
>> +fn << check2.fn;
>> +p1 << check2.p1;
>> +p2 << check2.p2;
>> +@@
>> +
>> +print('Warning: function {} propagates to errp several times in '
>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>> +
>> +// Convert special case with goto separately.
>> +// I tried merging this into the following rule the obvious way, but
>> +// it made Coccinelle hang on block.c
>> +//
>> +// Note interesting thing: if we don't do it here, and try to fixup
>> +// "out: }" things later after all transformations (the rule will be
>> +// the same, just without error_propagate() call), coccinelle fails to
>> +// match this "out: }".
>> +@ disable optional_qualifier@
>> +identifier rule1.fn, rule1.local_err, out;
> 
> As explained above, I doubt the need for rule1.fn.  We do need
> rule1.local_err to avoid unwanted transformations.  More of the same
> below.

Logically, I want to inherit from rule1. So why not to stress it by inheriting
fn variable? It's just a correct thing to do.
And I hope it helps coccinelle to work more efficiently.

> 
>> +symbol errp;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     <...
>> +-    goto out;
>> ++    return;
>> +     ...>
>> +- out:
>> +-    error_propagate(errp, local_err);
>> + }
>> +
>> +// Convert most of local_err related stuff.
>> +//
>> +// Note, that we update everything related to matched by rule1
>> +// function name and local_err name. We may match something not
>> +// related to the pattern matched by rule1. For example, local_err may
>> +// be defined with the same name in different blocks inside one
>> +// function, and in one block follow the propagation pattern and in
>> +// other block doesn't. Or we may have several functions with the same
>> +// name (for different configurations).
>> +//
>> +// Note also that errp-cleaning functions
>> +//   error_free_errp
>> +//   error_report_errp
>> +//   error_reportf_errp
>> +//   warn_report_errp
>> +//   warn_reportf_errp
>> +// are not yet implemented. They must call corresponding Error* -
>> +// freeing function and then set *errp to NULL, to avoid further
>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>> +// For example, error_free_errp may look like this:
>> +//
>> +//    void error_free_errp(Error **errp)
>> +//    {
>> +//        error_free(*errp);
>> +//        *errp = NULL;
>> +//    }
>> +@ disable optional_qualifier exists@
>> +identifier rule1.fn, rule1.local_err;
>> +expression list args;
>> +symbol errp;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     <...
>> +(
>> +-    Error *local_err = NULL;
>> +|
>> +
>> +// Convert error clearing functions
>> +(
>> +-    error_free(local_err);
>> ++    error_free_errp(errp);
>> +|
>> +-    error_report_err(local_err);
>> ++    error_report_errp(errp);
>> +|
>> +-    error_reportf_err(local_err, args);
>> ++    error_reportf_errp(errp, args);
>> +|
>> +-    warn_report_err(local_err);
>> ++    warn_report_errp(errp);
>> +|
>> +-    warn_reportf_err(local_err, args);
>> ++    warn_reportf_errp(errp, args);
>> +)
>> +?-    local_err = NULL;
>> +
>> +|
>> +-    error_propagate_prepend(errp, local_err, args);
>> ++    error_prepend(errp, args);
>> +|
>> +-    error_propagate(errp, local_err);
>> +|
>> +-    &local_err
>> ++    errp
>> +)
>> +     ...>
>> + }
>> +
>> +// Convert remaining local_err usage. For example, different kinds of
>> +// error checking in if conditionals. We can't merge this into
>> +// previous hunk, as this conflicts with other substitutions in it (at
>> +// least with "- local_err = NULL").
>> +@ disable optional_qualifier@
>> +identifier rule1.fn, rule1.local_err;
>> +symbol errp;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     <...
>> +-    local_err
>> ++    *errp
>> +     ...>
>> + }
>> +
>> +// Always use the same pattern for checking error
>> +@ disable optional_qualifier@
>> +identifier rule1.fn;
>> +symbol errp;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     <...
>> +-    *errp != NULL
>> ++    *errp
>> +     ...>
>> + }
>> +
>> +// Revert temporary ___ identifier.
>> +@ disable optional_qualifier@
>> +identifier rule1.fn;
>> +@@
>> +
>> + fn(..., Error **
>> +-   ____
>> ++   errp
>> +    , ...)
>> + {
>> +     ...
>> + }
>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>> index 30140d9bfe..56c133520d 100644
>> --- a/include/qapi/error.h
>> +++ b/include/qapi/error.h
>> @@ -214,6 +214,9 @@
>>    *         }
>>    *         ...
>>    *     }
>> + *
>> + * For mass-conversion use script
>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>    */
>>   
>>   #ifndef ERROR_H
>> diff --git a/MAINTAINERS b/MAINTAINERS
>> index 857f969aa1..047f1b9714 100644
>> --- a/MAINTAINERS
>> +++ b/MAINTAINERS
>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>   F: qapi/error.json
>>   F: util/error.c
>>   F: util/qemu-error.c
>> +F: scripts/coccinelle/*err*.cocci
>>   
>>   GDB stub
>>   M: Alex Bennée <alex.bennee@linaro.org>
>
Markus Armbruster March 13, 2020, 7:50 a.m. UTC | #3
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

[...]
> +// Warn several Error * definitions.
> +@check1 disable optional_qualifier exists@
> +identifier fn = rule1.fn, local_err, local_err2;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     ...
> +     Error *local_err = NULL;
> +     ... when any
> +     Error *local_err2 = NULL;
> +     ... when any
> + }
> +
> +@ script:python @
> +fn << check1.fn;
> +@@
> +
> +print('Warning: function {} has several definitions of '
> +      'Error * local variable'.format(fn))

Printing the positions like you do in the next rule is useful when
examining these warnings.

> +
> +// Warn several propagations in control flow.
> +@check2 disable optional_qualifier exists@
> +identifier fn = rule1.fn;
> +symbol errp;
> +position p1, p2;
> +@@
> +
> + fn(..., Error ** ____, ...)
> + {
> +     ...
> +(
> +     error_propagate_prepend(errp, ...);@p1
> +|
> +     error_propagate(errp, ...);@p1
> +)
> +     ...
> +(
> +     error_propagate_prepend(errp, ...);@p2
> +|
> +     error_propagate(errp, ...);@p2
> +)
> +     ... when any
> + }
> +
> +@ script:python @
> +fn << check2.fn;
> +p1 << check2.p1;
> +p2 << check2.p2;
> +@@
> +
> +print('Warning: function {} propagates to errp several times in '
> +      'one control flow: at {}:{} and then at {}:{}'.format(
> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
[...]
Vladimir Sementsov-Ogievskiy March 13, 2020, 8:06 a.m. UTC | #4
13.03.2020 10:50, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
> [...]
>> +// Warn several Error * definitions.
>> +@check1 disable optional_qualifier exists@
>> +identifier fn = rule1.fn, local_err, local_err2;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     ...
>> +     Error *local_err = NULL;
>> +     ... when any
>> +     Error *local_err2 = NULL;
>> +     ... when any
>> + }
>> +
>> +@ script:python @
>> +fn << check1.fn;
>> +@@
>> +
>> +print('Warning: function {} has several definitions of '
>> +      'Error * local variable'.format(fn))
> 
> Printing the positions like you do in the next rule is useful when
> examining these warnings.

I decided that searching for Error * definition is simple, and better for
user to search all definitions by hand (may be more than too).

But understanding control flows is more complex thing and better to help
user with line positions.

But if you want, we can add them of course. Note, that for some reasons some
times coccinelle instead of original filename prints something like /tmp/...original-name...
so it don't look nice and may be a bit misleading.

> 
>> +
>> +// Warn several propagations in control flow.
>> +@check2 disable optional_qualifier exists@
>> +identifier fn = rule1.fn;
>> +symbol errp;
>> +position p1, p2;
>> +@@
>> +
>> + fn(..., Error ** ____, ...)
>> + {
>> +     ...
>> +(
>> +     error_propagate_prepend(errp, ...);@p1
>> +|
>> +     error_propagate(errp, ...);@p1
>> +)
>> +     ...
>> +(
>> +     error_propagate_prepend(errp, ...);@p2
>> +|
>> +     error_propagate(errp, ...);@p2
>> +)
>> +     ... when any
>> + }
>> +
>> +@ script:python @
>> +fn << check2.fn;
>> +p1 << check2.p1;
>> +p2 << check2.p2;
>> +@@
>> +
>> +print('Warning: function {} propagates to errp several times in '
>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> [...]
>
Markus Armbruster March 13, 2020, 2:58 p.m. UTC | #5
I tried this script on the whole tree.  Observations:

* $ git-diff --shortstat \*.[ch]
   333 files changed, 3480 insertions(+), 4586 deletions(-)

* Twelve functions have "several definitions of Error * local variable".

  Eight declare such a variable within a loop.  Reported because
  Coccinelle matches along control flow, not just along text.  Ignore.

  Remaining four:

  * ivshmem_common_realize()

    Two variables (messed up in commit fe44dc91807), should be replaced
    by one.

  * qmp_query_cpu_model_expansion() two times

    Three declarations in separate blocks; two should be replaced by
    &error_abort, one moved to the function block.

  * xen_block_device_destroy()

    Two declarations in seperate blocks; should be replaced by a single
    one.

  Separate manual cleanup patches, ideally applied before running
  Coccinelle to keep Coccinelle's changes as simple and safe as
  possible.  I'll post patches.  Only the one for
  xen_block_device_destroy() affects by this series.

* No function "propagates to errp several times"

  I tested the rule does detect this as advertized by feeding it an
  obvious example.  We're good.

* ERRP_AUTO_PROPAGATE() inserted 744 times, always right at the
  beginning of a function.

* As far as I can tell, all changed functions have ERRP_AUTO_PROPAGATE()
  inserted.  Good.

* Almost 1100 error propagations dropped:error_propagate() removed,
  error_propagate_prepend() replaced by just error_prepend().

* Four error_propagate() are transformed.  Two instances each in
  aspeed_soc_ast2600_realize() and aspeed_soc_realize().  Pattern:

     {
    +    ERRP_AUTO_PROPAGATE();
         ...
    -    Error *err = NULL, *local_err = NULL;
    +    Error *local_err = NULL;
         ...

             object_property_set_T(..., 
    -                              &err);
    +                              errp);
             object_property_set_T(...,
                                   &local_err);
    -        error_propagate(&err, local_err);
    -        if (err) {
    -            error_propagate(errp, err);
    +        error_propagate(errp, local_err);
    +        if (*errp) {
                 return;
             }

  This is what error.h calls "Receive and accumulate multiple errors
  (first one wins)".

  Result:

        ERRP_AUTO_PROPAGATE();
        ...
        Error *local_err = NULL;
        ...

            object_property_set_T(..., errp);
            object_property_set_T(..., &local_err);
            error_propagate(errp, local_err);
            if (*errp) {
                return;
            }

  Could be done without the accumulation:

        ERRP_AUTO_PROPAGATE();
        ...

            object_property_set_T(..., errp);
            if (*errp) {
                return;
            }
            object_property_set_T(..., errp);
            if (*errp) {
                return;
            }

  I find this a bit easier to understand.  Matter of taste.  If we want
  to change to this, do it manually and separately.  I'd do it on top.

* Some 90 propagations remain.

  Some of them could use cleanup, e.g. file_memory_backend_set_pmem(),
  css_clear_io_interrupt().  Out of scope for this series.

  Some move errors around in unusual ways, e.g. in block/nbd.c.  Could
  use review.  Out of scope for this series.

  I spotted three that should be transformed, but aren't:

  - qcrypto_block_luks_store_key()

    I believe g_autoptr() confuses Coccinelle.  Undermines all our
    Coccinelle use, not just this patch.  I think we need to update
    scripts/cocci-macro-file.h for it.

  - armsse_realize()

    Something in this huge function confuses Coccinelle, but I don't
    know what exactly.  If I delete most of it, the error_propagate()
    transforms okay.  If I delete less, Coccinelle hangs.

  - apply_cpu_model()

    Gets transformed fine if I remove the #ifndef CONFIG_USER_ONLY.  I
    have no idea why the #if spooks Coccinelle here, but not elsewhere.

  None of these three affects this series.  No need to hold it back for
  further investigation.

* 30 error_free() and two warn_reportf_err() are transformed.  Patterns:

    -    error_free(local_err);
    -    local_err = NULL;
    +    error_free_errp(errp);

  and

    -    error_free(local_err);
    +    error_free_errp(errp);

  and

    -    warn_report_err(local_err);
    -    local_err = NULL;
    +    warn_report_errp(errp);

  Good.

* Many error_free(), error_reportf_err() and warn_reportf_err() remain.
  None of them have an argument of the form *errp.  Such arguments would
  have to be reviewed for possible interference with
  ERRP_AUTO_PROPAGATE().

* Almost 700 Error *err = NULL removed.  Almost 600 remain.

* Error usage in rdma.c is questionable / wrong.  Out of scope for this
  series.

As far as I can tell, your Coccinelle script is working as intended,
except for three missed error propagations noted above.  We can proceed
with this series regardless, if we want.  I'd prefer to integrate my
forthcoming cleanup to xen_block_device_destroy(), though.
Vladimir Sementsov-Ogievskiy March 13, 2020, 3:22 p.m. UTC | #6
13.03.2020 17:58, Markus Armbruster wrote:
> I tried this script on the whole tree.  Observations:
> 
> * $ git-diff --shortstat \*.[ch]
>     333 files changed, 3480 insertions(+), 4586 deletions(-)
> 
> * Twelve functions have "several definitions of Error * local variable".
> 
>    Eight declare such a variable within a loop.  Reported because
>    Coccinelle matches along control flow, not just along text.  Ignore.
> 
>    Remaining four:
> 
>    * ivshmem_common_realize()
> 
>      Two variables (messed up in commit fe44dc91807), should be replaced
>      by one.
> 
>    * qmp_query_cpu_model_expansion() two times
> 
>      Three declarations in separate blocks; two should be replaced by
>      &error_abort, one moved to the function block.
> 
>    * xen_block_device_destroy()
> 
>      Two declarations in seperate blocks; should be replaced by a single
>      one.
> 
>    Separate manual cleanup patches, ideally applied before running
>    Coccinelle to keep Coccinelle's changes as simple and safe as
>    possible.  I'll post patches.  Only the one for
>    xen_block_device_destroy() affects by this series.
> 
> * No function "propagates to errp several times"
> 
>    I tested the rule does detect this as advertized by feeding it an
>    obvious example.  We're good.
> 
> * ERRP_AUTO_PROPAGATE() inserted 744 times, always right at the
>    beginning of a function.
> 
> * As far as I can tell, all changed functions have ERRP_AUTO_PROPAGATE()
>    inserted.  Good.
> 
> * Almost 1100 error propagations dropped:error_propagate() removed,
>    error_propagate_prepend() replaced by just error_prepend().
> 
> * Four error_propagate() are transformed.  Two instances each in
>    aspeed_soc_ast2600_realize() and aspeed_soc_realize().  Pattern:
> 
>       {
>      +    ERRP_AUTO_PROPAGATE();
>           ...
>      -    Error *err = NULL, *local_err = NULL;
>      +    Error *local_err = NULL;
>           ...
> 
>               object_property_set_T(...,
>      -                              &err);
>      +                              errp);
>               object_property_set_T(...,
>                                     &local_err);
>      -        error_propagate(&err, local_err);
>      -        if (err) {
>      -            error_propagate(errp, err);
>      +        error_propagate(errp, local_err);
>      +        if (*errp) {
>                   return;
>               }
> 
>    This is what error.h calls "Receive and accumulate multiple errors
>    (first one wins)".
> 
>    Result:
> 
>          ERRP_AUTO_PROPAGATE();
>          ...
>          Error *local_err = NULL;
>          ...
> 
>              object_property_set_T(..., errp);
>              object_property_set_T(..., &local_err);
>              error_propagate(errp, local_err);
>              if (*errp) {
>                  return;
>              }
> 
>    Could be done without the accumulation:
> 
>          ERRP_AUTO_PROPAGATE();
>          ...
> 
>              object_property_set_T(..., errp);
>              if (*errp) {
>                  return;
>              }
>              object_property_set_T(..., errp);
>              if (*errp) {
>                  return;
>              }
> 
>    I find this a bit easier to understand.  Matter of taste.  If we want
>    to change to this, do it manually and separately.  I'd do it on top.
> 
> * Some 90 propagations remain.
> 
>    Some of them could use cleanup, e.g. file_memory_backend_set_pmem(),
>    css_clear_io_interrupt().  Out of scope for this series.
> 
>    Some move errors around in unusual ways, e.g. in block/nbd.c.  Could
>    use review.  Out of scope for this series.
> 
>    I spotted three that should be transformed, but aren't:
> 
>    - qcrypto_block_luks_store_key()
> 
>      I believe g_autoptr() confuses Coccinelle.  Undermines all our
>      Coccinelle use, not just this patch.  I think we need to update
>      scripts/cocci-macro-file.h for it.
> 
>    - armsse_realize()
> 
>      Something in this huge function confuses Coccinelle, but I don't
>      know what exactly.  If I delete most of it, the error_propagate()
>      transforms okay.  If I delete less, Coccinelle hangs.
> 
>    - apply_cpu_model()
> 
>      Gets transformed fine if I remove the #ifndef CONFIG_USER_ONLY.  I
>      have no idea why the #if spooks Coccinelle here, but not elsewhere.
> 
>    None of these three affects this series.  No need to hold it back for
>    further investigation.
> 
> * 30 error_free() and two warn_reportf_err() are transformed.  Patterns:
> 
>      -    error_free(local_err);
>      -    local_err = NULL;
>      +    error_free_errp(errp);
> 
>    and
> 
>      -    error_free(local_err);
>      +    error_free_errp(errp);
> 
>    and
> 
>      -    warn_report_err(local_err);
>      -    local_err = NULL;
>      +    warn_report_errp(errp);
> 
>    Good.
> 
> * Many error_free(), error_reportf_err() and warn_reportf_err() remain.
>    None of them have an argument of the form *errp.  Such arguments would
>    have to be reviewed for possible interference with
>    ERRP_AUTO_PROPAGATE().
> 
> * Almost 700 Error *err = NULL removed.  Almost 600 remain.
> 
> * Error usage in rdma.c is questionable / wrong.  Out of scope for this
>    series.
> 
> As far as I can tell, your Coccinelle script is working as intended,
> except for three missed error propagations noted above.  We can proceed
> with this series regardless, if we want.  I'd prefer to integrate my
> forthcoming cleanup to xen_block_device_destroy(), though.
> 

Great investigation!!!

I'm for proceeding as is, or with your cleanup for xen_block_device_destroy().
Still, script converts xen_block_device_destroy correctly anyway, resulting code
will be the same and we are OK without cleanup as well.
Markus Armbruster March 13, 2020, 3:34 p.m. UTC | #7
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 13.03.2020 10:50, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>
>> [...]
>>> +// Warn several Error * definitions.
>>> +@check1 disable optional_qualifier exists@
>>> +identifier fn = rule1.fn, local_err, local_err2;
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     ...
>>> +     Error *local_err = NULL;
>>> +     ... when any
>>> +     Error *local_err2 = NULL;
>>> +     ... when any
>>> + }
>>> +
>>> +@ script:python @
>>> +fn << check1.fn;
>>> +@@
>>> +
>>> +print('Warning: function {} has several definitions of '
>>> +      'Error * local variable'.format(fn))
>>
>> Printing the positions like you do in the next rule is useful when
>> examining these warnings.
>
> I decided that searching for Error * definition is simple, and better for
> user to search all definitions by hand (may be more than too).
>
> But understanding control flows is more complex thing and better to help
> user with line positions.
>
> But if you want, we can add them of course. Note, that for some reasons some
> times coccinelle instead of original filename prints something like /tmp/...original-name...
> so it don't look nice and may be a bit misleading.

I noticed when I actually tried mu idea %-}
Markus Armbruster March 13, 2020, 3:42 p.m. UTC | #8
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 12.03.2020 19:36, Markus Armbruster wrote:
>> I may have a second look tomorrow with fresher eyes, but let's get this
>> out now as is.
>>
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>
>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>> does corresponding changes in code (look for details in
>>> include/qapi/error.h)
>>>
>>> Usage example:
>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>   --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>   --max-width 80 FILES...
>>>
>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>> ---
>>>
>>> Cc: Eric Blake <eblake@redhat.com>
>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>> Cc: Max Reitz <mreitz@redhat.com>
>>> Cc: Greg Kurz <groug@kaod.org>
>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>> Cc: Paul Durrant <paul@xen.org>
>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>> Cc: Markus Armbruster <armbru@redhat.com>
>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>> Cc: qemu-devel@nongnu.org
>>> Cc: qemu-block@nongnu.org
>>> Cc: xen-devel@lists.xenproject.org
>>>
>>>   scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>   include/qapi/error.h                          |   3 +
>>>   MAINTAINERS                                   |   1 +
>>>   3 files changed, 331 insertions(+)
>>>   create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>
>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>> new file mode 100644
>>> index 0000000000..7dac2dcfa4
>>> --- /dev/null
>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>> @@ -0,0 +1,327 @@
>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>> +//
>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>> +//
>>> +// This program is free software; you can redistribute it and/or
>>> +// modify it under the terms of the GNU General Public License as
>>> +// published by the Free Software Foundation; either version 2 of the
>>> +// License, or (at your option) any later version.
>>> +//
>>> +// This program is distributed in the hope that it will be useful,
>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>> +// GNU General Public License for more details.
>>> +//
>>> +// You should have received a copy of the GNU General Public License
>>> +// along with this program.  If not, see
>>> +// <http://www.gnu.org/licenses/>.
>>> +//
>>> +// Usage example:
>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>> +//  --no-show-diff --max-width 80 FILES...
>>> +//
>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>> +// than 80, and without this parameter coccinelle may reindent some
>>> +// lines which fit into 80 characters but not to coccinelle default,
>>> +// which in turn produces extra patch hunks for no reason.
>>
>> This is about unwanted reformatting of parameter lists due to the ___
>> chaining hack.  --max-width 80 makes that less likely, but not
>> impossible.
>>
>> We can search for unwanted reformatting of parameter lists.  I think
>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>> tree, I get one false positive (not a parameter list), and one hit:
>>
>>      @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>           }
>>       }
>>
>>      -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>      +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>      +                               Error **errp)
>>       {
>>      +    ERRP_AUTO_PROPAGATE();
>>           int i;
>>
>>           if (!props) {
>>
>> Reformatting, but not unwanted.
>
> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.

Agree.

>>
>> The --max-width 80 hack is good enough for me.
>>
>> It does result in slightly long transformed lines, e.g. this one in
>> replication.c:
>>
>>      @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>               s->mode = REPLICATION_MODE_PRIMARY;
>>               top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>               if (top_id) {
>>      -            error_setg(&local_err, "The primary side does not support option top-id");
>>      +            error_setg(errp, "The primary side does not support option top-id");
>>                   goto fail;
>>               }
>>           } else if (!strcmp(mode, "secondary")) {
>>
>> v8 did break this line (that's how I found it).  However, v9 still
>> shortens the line, just not below the target.  All your + lines look
>> quite unlikely to lengthen lines.  Let's not worry about this.
>>
>>> +// Switch unusual Error ** parameter names to errp
>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>> +//
>>> +// Disable optional_qualifier to skip functions with
>>> +// "Error *const *errp" parameter.
>>> +//
>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>> +// that signals unusual semantics, and the parameter name may well
>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>> +//
>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>> +// error_propagate_prepend().
>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>> +identifier fn;
>>> +identifier _errp != errp;
>>> +@@
>>> +
>>> + fn(...,
>>> +-   Error **_errp
>>> ++   Error **errp
>>> +    ,...)
>>> + {
>>> +(
>>> +     ... when != assert(_errp && *_errp)
>>> +&
>>> +     <...
>>> +-    _errp
>>> ++    errp
>>> +     ...>
>>> +)
>>> + }
>>> +
>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>> +// necessary
>>> +//
>>> +// Note, that without "when any" the final "..." does not mach
>>> +// something matched by previous pattern, i.e. the rule will not match
>>> +// double error_prepend in control flow like in
>>> +// vfio_set_irq_signaling().
>>> +//
>>> +// Note, "exists" says that we want apply rule even if it matches not
>>> +// on all possible control flows (otherwise, it will not match
>>> +// standard pattern when error_propagate() call is in if branch).
>>> +@ disable optional_qualifier exists@
>>> +identifier fn, local_err;
>>> +symbol errp;
>>> +@@
>>> +
>>> + fn(..., Error **errp, ...)
>>> + {
>>> ++   ERRP_AUTO_PROPAGATE();
>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>> +(
>>> +(
>>> +    error_append_hint(errp, ...);
>>> +|
>>> +    error_prepend(errp, ...);
>>> +|
>>> +    error_vprepend(errp, ...);
>>> +)
>>> +    ... when any
>>> +|
>>> +    Error *local_err = NULL;
>>> +    ...
>>> +(
>>> +    error_propagate_prepend(errp, local_err, ...);
>>> +|
>>> +    error_propagate(errp, local_err);
>>> +)
>>> +    ...
>>> +)
>>> + }
>>> +
>>> +
>>> +// Match functions with propagation of local error to errp.
>>> +// We want to refer these functions in several following rules, but I
>>> +// don't know a proper way to inherit a function, not just its name
>>> +// (to not match another functions with same name in following rules).
>>> +// Not-proper way is as follows: rename errp parameter in functions
>>> +// header and match it in following rules. Rename it back after all
>>> +// transformations.
>>> +//
>>> +// The simplest case of propagation scheme is single definition of
>>> +// local_err with at most one error_propagate_prepend or
>>> +// error_propagate on each control-flow. Still, we want to match more
>>> +// complex schemes too. We'll warn them with help of further rules.
>>
>> I think what we actually want is to examine instances of this pattern to
>> figure out whether and how we want to transform them.  Perhaps:
>>
>>      // The common case is a single definition of local_err with at most one
>>      // error_propagate_prepend() or error_propagate() on each control-flow
>>      // path. Instances of this case we convert with this script. Functions
>
> For me, sounds a bit like "other things we don't convert".
> Actually we convert other things too.

What other patterns of error propagation do we convert?

>>      // with multiple definitions or propagates we want to examine
>>      // manually. Later rules emit warnings to guide us to them.
>>
>>> +@rule1 disable optional_qualifier exists@
>>> +identifier fn, local_err;
>>> +symbol errp;
>>> +@@
>>> +
>>> + fn(..., Error **
>>> +-    errp
>>> ++    ____
>>> +    , ...)
>>> + {
>>> +     ...
>>> +     Error *local_err = NULL;
>>> +     ...
>>> +(
>>> +     error_propagate_prepend(errp, local_err, ...);
>>> +|
>>> +     error_propagate(errp, local_err);
>>> +)
>>> +     ...
>>> + }
>>> +
>>> +
>>> +// Warn several Error * definitions.
>>> +@check1 disable optional_qualifier exists@
>>> +identifier fn = rule1.fn, local_err, local_err2;
>>
>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>> particular reason for the difference?
>
> I didn't find other way to ref check1.fn in next python rule. It just don't
> work if I write here just rule1.fn.
>
>>
>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>> everywhere, then apply the script to the complete tree, I get the same
>> result.
>
> I think, it's more efficient to reuse names from previous rules. I think it should
> work faster (more information, less extra matching).

Nope.  With my hacked up script (patch appended) Coccinelle is actually
*faster* for the .[ch] touched by this series: with your unmodified
script, it takes a bit over 12s on my box, with mine around 7s.  Output
is identical.

Never guess performance, always measure it :)

Two notes on my script:

* Unlike yours, it recognizes double-propagation in my test case.
  Discussed below.

* Its "several definitions of" warning includes positions.  That turned
  out to be useless, but I've been too lazy to take that out again.

>>
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     ...
>>> +     Error *local_err = NULL;
>>> +     ... when any
>>> +     Error *local_err2 = NULL;
>>> +     ... when any
>>> + }
>>> +
>>> +@ script:python @
>>> +fn << check1.fn;
>>> +@@
>>> +
>>> +print('Warning: function {} has several definitions of '
>>> +      'Error * local variable'.format(fn))
>>> +
>>> +// Warn several propagations in control flow.
>>> +@check2 disable optional_qualifier exists@
>>> +identifier fn = rule1.fn;
>>> +symbol errp;
>>> +position p1, p2;
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     ...
>>> +(
>>> +     error_propagate_prepend(errp, ...);@p1
>>> +|
>>> +     error_propagate(errp, ...);@p1
>>> +)
>>> +     ...
>>> +(
>>> +     error_propagate_prepend(errp, ...);@p2
>>> +|
>>> +     error_propagate(errp, ...);@p2
>>> +)
>>> +     ... when any
>>> + }
>>> +
>>
>> Hmm, we don't catch the example I used in review of v8:
>>
>>      extern foo(int, Error **);
>>      extern bar(int, Error **);
>>
>>      void frob(Error **errp)
>>      {
>>          Error *local_err = NULL;
>>          int arg;
>>
>>          foo(arg, errp);
>>          bar(arg, &local_err);
>>          error_propagate(errp, local_err);
>>          bar(arg + 1, &local_err);
>>          error_propagate(errp, local_err);
>>      }
>>
>> I believe this is because rule1 does not match here.
>
> Yes, rule1 wants at least one code flow with non-doubled propagation.
>
>>
>> If I change the rule as follows, it catches the example:
>>
>>      @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>
>>       // Warn several propagations in control flow.
>>       @check2 disable optional_qualifier exists@
>>      -identifier fn = rule1.fn;
>>      -symbol errp;
>>      +identifier fn, _errp;
>>       position p1, p2;
>>       @@
>>
>>      - fn(..., Error ** ____, ...)
>>      + fn(..., Error **_errp, ...)
>>        {
>>            ...
>>       (
>>      -     error_propagate_prepend(errp, ...);@p1
>>      +     error_propagate_prepend(_errp, ...);@p1
>>       |
>>      -     error_propagate(errp, ...);@p1
>>      +     error_propagate(_errp, ...);@p1
>>       )
>>            ...
>>       (
>>      -     error_propagate_prepend(errp, ...);@p2
>>      +     error_propagate_prepend(_errp, ...);@p2
>>       |
>>      -     error_propagate(errp, ...);@p2
>>      +     error_propagate(_errp, ...);@p2
>>       )
>>            ... when any
>>        }
>>
>> To my mild surprise, it still doesn't find anything in our tree.
>>
>> Should we decouple the previous rule from rule1, too?  I tested the
>> following on the whole tree:
>
> I don't think so. Why to check what we are not going to convert? If we want
> to check side things, it's better to do it in other coccinelle script..

Misunderstanding?  The rules are still chained together via the ___
hack, just not via function name, because that's unreliable and
redundant.

>>
>>      @@ -136,10 +136,10 @@ symbol errp;
>>
>>       // Warn several Error * definitions.
>>       @check1 disable optional_qualifier exists@
>>      -identifier fn = rule1.fn, local_err, local_err2;
>>      +identifier fn, _errp, local_err, local_err2;
>>       @@
>>
>>      - fn(..., Error ** ____, ...)
>>      + fn(..., Error **_errp, ...)
>>        {
>>            ...
>>            Error *local_err = NULL;
>>
>> Warnings remain unchanged.
>>
>>> +@ script:python @
>>> +fn << check2.fn;
>>> +p1 << check2.p1;
>>> +p2 << check2.p2;
>>> +@@
>>> +
>>> +print('Warning: function {} propagates to errp several times in '
>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>> +
>>> +// Convert special case with goto separately.
>>> +// I tried merging this into the following rule the obvious way, but
>>> +// it made Coccinelle hang on block.c
>>> +//
>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>> +// "out: }" things later after all transformations (the rule will be
>>> +// the same, just without error_propagate() call), coccinelle fails to
>>> +// match this "out: }".
>>> +@ disable optional_qualifier@
>>> +identifier rule1.fn, rule1.local_err, out;
>>
>> As explained above, I doubt the need for rule1.fn.  We do need
>> rule1.local_err to avoid unwanted transformations.  More of the same
>> below.
>
> Logically, I want to inherit from rule1. So why not to stress it by inheriting
> fn variable? It's just a correct thing to do.
> And I hope it helps coccinelle to work more efficiently.
>
>>
>>> +symbol errp;
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     <...
>>> +-    goto out;
>>> ++    return;
>>> +     ...>
>>> +- out:
>>> +-    error_propagate(errp, local_err);
>>> + }
>>> +
>>> +// Convert most of local_err related stuff.
>>> +//
>>> +// Note, that we update everything related to matched by rule1
>>> +// function name and local_err name. We may match something not
>>> +// related to the pattern matched by rule1. For example, local_err may
>>> +// be defined with the same name in different blocks inside one
>>> +// function, and in one block follow the propagation pattern and in
>>> +// other block doesn't. Or we may have several functions with the same
>>> +// name (for different configurations).
>>> +//
>>> +// Note also that errp-cleaning functions
>>> +//   error_free_errp
>>> +//   error_report_errp
>>> +//   error_reportf_errp
>>> +//   warn_report_errp
>>> +//   warn_reportf_errp
>>> +// are not yet implemented. They must call corresponding Error* -
>>> +// freeing function and then set *errp to NULL, to avoid further
>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>> +// For example, error_free_errp may look like this:
>>> +//
>>> +//    void error_free_errp(Error **errp)
>>> +//    {
>>> +//        error_free(*errp);
>>> +//        *errp = NULL;
>>> +//    }
>>> +@ disable optional_qualifier exists@
>>> +identifier rule1.fn, rule1.local_err;
>>> +expression list args;
>>> +symbol errp;
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     <...
>>> +(
>>> +-    Error *local_err = NULL;
>>> +|
>>> +
>>> +// Convert error clearing functions
>>> +(
>>> +-    error_free(local_err);
>>> ++    error_free_errp(errp);
>>> +|
>>> +-    error_report_err(local_err);
>>> ++    error_report_errp(errp);
>>> +|
>>> +-    error_reportf_err(local_err, args);
>>> ++    error_reportf_errp(errp, args);
>>> +|
>>> +-    warn_report_err(local_err);
>>> ++    warn_report_errp(errp);
>>> +|
>>> +-    warn_reportf_err(local_err, args);
>>> ++    warn_reportf_errp(errp, args);
>>> +)
>>> +?-    local_err = NULL;
>>> +
>>> +|
>>> +-    error_propagate_prepend(errp, local_err, args);
>>> ++    error_prepend(errp, args);
>>> +|
>>> +-    error_propagate(errp, local_err);
>>> +|
>>> +-    &local_err
>>> ++    errp
>>> +)
>>> +     ...>
>>> + }
>>> +
>>> +// Convert remaining local_err usage. For example, different kinds of
>>> +// error checking in if conditionals. We can't merge this into
>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>> +// least with "- local_err = NULL").
>>> +@ disable optional_qualifier@
>>> +identifier rule1.fn, rule1.local_err;
>>> +symbol errp;
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     <...
>>> +-    local_err
>>> ++    *errp
>>> +     ...>
>>> + }
>>> +
>>> +// Always use the same pattern for checking error
>>> +@ disable optional_qualifier@
>>> +identifier rule1.fn;
>>> +symbol errp;
>>> +@@
>>> +
>>> + fn(..., Error ** ____, ...)
>>> + {
>>> +     <...
>>> +-    *errp != NULL
>>> ++    *errp
>>> +     ...>
>>> + }
>>> +
>>> +// Revert temporary ___ identifier.
>>> +@ disable optional_qualifier@
>>> +identifier rule1.fn;
>>> +@@
>>> +
>>> + fn(..., Error **
>>> +-   ____
>>> ++   errp
>>> +    , ...)
>>> + {
>>> +     ...
>>> + }
>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>> index 30140d9bfe..56c133520d 100644
>>> --- a/include/qapi/error.h
>>> +++ b/include/qapi/error.h
>>> @@ -214,6 +214,9 @@
>>>    *         }
>>>    *         ...
>>>    *     }
>>> + *
>>> + * For mass-conversion use script
>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>    */
>>>     #ifndef ERROR_H
>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>> index 857f969aa1..047f1b9714 100644
>>> --- a/MAINTAINERS
>>> +++ b/MAINTAINERS
>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>   F: qapi/error.json
>>>   F: util/error.c
>>>   F: util/qemu-error.c
>>> +F: scripts/coccinelle/*err*.cocci
>>>     GDB stub
>>>   M: Alex Bennée <alex.bennee@linaro.org>
>>


From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
From: Markus Armbruster <armbru@redhat.com>
Date: Fri, 13 Mar 2020 14:27:57 +0100
Subject: [PATCH] fixup! scripts: Coccinelle script to use
 ERRP_AUTO_PROPAGATE()

---
 scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
 1 file changed, 20 insertions(+), 17 deletions(-)

diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
index 7dac2dcfa4..43b0b0e63b 100644
--- a/scripts/coccinelle/auto-propagated-errp.cocci
+++ b/scripts/coccinelle/auto-propagated-errp.cocci
@@ -136,45 +136,48 @@ symbol errp;
 
 // Warn several Error * definitions.
 @check1 disable optional_qualifier exists@
-identifier fn = rule1.fn, local_err, local_err2;
+identifier fn, _errp, local_err, local_err2;
+position p1, p2;
 @@
 
- fn(..., Error ** ____, ...)
+ fn(..., Error **_errp, ...)
  {
      ...
-     Error *local_err = NULL;
+     Error *local_err = NULL;@p1
      ... when any
-     Error *local_err2 = NULL;
+     Error *local_err2 = NULL;@p2
      ... when any
  }
 
 @ script:python @
 fn << check1.fn;
+p1 << check1.p1;
+p2 << check1.p2;
 @@
 
 print('Warning: function {} has several definitions of '
-      'Error * local variable'.format(fn))
+      'Error * local variable: at {}:{} and then at {}:{}'.format(
+          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
 
 // Warn several propagations in control flow.
 @check2 disable optional_qualifier exists@
-identifier fn = rule1.fn;
-symbol errp;
+identifier fn, _errp;
 position p1, p2;
 @@
 
- fn(..., Error ** ____, ...)
+ fn(..., Error **_errp, ...)
  {
      ...
 (
-     error_propagate_prepend(errp, ...);@p1
+     error_propagate_prepend(_errp, ...);@p1
 |
-     error_propagate(errp, ...);@p1
+     error_propagate(_errp, ...);@p1
 )
      ...
 (
-     error_propagate_prepend(errp, ...);@p2
+     error_propagate_prepend(_errp, ...);@p2
 |
-     error_propagate(errp, ...);@p2
+     error_propagate(_errp, ...);@p2
 )
      ... when any
  }
@@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
 // the same, just without error_propagate() call), coccinelle fails to
 // match this "out: }".
 @ disable optional_qualifier@
-identifier rule1.fn, rule1.local_err, out;
+identifier fn, rule1.local_err, out;
 symbol errp;
 @@
 
@@ -239,7 +242,7 @@ symbol errp;
 //        *errp = NULL;
 //    }
 @ disable optional_qualifier exists@
-identifier rule1.fn, rule1.local_err;
+identifier fn, rule1.local_err;
 expression list args;
 symbol errp;
 @@
@@ -287,7 +290,7 @@ symbol errp;
 // previous hunk, as this conflicts with other substitutions in it (at
 // least with "- local_err = NULL").
 @ disable optional_qualifier@
-identifier rule1.fn, rule1.local_err;
+identifier fn, rule1.local_err;
 symbol errp;
 @@
 
@@ -301,7 +304,7 @@ symbol errp;
 
 // Always use the same pattern for checking error
 @ disable optional_qualifier@
-identifier rule1.fn;
+identifier fn;
 symbol errp;
 @@
 
@@ -315,7 +318,7 @@ symbol errp;
 
 // Revert temporary ___ identifier.
 @ disable optional_qualifier@
-identifier rule1.fn;
+identifier fn;
 @@
 
  fn(..., Error **
Vladimir Sementsov-Ogievskiy March 13, 2020, 4:12 p.m. UTC | #9
13.03.2020 18:42, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> 12.03.2020 19:36, Markus Armbruster wrote:
>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>> out now as is.
>>>
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>
>>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>>> does corresponding changes in code (look for details in
>>>> include/qapi/error.h)
>>>>
>>>> Usage example:
>>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>    --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>>    --max-width 80 FILES...
>>>>
>>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>>> ---
>>>>
>>>> Cc: Eric Blake <eblake@redhat.com>
>>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>>> Cc: Max Reitz <mreitz@redhat.com>
>>>> Cc: Greg Kurz <groug@kaod.org>
>>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>>> Cc: Paul Durrant <paul@xen.org>
>>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>>> Cc: Markus Armbruster <armbru@redhat.com>
>>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>>> Cc: qemu-devel@nongnu.org
>>>> Cc: qemu-block@nongnu.org
>>>> Cc: xen-devel@lists.xenproject.org
>>>>
>>>>    scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>>    include/qapi/error.h                          |   3 +
>>>>    MAINTAINERS                                   |   1 +
>>>>    3 files changed, 331 insertions(+)
>>>>    create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>>
>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>> new file mode 100644
>>>> index 0000000000..7dac2dcfa4
>>>> --- /dev/null
>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>> @@ -0,0 +1,327 @@
>>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>>> +//
>>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>>> +//
>>>> +// This program is free software; you can redistribute it and/or
>>>> +// modify it under the terms of the GNU General Public License as
>>>> +// published by the Free Software Foundation; either version 2 of the
>>>> +// License, or (at your option) any later version.
>>>> +//
>>>> +// This program is distributed in the hope that it will be useful,
>>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>>> +// GNU General Public License for more details.
>>>> +//
>>>> +// You should have received a copy of the GNU General Public License
>>>> +// along with this program.  If not, see
>>>> +// <http://www.gnu.org/licenses/>.
>>>> +//
>>>> +// Usage example:
>>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>>> +//  --no-show-diff --max-width 80 FILES...
>>>> +//
>>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>>> +// than 80, and without this parameter coccinelle may reindent some
>>>> +// lines which fit into 80 characters but not to coccinelle default,
>>>> +// which in turn produces extra patch hunks for no reason.
>>>
>>> This is about unwanted reformatting of parameter lists due to the ___
>>> chaining hack.  --max-width 80 makes that less likely, but not
>>> impossible.
>>>
>>> We can search for unwanted reformatting of parameter lists.  I think
>>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>>> tree, I get one false positive (not a parameter list), and one hit:
>>>
>>>       @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>>            }
>>>        }
>>>
>>>       -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>>       +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>>       +                               Error **errp)
>>>        {
>>>       +    ERRP_AUTO_PROPAGATE();
>>>            int i;
>>>
>>>            if (!props) {
>>>
>>> Reformatting, but not unwanted.
>>
>> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
>> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.
> 
> Agree.
> 
>>>
>>> The --max-width 80 hack is good enough for me.
>>>
>>> It does result in slightly long transformed lines, e.g. this one in
>>> replication.c:
>>>
>>>       @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>>                s->mode = REPLICATION_MODE_PRIMARY;
>>>                top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>>                if (top_id) {
>>>       -            error_setg(&local_err, "The primary side does not support option top-id");
>>>       +            error_setg(errp, "The primary side does not support option top-id");
>>>                    goto fail;
>>>                }
>>>            } else if (!strcmp(mode, "secondary")) {
>>>
>>> v8 did break this line (that's how I found it).  However, v9 still
>>> shortens the line, just not below the target.  All your + lines look
>>> quite unlikely to lengthen lines.  Let's not worry about this.
>>>
>>>> +// Switch unusual Error ** parameter names to errp
>>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>>> +//
>>>> +// Disable optional_qualifier to skip functions with
>>>> +// "Error *const *errp" parameter.
>>>> +//
>>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>>> +// that signals unusual semantics, and the parameter name may well
>>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>>> +//
>>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>>> +// error_propagate_prepend().
>>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>>> +identifier fn;
>>>> +identifier _errp != errp;
>>>> +@@
>>>> +
>>>> + fn(...,
>>>> +-   Error **_errp
>>>> ++   Error **errp
>>>> +    ,...)
>>>> + {
>>>> +(
>>>> +     ... when != assert(_errp && *_errp)
>>>> +&
>>>> +     <...
>>>> +-    _errp
>>>> ++    errp
>>>> +     ...>
>>>> +)
>>>> + }
>>>> +
>>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>>> +// necessary
>>>> +//
>>>> +// Note, that without "when any" the final "..." does not mach
>>>> +// something matched by previous pattern, i.e. the rule will not match
>>>> +// double error_prepend in control flow like in
>>>> +// vfio_set_irq_signaling().
>>>> +//
>>>> +// Note, "exists" says that we want apply rule even if it matches not
>>>> +// on all possible control flows (otherwise, it will not match
>>>> +// standard pattern when error_propagate() call is in if branch).
>>>> +@ disable optional_qualifier exists@
>>>> +identifier fn, local_err;
>>>> +symbol errp;
>>>> +@@
>>>> +
>>>> + fn(..., Error **errp, ...)
>>>> + {
>>>> ++   ERRP_AUTO_PROPAGATE();
>>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>>> +(
>>>> +(
>>>> +    error_append_hint(errp, ...);
>>>> +|
>>>> +    error_prepend(errp, ...);
>>>> +|
>>>> +    error_vprepend(errp, ...);
>>>> +)
>>>> +    ... when any
>>>> +|
>>>> +    Error *local_err = NULL;
>>>> +    ...
>>>> +(
>>>> +    error_propagate_prepend(errp, local_err, ...);
>>>> +|
>>>> +    error_propagate(errp, local_err);
>>>> +)
>>>> +    ...
>>>> +)
>>>> + }
>>>> +
>>>> +
>>>> +// Match functions with propagation of local error to errp.
>>>> +// We want to refer these functions in several following rules, but I
>>>> +// don't know a proper way to inherit a function, not just its name
>>>> +// (to not match another functions with same name in following rules).
>>>> +// Not-proper way is as follows: rename errp parameter in functions
>>>> +// header and match it in following rules. Rename it back after all
>>>> +// transformations.
>>>> +//
>>>> +// The simplest case of propagation scheme is single definition of
>>>> +// local_err with at most one error_propagate_prepend or
>>>> +// error_propagate on each control-flow. Still, we want to match more
>>>> +// complex schemes too. We'll warn them with help of further rules.
>>>
>>> I think what we actually want is to examine instances of this pattern to
>>> figure out whether and how we want to transform them.  Perhaps:
>>>
>>>       // The common case is a single definition of local_err with at most one
>>>       // error_propagate_prepend() or error_propagate() on each control-flow
>>>       // path. Instances of this case we convert with this script. Functions
>>
>> For me, sounds a bit like "other things we don't convert".
>> Actually we convert other things too.
> 
> What other patterns of error propagation do we convert?

Something like in xen_block_device_destroy, why not? Otherwise, it's better to avoid
matching things like xen_block_device_destroy, not just warn them.
But I'd prefer to proceed now as is to fit into 5.0.. Too much time already
spent on this. So, I'm OK with your wording too.

> 
>>>       // with multiple definitions or propagates we want to examine
>>>       // manually. Later rules emit warnings to guide us to them.
>>>
>>>> +@rule1 disable optional_qualifier exists@
>>>> +identifier fn, local_err;
>>>> +symbol errp;
>>>> +@@
>>>> +
>>>> + fn(..., Error **
>>>> +-    errp
>>>> ++    ____
>>>> +    , ...)
>>>> + {
>>>> +     ...
>>>> +     Error *local_err = NULL;
>>>> +     ...
>>>> +(
>>>> +     error_propagate_prepend(errp, local_err, ...);
>>>> +|
>>>> +     error_propagate(errp, local_err);
>>>> +)
>>>> +     ...
>>>> + }
>>>> +
>>>> +
>>>> +// Warn several Error * definitions.
>>>> +@check1 disable optional_qualifier exists@
>>>> +identifier fn = rule1.fn, local_err, local_err2;
>>>
>>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>>> particular reason for the difference?
>>
>> I didn't find other way to ref check1.fn in next python rule. It just don't
>> work if I write here just rule1.fn.
>>
>>>
>>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>>> everywhere, then apply the script to the complete tree, I get the same
>>> result.
>>
>> I think, it's more efficient to reuse names from previous rules. I think it should
>> work faster (more information, less extra matching).
> 
> Nope.  With my hacked up script (patch appended) Coccinelle is actually
> *faster* for the .[ch] touched by this series: with your unmodified
> script, it takes a bit over 12s on my box, with mine around 7s.  Output
> is identical.
> 
> Never guess performance, always measure it :)

Hmm, whole tree results would be better proof

> 
> Two notes on my script:
> 
> * Unlike yours, it recognizes double-propagation in my test case.
>    Discussed below.
> 
> * Its "several definitions of" warning includes positions.  That turned
>    out to be useless, but I've been too lazy to take that out again.
> 
>>>
>>>> +@@
>>>> +
>>>> + fn(..., Error ** ____, ...)
>>>> + {
>>>> +     ...
>>>> +     Error *local_err = NULL;
>>>> +     ... when any
>>>> +     Error *local_err2 = NULL;
>>>> +     ... when any
>>>> + }
>>>> +
>>>> +@ script:python @
>>>> +fn << check1.fn;
>>>> +@@
>>>> +
>>>> +print('Warning: function {} has several definitions of '
>>>> +      'Error * local variable'.format(fn))
>>>> +
>>>> +// Warn several propagations in control flow.
>>>> +@check2 disable optional_qualifier exists@
>>>> +identifier fn = rule1.fn;
>>>> +symbol errp;
>>>> +position p1, p2;
>>>> +@@
>>>> +
>>>> + fn(..., Error ** ____, ...)
>>>> + {
>>>> +     ...
>>>> +(
>>>> +     error_propagate_prepend(errp, ...);@p1
>>>> +|
>>>> +     error_propagate(errp, ...);@p1
>>>> +)
>>>> +     ...
>>>> +(
>>>> +     error_propagate_prepend(errp, ...);@p2
>>>> +|
>>>> +     error_propagate(errp, ...);@p2
>>>> +)
>>>> +     ... when any
>>>> + }
>>>> +
>>>
>>> Hmm, we don't catch the example I used in review of v8:
>>>
>>>       extern foo(int, Error **);
>>>       extern bar(int, Error **);
>>>
>>>       void frob(Error **errp)
>>>       {
>>>           Error *local_err = NULL;
>>>           int arg;
>>>
>>>           foo(arg, errp);
>>>           bar(arg, &local_err);
>>>           error_propagate(errp, local_err);
>>>           bar(arg + 1, &local_err);
>>>           error_propagate(errp, local_err);
>>>       }
>>>
>>> I believe this is because rule1 does not match here.
>>
>> Yes, rule1 wants at least one code flow with non-doubled propagation.
>>
>>>
>>> If I change the rule as follows, it catches the example:
>>>
>>>       @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>>
>>>        // Warn several propagations in control flow.
>>>        @check2 disable optional_qualifier exists@
>>>       -identifier fn = rule1.fn;
>>>       -symbol errp;
>>>       +identifier fn, _errp;
>>>        position p1, p2;
>>>        @@
>>>
>>>       - fn(..., Error ** ____, ...)
>>>       + fn(..., Error **_errp, ...)
>>>         {
>>>             ...
>>>        (
>>>       -     error_propagate_prepend(errp, ...);@p1
>>>       +     error_propagate_prepend(_errp, ...);@p1
>>>        |
>>>       -     error_propagate(errp, ...);@p1
>>>       +     error_propagate(_errp, ...);@p1
>>>        )
>>>             ...
>>>        (
>>>       -     error_propagate_prepend(errp, ...);@p2
>>>       +     error_propagate_prepend(_errp, ...);@p2
>>>        |
>>>       -     error_propagate(errp, ...);@p2
>>>       +     error_propagate(_errp, ...);@p2
>>>        )
>>>             ... when any
>>>         }
>>>
>>> To my mild surprise, it still doesn't find anything in our tree.
>>>
>>> Should we decouple the previous rule from rule1, too?  I tested the
>>> following on the whole tree:
>>
>> I don't think so. Why to check what we are not going to convert? If we want
>> to check side things, it's better to do it in other coccinelle script..
> 
> Misunderstanding?  The rules are still chained together via the ___
> hack, just not via function name, because that's unreliable and
> redundant.


Strange.. Then, how can it match something not matched by rule1?


> 
>>>
>>>       @@ -136,10 +136,10 @@ symbol errp;
>>>
>>>        // Warn several Error * definitions.
>>>        @check1 disable optional_qualifier exists@
>>>       -identifier fn = rule1.fn, local_err, local_err2;
>>>       +identifier fn, _errp, local_err, local_err2;
>>>        @@
>>>
>>>       - fn(..., Error ** ____, ...)
>>>       + fn(..., Error **_errp, ...)
>>>         {
>>>             ...
>>>             Error *local_err = NULL;
>>>
>>> Warnings remain unchanged.
>>>
>>>> +@ script:python @
>>>> +fn << check2.fn;
>>>> +p1 << check2.p1;
>>>> +p2 << check2.p2;
>>>> +@@
>>>> +
>>>> +print('Warning: function {} propagates to errp several times in '
>>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>> +
>>>> +// Convert special case with goto separately.
>>>> +// I tried merging this into the following rule the obvious way, but
>>>> +// it made Coccinelle hang on block.c
>>>> +//
>>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>>> +// "out: }" things later after all transformations (the rule will be
>>>> +// the same, just without error_propagate() call), coccinelle fails to
>>>> +// match this "out: }".
>>>> +@ disable optional_qualifier@
>>>> +identifier rule1.fn, rule1.local_err, out;
>>>
>>> As explained above, I doubt the need for rule1.fn.  We do need
>>> rule1.local_err to avoid unwanted transformations.  More of the same
>>> below.
>>
>> Logically, I want to inherit from rule1. So why not to stress it by inheriting
>> fn variable? It's just a correct thing to do.
>> And I hope it helps coccinelle to work more efficiently.
>>
>>>
>>>> +symbol errp;
>>>> +@@
>>>> +
>>>> + fn(..., Error ** ____, ...)
>>>> + {
>>>> +     <...
>>>> +-    goto out;
>>>> ++    return;
>>>> +     ...>
>>>> +- out:
>>>> +-    error_propagate(errp, local_err);
>>>> + }
>>>> +
>>>> +// Convert most of local_err related stuff.
>>>> +//
>>>> +// Note, that we update everything related to matched by rule1
>>>> +// function name and local_err name. We may match something not
>>>> +// related to the pattern matched by rule1. For example, local_err may
>>>> +// be defined with the same name in different blocks inside one
>>>> +// function, and in one block follow the propagation pattern and in
>>>> +// other block doesn't. Or we may have several functions with the same
>>>> +// name (for different configurations).
>>>> +//
>>>> +// Note also that errp-cleaning functions
>>>> +//   error_free_errp
>>>> +//   error_report_errp
>>>> +//   error_reportf_errp
>>>> +//   warn_report_errp
>>>> +//   warn_reportf_errp
>>>> +// are not yet implemented. They must call corresponding Error* -
>>>> +// freeing function and then set *errp to NULL, to avoid further
>>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>>> +// For example, error_free_errp may look like this:
>>>> +//
>>>> +//    void error_free_errp(Error **errp)
>>>> +//    {
>>>> +//        error_free(*errp);
>>>> +//        *errp = NULL;
>>>> +//    }
>>>> +@ disable optional_qualifier exists@
>>>> +identifier rule1.fn, rule1.local_err;
>>>> +expression list args;
>>>> +symbol errp;
>>>> +@@
>>>> +
>>>> + fn(..., Error ** ____, ...)
>>>> + {
>>>> +     <...
>>>> +(
>>>> +-    Error *local_err = NULL;
>>>> +|
>>>> +
>>>> +// Convert error clearing functions
>>>> +(
>>>> +-    error_free(local_err);
>>>> ++    error_free_errp(errp);
>>>> +|
>>>> +-    error_report_err(local_err);
>>>> ++    error_report_errp(errp);
>>>> +|
>>>> +-    error_reportf_err(local_err, args);
>>>> ++    error_reportf_errp(errp, args);
>>>> +|
>>>> +-    warn_report_err(local_err);
>>>> ++    warn_report_errp(errp);
>>>> +|
>>>> +-    warn_reportf_err(local_err, args);
>>>> ++    warn_reportf_errp(errp, args);
>>>> +)
>>>> +?-    local_err = NULL;
>>>> +
>>>> +|
>>>> +-    error_propagate_prepend(errp, local_err, args);
>>>> ++    error_prepend(errp, args);
>>>> +|
>>>> +-    error_propagate(errp, local_err);
>>>> +|
>>>> +-    &local_err
>>>> ++    errp
>>>> +)
>>>> +     ...>
>>>> + }
>>>> +
>>>> +// Convert remaining local_err usage. For example, different kinds of
>>>> +// error checking in if conditionals. We can't merge this into
>>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>>> +// least with "- local_err = NULL").
>>>> +@ disable optional_qualifier@
>>>> +identifier rule1.fn, rule1.local_err;
>>>> +symbol errp;
>>>> +@@
>>>> +
>>>> + fn(..., Error ** ____, ...)
>>>> + {
>>>> +     <...
>>>> +-    local_err
>>>> ++    *errp
>>>> +     ...>
>>>> + }
>>>> +
>>>> +// Always use the same pattern for checking error
>>>> +@ disable optional_qualifier@
>>>> +identifier rule1.fn;
>>>> +symbol errp;
>>>> +@@
>>>> +
>>>> + fn(..., Error ** ____, ...)
>>>> + {
>>>> +     <...
>>>> +-    *errp != NULL
>>>> ++    *errp
>>>> +     ...>
>>>> + }
>>>> +
>>>> +// Revert temporary ___ identifier.
>>>> +@ disable optional_qualifier@
>>>> +identifier rule1.fn;
>>>> +@@
>>>> +
>>>> + fn(..., Error **
>>>> +-   ____
>>>> ++   errp
>>>> +    , ...)
>>>> + {
>>>> +     ...
>>>> + }
>>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>>> index 30140d9bfe..56c133520d 100644
>>>> --- a/include/qapi/error.h
>>>> +++ b/include/qapi/error.h
>>>> @@ -214,6 +214,9 @@
>>>>     *         }
>>>>     *         ...
>>>>     *     }
>>>> + *
>>>> + * For mass-conversion use script
>>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>>     */
>>>>      #ifndef ERROR_H
>>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>>> index 857f969aa1..047f1b9714 100644
>>>> --- a/MAINTAINERS
>>>> +++ b/MAINTAINERS
>>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>>    F: qapi/error.json
>>>>    F: util/error.c
>>>>    F: util/qemu-error.c
>>>> +F: scripts/coccinelle/*err*.cocci
>>>>      GDB stub
>>>>    M: Alex Bennée <alex.bennee@linaro.org>
>>>
> 
> 
>  From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
> From: Markus Armbruster <armbru@redhat.com>
> Date: Fri, 13 Mar 2020 14:27:57 +0100
> Subject: [PATCH] fixup! scripts: Coccinelle script to use
>   ERRP_AUTO_PROPAGATE()
> 
> ---
>   scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
>   1 file changed, 20 insertions(+), 17 deletions(-)
> 
> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
> index 7dac2dcfa4..43b0b0e63b 100644
> --- a/scripts/coccinelle/auto-propagated-errp.cocci
> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
> @@ -136,45 +136,48 @@ symbol errp;
>   
>   // Warn several Error * definitions.
>   @check1 disable optional_qualifier exists@
> -identifier fn = rule1.fn, local_err, local_err2;
> +identifier fn, _errp, local_err, local_err2;
> +position p1, p2;


Hmm, seems like I forget to define ____ as symbol in my patch

>   @@
>   
> - fn(..., Error ** ____, ...)
> + fn(..., Error **_errp, ...)

Ahmm.. it will break compilation?

Or, how will it work when _errp defined as meta variable is only in "+..." line? Should it be symbol instead, or just not defined?

>    {
>        ...
> -     Error *local_err = NULL;
> +     Error *local_err = NULL;@p1

Why to do -/+ here? Nothing changed..

>        ... when any
> -     Error *local_err2 = NULL;
> +     Error *local_err2 = NULL;@p2
>        ... when any
>    }
>   
>   @ script:python @
>   fn << check1.fn;
> +p1 << check1.p1;
> +p2 << check1.p2;
>   @@
>   
>   print('Warning: function {} has several definitions of '
> -      'Error * local variable'.format(fn))
> +      'Error * local variable: at {}:{} and then at {}:{}'.format(
> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>   
>   // Warn several propagations in control flow.
>   @check2 disable optional_qualifier exists@
> -identifier fn = rule1.fn;
> -symbol errp;
> +identifier fn, _errp;
>   position p1, p2;
>   @@
>   
> - fn(..., Error ** ____, ...)
> + fn(..., Error **_errp, ...)
>    {
>        ...
>   (
> -     error_propagate_prepend(errp, ...);@p1
> +     error_propagate_prepend(_errp, ...);@p1
>   |
> -     error_propagate(errp, ...);@p1
> +     error_propagate(_errp, ...);@p1
>   )
>        ...
>   (
> -     error_propagate_prepend(errp, ...);@p2
> +     error_propagate_prepend(_errp, ...);@p2
>   |
> -     error_propagate(errp, ...);@p2
> +     error_propagate(_errp, ...);@p2
>   )

You change some occurrences of errp to _errp, but not all. It breaks compilation.

>        ... when any
>    }
> @@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
>   // the same, just without error_propagate() call), coccinelle fails to
>   // match this "out: }".
>   @ disable optional_qualifier@
> -identifier rule1.fn, rule1.local_err, out;
> +identifier fn, rule1.local_err, out;

Hmm. If it improves performance it is strange.. But I can live with this change.

>   symbol errp;
>   @@
>   
> @@ -239,7 +242,7 @@ symbol errp;
>   //        *errp = NULL;
>   //    }
>   @ disable optional_qualifier exists@
> -identifier rule1.fn, rule1.local_err;
> +identifier fn, rule1.local_err;
>   expression list args;
>   symbol errp;
>   @@
> @@ -287,7 +290,7 @@ symbol errp;
>   // previous hunk, as this conflicts with other substitutions in it (at
>   // least with "- local_err = NULL").
>   @ disable optional_qualifier@
> -identifier rule1.fn, rule1.local_err;
> +identifier fn, rule1.local_err;
>   symbol errp;
>   @@
>   
> @@ -301,7 +304,7 @@ symbol errp;
>   
>   // Always use the same pattern for checking error
>   @ disable optional_qualifier@
> -identifier rule1.fn;
> +identifier fn;
>   symbol errp;
>   @@
>   
> @@ -315,7 +318,7 @@ symbol errp;
>   
>   // Revert temporary ___ identifier.
>   @ disable optional_qualifier@
> -identifier rule1.fn;
> +identifier fn;
>   @@
>   
>    fn(..., Error **
>
Markus Armbruster March 13, 2020, 9:54 p.m. UTC | #10
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 13.03.2020 18:42, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>
>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>> out now as is.
>>>>
>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>
>>>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>>>> does corresponding changes in code (look for details in
>>>>> include/qapi/error.h)
>>>>>
>>>>> Usage example:
>>>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>    --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>>>    --max-width 80 FILES...
>>>>>
>>>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>>>> ---
>>>>>
>>>>> Cc: Eric Blake <eblake@redhat.com>
>>>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>>>> Cc: Max Reitz <mreitz@redhat.com>
>>>>> Cc: Greg Kurz <groug@kaod.org>
>>>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>>>> Cc: Paul Durrant <paul@xen.org>
>>>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>>>> Cc: Markus Armbruster <armbru@redhat.com>
>>>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>>>> Cc: qemu-devel@nongnu.org
>>>>> Cc: qemu-block@nongnu.org
>>>>> Cc: xen-devel@lists.xenproject.org
>>>>>
>>>>>    scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>>>    include/qapi/error.h                          |   3 +
>>>>>    MAINTAINERS                                   |   1 +
>>>>>    3 files changed, 331 insertions(+)
>>>>>    create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>>>
>>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>> new file mode 100644
>>>>> index 0000000000..7dac2dcfa4
>>>>> --- /dev/null
>>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>> @@ -0,0 +1,327 @@
>>>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>>>> +//
>>>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>>>> +//
>>>>> +// This program is free software; you can redistribute it and/or
>>>>> +// modify it under the terms of the GNU General Public License as
>>>>> +// published by the Free Software Foundation; either version 2 of the
>>>>> +// License, or (at your option) any later version.
>>>>> +//
>>>>> +// This program is distributed in the hope that it will be useful,
>>>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>>>> +// GNU General Public License for more details.
>>>>> +//
>>>>> +// You should have received a copy of the GNU General Public License
>>>>> +// along with this program.  If not, see
>>>>> +// <http://www.gnu.org/licenses/>.
>>>>> +//
>>>>> +// Usage example:
>>>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>>>> +//  --no-show-diff --max-width 80 FILES...
>>>>> +//
>>>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>>>> +// than 80, and without this parameter coccinelle may reindent some
>>>>> +// lines which fit into 80 characters but not to coccinelle default,
>>>>> +// which in turn produces extra patch hunks for no reason.
>>>>
>>>> This is about unwanted reformatting of parameter lists due to the ___
>>>> chaining hack.  --max-width 80 makes that less likely, but not
>>>> impossible.
>>>>
>>>> We can search for unwanted reformatting of parameter lists.  I think
>>>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>>>> tree, I get one false positive (not a parameter list), and one hit:
>>>>
>>>>       @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>>>            }
>>>>        }
>>>>
>>>>       -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>>>       +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>>>       +                               Error **errp)
>>>>        {
>>>>       +    ERRP_AUTO_PROPAGATE();
>>>>            int i;
>>>>
>>>>            if (!props) {
>>>>
>>>> Reformatting, but not unwanted.
>>>
>>> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
>>> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.
>>
>> Agree.
>>
>>>>
>>>> The --max-width 80 hack is good enough for me.
>>>>
>>>> It does result in slightly long transformed lines, e.g. this one in
>>>> replication.c:
>>>>
>>>>       @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>>>                s->mode = REPLICATION_MODE_PRIMARY;
>>>>                top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>>>                if (top_id) {
>>>>       -            error_setg(&local_err, "The primary side does not support option top-id");
>>>>       +            error_setg(errp, "The primary side does not support option top-id");
>>>>                    goto fail;
>>>>                }
>>>>            } else if (!strcmp(mode, "secondary")) {
>>>>
>>>> v8 did break this line (that's how I found it).  However, v9 still
>>>> shortens the line, just not below the target.  All your + lines look
>>>> quite unlikely to lengthen lines.  Let's not worry about this.
>>>>
>>>>> +// Switch unusual Error ** parameter names to errp
>>>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>>>> +//
>>>>> +// Disable optional_qualifier to skip functions with
>>>>> +// "Error *const *errp" parameter.
>>>>> +//
>>>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>>>> +// that signals unusual semantics, and the parameter name may well
>>>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>>>> +//
>>>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>>>> +// error_propagate_prepend().
>>>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>>>> +identifier fn;
>>>>> +identifier _errp != errp;
>>>>> +@@
>>>>> +
>>>>> + fn(...,
>>>>> +-   Error **_errp
>>>>> ++   Error **errp
>>>>> +    ,...)
>>>>> + {
>>>>> +(
>>>>> +     ... when != assert(_errp && *_errp)
>>>>> +&
>>>>> +     <...
>>>>> +-    _errp
>>>>> ++    errp
>>>>> +     ...>
>>>>> +)
>>>>> + }
>>>>> +
>>>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>>>> +// necessary
>>>>> +//
>>>>> +// Note, that without "when any" the final "..." does not mach
>>>>> +// something matched by previous pattern, i.e. the rule will not match
>>>>> +// double error_prepend in control flow like in
>>>>> +// vfio_set_irq_signaling().
>>>>> +//
>>>>> +// Note, "exists" says that we want apply rule even if it matches not
>>>>> +// on all possible control flows (otherwise, it will not match
>>>>> +// standard pattern when error_propagate() call is in if branch).
>>>>> +@ disable optional_qualifier exists@
>>>>> +identifier fn, local_err;
>>>>> +symbol errp;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error **errp, ...)
>>>>> + {
>>>>> ++   ERRP_AUTO_PROPAGATE();
>>>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>>>> +(
>>>>> +(
>>>>> +    error_append_hint(errp, ...);
>>>>> +|
>>>>> +    error_prepend(errp, ...);
>>>>> +|
>>>>> +    error_vprepend(errp, ...);
>>>>> +)
>>>>> +    ... when any
>>>>> +|
>>>>> +    Error *local_err = NULL;
>>>>> +    ...
>>>>> +(
>>>>> +    error_propagate_prepend(errp, local_err, ...);
>>>>> +|
>>>>> +    error_propagate(errp, local_err);
>>>>> +)
>>>>> +    ...
>>>>> +)
>>>>> + }
>>>>> +
>>>>> +
>>>>> +// Match functions with propagation of local error to errp.
>>>>> +// We want to refer these functions in several following rules, but I
>>>>> +// don't know a proper way to inherit a function, not just its name
>>>>> +// (to not match another functions with same name in following rules).
>>>>> +// Not-proper way is as follows: rename errp parameter in functions
>>>>> +// header and match it in following rules. Rename it back after all
>>>>> +// transformations.
>>>>> +//
>>>>> +// The simplest case of propagation scheme is single definition of
>>>>> +// local_err with at most one error_propagate_prepend or
>>>>> +// error_propagate on each control-flow. Still, we want to match more
>>>>> +// complex schemes too. We'll warn them with help of further rules.
>>>>
>>>> I think what we actually want is to examine instances of this pattern to
>>>> figure out whether and how we want to transform them.  Perhaps:
>>>>
>>>>       // The common case is a single definition of local_err with at most one
>>>>       // error_propagate_prepend() or error_propagate() on each control-flow
>>>>       // path. Instances of this case we convert with this script. Functions
>>>
>>> For me, sounds a bit like "other things we don't convert".
>>> Actually we convert other things too.
>>
>> What other patterns of error propagation do we convert?
>
> Something like in xen_block_device_destroy, why not? Otherwise, it's better to avoid
> matching things like xen_block_device_destroy, not just warn them.
> But I'd prefer to proceed now as is to fit into 5.0.. Too much time already
> spent on this. So, I'm OK with your wording too.

Let's scratch "Instances of this case we convert with this script."

>>>>       // with multiple definitions or propagates we want to examine
>>>>       // manually. Later rules emit warnings to guide us to them.
>>>>
>>>>> +@rule1 disable optional_qualifier exists@
>>>>> +identifier fn, local_err;
>>>>> +symbol errp;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error **
>>>>> +-    errp
>>>>> ++    ____
>>>>> +    , ...)
>>>>> + {
>>>>> +     ...
>>>>> +     Error *local_err = NULL;
>>>>> +     ...
>>>>> +(
>>>>> +     error_propagate_prepend(errp, local_err, ...);
>>>>> +|
>>>>> +     error_propagate(errp, local_err);
>>>>> +)
>>>>> +     ...
>>>>> + }
>>>>> +
>>>>> +
>>>>> +// Warn several Error * definitions.
>>>>> +@check1 disable optional_qualifier exists@
>>>>> +identifier fn = rule1.fn, local_err, local_err2;
>>>>
>>>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>>>> particular reason for the difference?
>>>
>>> I didn't find other way to ref check1.fn in next python rule. It just don't
>>> work if I write here just rule1.fn.
>>>
>>>>
>>>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>>>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>>>> everywhere, then apply the script to the complete tree, I get the same
>>>> result.
>>>
>>> I think, it's more efficient to reuse names from previous rules. I think it should
>>> work faster (more information, less extra matching).
>>
>> Nope.  With my hacked up script (patch appended) Coccinelle is actually
>> *faster* for the .[ch] touched by this series: with your unmodified
>> script, it takes a bit over 12s on my box, with mine around 7s.  Output
>> is identical.
>>
>> Never guess performance, always measure it :)
>
> Hmm, whole tree results would be better proof
>
>>
>> Two notes on my script:
>>
>> * Unlike yours, it recognizes double-propagation in my test case.
>>    Discussed below.
>>
>> * Its "several definitions of" warning includes positions.  That turned
>>    out to be useless, but I've been too lazy to take that out again.
>>
>>>>
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error ** ____, ...)
>>>>> + {
>>>>> +     ...
>>>>> +     Error *local_err = NULL;
>>>>> +     ... when any
>>>>> +     Error *local_err2 = NULL;
>>>>> +     ... when any
>>>>> + }

This flags functions that have more than one declaration along any
control flow path.  It doesn't flag this one:

    void gnat(bool b, Error **errp)
    {
        if (b) {
            Error *local_err = NULL;
            foo(arg, &local_err);
            error_propagate(errp, local_err);
        } else {
            Error *local_err = NULL;
            bar(arg, &local_err);
            error_propagate(errp, local_err);
        }
    }

The Coccinelle script does the right thing for this one regardless.

I'd prefer to have such functions flagged, too.  But spending time on
convincing Coccinelle to do it for me is not worthwhile; I can simply
search the diff produced by Coccinelle for deletions of declarations
that are not indented exactly four spaces.

But if we keep this rule, we should adjust its comment

    // Warn several Error * definitions.

because it sure suggests it also catches functions like the one I gave
above.

>>>>> +
>>>>> +@ script:python @
>>>>> +fn << check1.fn;
>>>>> +@@
>>>>> +
>>>>> +print('Warning: function {} has several definitions of '
>>>>> +      'Error * local variable'.format(fn))
>>>>> +
>>>>> +// Warn several propagations in control flow.
>>>>> +@check2 disable optional_qualifier exists@
>>>>> +identifier fn = rule1.fn;
>>>>> +symbol errp;
>>>>> +position p1, p2;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error ** ____, ...)
>>>>> + {
>>>>> +     ...
>>>>> +(
>>>>> +     error_propagate_prepend(errp, ...);@p1
>>>>> +|
>>>>> +     error_propagate(errp, ...);@p1
>>>>> +)
>>>>> +     ...
>>>>> +(
>>>>> +     error_propagate_prepend(errp, ...);@p2
>>>>> +|
>>>>> +     error_propagate(errp, ...);@p2
>>>>> +)
>>>>> +     ... when any
>>>>> + }
>>>>> +
>>>>
>>>> Hmm, we don't catch the example I used in review of v8:
>>>>
>>>>       extern foo(int, Error **);
>>>>       extern bar(int, Error **);
>>>>
>>>>       void frob(Error **errp)
>>>>       {
>>>>           Error *local_err = NULL;
>>>>           int arg;
>>>>
>>>>           foo(arg, errp);
>>>>           bar(arg, &local_err);
>>>>           error_propagate(errp, local_err);
>>>>           bar(arg + 1, &local_err);
>>>>           error_propagate(errp, local_err);
>>>>       }
>>>>
>>>> I believe this is because rule1 does not match here.
>>>
>>> Yes, rule1 wants at least one code flow with non-doubled propagation.
>>>
>>>>
>>>> If I change the rule as follows, it catches the example:
>>>>
>>>>       @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>>>
>>>>        // Warn several propagations in control flow.
>>>>        @check2 disable optional_qualifier exists@
>>>>       -identifier fn = rule1.fn;
>>>>       -symbol errp;
>>>>       +identifier fn, _errp;
>>>>        position p1, p2;
>>>>        @@
>>>>
>>>>       - fn(..., Error ** ____, ...)
>>>>       + fn(..., Error **_errp, ...)
>>>>         {
>>>>             ...
>>>>        (
>>>>       -     error_propagate_prepend(errp, ...);@p1
>>>>       +     error_propagate_prepend(_errp, ...);@p1
>>>>        |
>>>>       -     error_propagate(errp, ...);@p1
>>>>       +     error_propagate(_errp, ...);@p1
>>>>        )
>>>>             ...
>>>>        (
>>>>       -     error_propagate_prepend(errp, ...);@p2
>>>>       +     error_propagate_prepend(_errp, ...);@p2
>>>>        |
>>>>       -     error_propagate(errp, ...);@p2
>>>>       +     error_propagate(_errp, ...);@p2
>>>>        )
>>>>             ... when any
>>>>         }
>>>>
>>>> To my mild surprise, it still doesn't find anything in our tree.
>>>>
>>>> Should we decouple the previous rule from rule1, too?  I tested the
>>>> following on the whole tree:
>>>
>>> I don't think so. Why to check what we are not going to convert? If we want
>>> to check side things, it's better to do it in other coccinelle script..
>>
>> Misunderstanding?  The rules are still chained together via the ___
>> hack, just not via function name, because that's unreliable and
>> redundant.
>
> Strange.. Then, how can it match something not matched by rule1?

I think I got confused when I wrote the "Misunderstanding?" paragraph.

Let me try again.

First rule check2.

The common case is a at most one propagation to @errp along any control
flow path.  We trust your Coccinelle script to convert that alright.

Any other propagation to @errp I want to review.  Whether the script
attempts a conversion or not is unimportant, as long as it points me to
the function to review.

Rule rule1 matches functions that propagate to @errp once along at least
one control flow path.

Unchained from rule rule1, rule check2 flags any function that
propagates to @errp multiple times along any control flow path.

Chained to rule1, it flags only functions that also have a path with
single propagation.

In other words, the unchained rule flags *all* multi-propagations to
@errp, while the chained rule flags only the ones the script attempts to
convert.  The former is much more useful to me.

Now rule check1.  It flags functions with multiple declarations along
any control flow path.  Again, chaining it to rule1 restricts it to the
functions we attempt to convert.  Makes it less useful to me.  However,
because my desire to review multiple declarations in function we don't
attempt to convert is lower than my desire to review multiple
propagations to @errp in such functions, chaining check1 is tolerable
for me.  But why chain check1 if we don't chain check2?

>
>>
>>>>
>>>>       @@ -136,10 +136,10 @@ symbol errp;
>>>>
>>>>        // Warn several Error * definitions.
>>>>        @check1 disable optional_qualifier exists@
>>>>       -identifier fn = rule1.fn, local_err, local_err2;
>>>>       +identifier fn, _errp, local_err, local_err2;
>>>>        @@
>>>>
>>>>       - fn(..., Error ** ____, ...)
>>>>       + fn(..., Error **_errp, ...)
>>>>         {
>>>>             ...
>>>>             Error *local_err = NULL;
>>>>
>>>> Warnings remain unchanged.
>>>>
>>>>> +@ script:python @
>>>>> +fn << check2.fn;
>>>>> +p1 << check2.p1;
>>>>> +p2 << check2.p2;
>>>>> +@@
>>>>> +
>>>>> +print('Warning: function {} propagates to errp several times in '
>>>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>> +
>>>>> +// Convert special case with goto separately.
>>>>> +// I tried merging this into the following rule the obvious way, but
>>>>> +// it made Coccinelle hang on block.c
>>>>> +//
>>>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>>>> +// "out: }" things later after all transformations (the rule will be
>>>>> +// the same, just without error_propagate() call), coccinelle fails to
>>>>> +// match this "out: }".
>>>>> +@ disable optional_qualifier@
>>>>> +identifier rule1.fn, rule1.local_err, out;
>>>>
>>>> As explained above, I doubt the need for rule1.fn.  We do need
>>>> rule1.local_err to avoid unwanted transformations.  More of the same
>>>> below.
>>>
>>> Logically, I want to inherit from rule1. So why not to stress it by inheriting
>>> fn variable? It's just a correct thing to do.
>>> And I hope it helps coccinelle to work more efficiently.
>>>
>>>>
>>>>> +symbol errp;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error ** ____, ...)
>>>>> + {
>>>>> +     <...
>>>>> +-    goto out;
>>>>> ++    return;
>>>>> +     ...>
>>>>> +- out:
>>>>> +-    error_propagate(errp, local_err);
>>>>> + }
>>>>> +
>>>>> +// Convert most of local_err related stuff.
>>>>> +//
>>>>> +// Note, that we update everything related to matched by rule1
>>>>> +// function name and local_err name. We may match something not
>>>>> +// related to the pattern matched by rule1. For example, local_err may
>>>>> +// be defined with the same name in different blocks inside one
>>>>> +// function, and in one block follow the propagation pattern and in
>>>>> +// other block doesn't. Or we may have several functions with the same
>>>>> +// name (for different configurations).
>>>>> +//
>>>>> +// Note also that errp-cleaning functions
>>>>> +//   error_free_errp
>>>>> +//   error_report_errp
>>>>> +//   error_reportf_errp
>>>>> +//   warn_report_errp
>>>>> +//   warn_reportf_errp
>>>>> +// are not yet implemented. They must call corresponding Error* -
>>>>> +// freeing function and then set *errp to NULL, to avoid further
>>>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>>>> +// For example, error_free_errp may look like this:
>>>>> +//
>>>>> +//    void error_free_errp(Error **errp)
>>>>> +//    {
>>>>> +//        error_free(*errp);
>>>>> +//        *errp = NULL;
>>>>> +//    }
>>>>> +@ disable optional_qualifier exists@
>>>>> +identifier rule1.fn, rule1.local_err;
>>>>> +expression list args;
>>>>> +symbol errp;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error ** ____, ...)
>>>>> + {
>>>>> +     <...
>>>>> +(
>>>>> +-    Error *local_err = NULL;
>>>>> +|
>>>>> +
>>>>> +// Convert error clearing functions
>>>>> +(
>>>>> +-    error_free(local_err);
>>>>> ++    error_free_errp(errp);
>>>>> +|
>>>>> +-    error_report_err(local_err);
>>>>> ++    error_report_errp(errp);
>>>>> +|
>>>>> +-    error_reportf_err(local_err, args);
>>>>> ++    error_reportf_errp(errp, args);
>>>>> +|
>>>>> +-    warn_report_err(local_err);
>>>>> ++    warn_report_errp(errp);
>>>>> +|
>>>>> +-    warn_reportf_err(local_err, args);
>>>>> ++    warn_reportf_errp(errp, args);
>>>>> +)
>>>>> +?-    local_err = NULL;
>>>>> +
>>>>> +|
>>>>> +-    error_propagate_prepend(errp, local_err, args);
>>>>> ++    error_prepend(errp, args);
>>>>> +|
>>>>> +-    error_propagate(errp, local_err);
>>>>> +|
>>>>> +-    &local_err
>>>>> ++    errp
>>>>> +)
>>>>> +     ...>
>>>>> + }
>>>>> +
>>>>> +// Convert remaining local_err usage. For example, different kinds of
>>>>> +// error checking in if conditionals. We can't merge this into
>>>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>>>> +// least with "- local_err = NULL").
>>>>> +@ disable optional_qualifier@
>>>>> +identifier rule1.fn, rule1.local_err;
>>>>> +symbol errp;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error ** ____, ...)
>>>>> + {
>>>>> +     <...
>>>>> +-    local_err
>>>>> ++    *errp
>>>>> +     ...>
>>>>> + }
>>>>> +
>>>>> +// Always use the same pattern for checking error
>>>>> +@ disable optional_qualifier@
>>>>> +identifier rule1.fn;
>>>>> +symbol errp;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error ** ____, ...)
>>>>> + {
>>>>> +     <...
>>>>> +-    *errp != NULL
>>>>> ++    *errp
>>>>> +     ...>
>>>>> + }
>>>>> +
>>>>> +// Revert temporary ___ identifier.
>>>>> +@ disable optional_qualifier@
>>>>> +identifier rule1.fn;
>>>>> +@@
>>>>> +
>>>>> + fn(..., Error **
>>>>> +-   ____
>>>>> ++   errp
>>>>> +    , ...)
>>>>> + {
>>>>> +     ...
>>>>> + }
>>>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>>>> index 30140d9bfe..56c133520d 100644
>>>>> --- a/include/qapi/error.h
>>>>> +++ b/include/qapi/error.h
>>>>> @@ -214,6 +214,9 @@
>>>>>     *         }
>>>>>     *         ...
>>>>>     *     }
>>>>> + *
>>>>> + * For mass-conversion use script
>>>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>>>     */
>>>>>      #ifndef ERROR_H
>>>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>>>> index 857f969aa1..047f1b9714 100644
>>>>> --- a/MAINTAINERS
>>>>> +++ b/MAINTAINERS
>>>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>>>    F: qapi/error.json
>>>>>    F: util/error.c
>>>>>    F: util/qemu-error.c
>>>>> +F: scripts/coccinelle/*err*.cocci
>>>>>      GDB stub
>>>>>    M: Alex Bennée <alex.bennee@linaro.org>
>>>>
>>
>>
>>  From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
>> From: Markus Armbruster <armbru@redhat.com>
>> Date: Fri, 13 Mar 2020 14:27:57 +0100
>> Subject: [PATCH] fixup! scripts: Coccinelle script to use
>>   ERRP_AUTO_PROPAGATE()
>>
>> ---
>>   scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
>>   1 file changed, 20 insertions(+), 17 deletions(-)
>>
>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>> index 7dac2dcfa4..43b0b0e63b 100644
>> --- a/scripts/coccinelle/auto-propagated-errp.cocci
>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>> @@ -136,45 +136,48 @@ symbol errp;
>>     // Warn several Error * definitions.
>>   @check1 disable optional_qualifier exists@
>> -identifier fn = rule1.fn, local_err, local_err2;
>> +identifier fn, _errp, local_err, local_err2;
>> +position p1, p2;
>
>
> Hmm, seems like I forget to define ____ as symbol in my patch

Coccinelle defaults to symbol.

>>   @@
>>   - fn(..., Error ** ____, ...)
>> + fn(..., Error **_errp, ...)
>
> Ahmm.. it will break compilation?
>
> Or, how will it work when _errp defined as meta variable is only in "+..." line? Should it be symbol instead, or just not defined?

Misunderstanding?  It's a diff between your .cocci and mine.  My version
is

    // Warn several Error * definitions.
    @check1 disable optional_qualifier exists@
    identifier fn, _errp, local_err, local_err2;
    position p1, p2;
    @@

     fn(..., Error **_errp, ...)
     {
         ...
         Error *local_err = NULL;@p1
         ... when any
         Error *local_err2 = NULL;@p2
         ... when any
     }

    @ script:python @
    fn << check1.fn;
    p1 << check1.p1;
    p2 << check1.p2;
    @@

>>    {
>>        ...
>> -     Error *local_err = NULL;
>> +     Error *local_err = NULL;@p1
>
> Why to do -/+ here? Nothing changed..
>
>>        ... when any
>> -     Error *local_err2 = NULL;
>> +     Error *local_err2 = NULL;@p2
>>        ... when any
>>    }
>>     @ script:python @
>>   fn << check1.fn;
>> +p1 << check1.p1;
>> +p2 << check1.p2;
>>   @@
>>     print('Warning: function {} has several definitions of '
>> -      'Error * local variable'.format(fn))
>> +      'Error * local variable: at {}:{} and then at {}:{}'.format(
>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>     // Warn several propagations in control flow.
>>   @check2 disable optional_qualifier exists@
>> -identifier fn = rule1.fn;
>> -symbol errp;
>> +identifier fn, _errp;
>>   position p1, p2;
>>   @@
>>   - fn(..., Error ** ____, ...)
>> + fn(..., Error **_errp, ...)
>>    {
>>        ...
>>   (
>> -     error_propagate_prepend(errp, ...);@p1
>> +     error_propagate_prepend(_errp, ...);@p1
>>   |
>> -     error_propagate(errp, ...);@p1
>> +     error_propagate(_errp, ...);@p1
>>   )
>>        ...
>>   (
>> -     error_propagate_prepend(errp, ...);@p2
>> +     error_propagate_prepend(_errp, ...);@p2
>>   |
>> -     error_propagate(errp, ...);@p2
>> +     error_propagate(_errp, ...);@p2
>>   )
>
> You change some occurrences of errp to _errp, but not all. It breaks compilation.
>
>>        ... when any
>>    }
>> @@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
>>   // the same, just without error_propagate() call), coccinelle fails to
>>   // match this "out: }".
>>   @ disable optional_qualifier@
>> -identifier rule1.fn, rule1.local_err, out;
>> +identifier fn, rule1.local_err, out;
>
> Hmm. If it improves performance it is strange.. But I can live with this change.
>
>>   symbol errp;
>>   @@
>>   @@ -239,7 +242,7 @@ symbol errp;
>>   //        *errp = NULL;
>>   //    }
>>   @ disable optional_qualifier exists@
>> -identifier rule1.fn, rule1.local_err;
>> +identifier fn, rule1.local_err;
>>   expression list args;
>>   symbol errp;
>>   @@
>> @@ -287,7 +290,7 @@ symbol errp;
>>   // previous hunk, as this conflicts with other substitutions in it (at
>>   // least with "- local_err = NULL").
>>   @ disable optional_qualifier@
>> -identifier rule1.fn, rule1.local_err;
>> +identifier fn, rule1.local_err;
>>   symbol errp;
>>   @@
>>   @@ -301,7 +304,7 @@ symbol errp;
>>     // Always use the same pattern for checking error
>>   @ disable optional_qualifier@
>> -identifier rule1.fn;
>> +identifier fn;
>>   symbol errp;
>>   @@
>>   @@ -315,7 +318,7 @@ symbol errp;
>>     // Revert temporary ___ identifier.
>>   @ disable optional_qualifier@
>> -identifier rule1.fn;
>> +identifier fn;
>>   @@
>>      fn(..., Error **
>>

I append my hacked up version of auto-propagated-errp.cocci.  It
produces the same patch as yours for the complete tree.



// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
//
// Copyright (c) 2020 Virtuozzo International GmbH.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see
// <http://www.gnu.org/licenses/>.
//
// Usage example:
// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
//  --macro-file scripts/cocci-macro-file.h --in-place \
//  --no-show-diff --max-width 80 FILES...
//
// Note: --max-width 80 is needed because coccinelle default is less
// than 80, and without this parameter coccinelle may reindent some
// lines which fit into 80 characters but not to coccinelle default,
// which in turn produces extra patch hunks for no reason.

// Switch unusual Error ** parameter names to errp
// (this is necessary to use ERRP_AUTO_PROPAGATE).
//
// Disable optional_qualifier to skip functions with
// "Error *const *errp" parameter.
//
// Skip functions with "assert(_errp && *_errp)" statement, because
// that signals unusual semantics, and the parameter name may well
// serve a purpose. (like nbd_iter_channel_error()).
//
// Skip util/error.c to not touch, for example, error_propagate() and
// error_propagate_prepend().
@ depends on !(file in "util/error.c") disable optional_qualifier@
identifier fn;
identifier _errp != errp;
@@

 fn(...,
-   Error **_errp
+   Error **errp
    ,...)
 {
(
     ... when != assert(_errp && *_errp)
&
     <...
-    _errp
+    errp
     ...>
)
 }

// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
// necessary
//
// Note, that without "when any" the final "..." does not mach
// something matched by previous pattern, i.e. the rule will not match
// double error_prepend in control flow like in
// vfio_set_irq_signaling().
//
// Note, "exists" says that we want apply rule even if it matches not
// on all possible control flows (otherwise, it will not match
// standard pattern when error_propagate() call is in if branch).
@ disable optional_qualifier exists@
identifier fn, local_err;
symbol errp;
@@

 fn(..., Error **errp, ...)
 {
+   ERRP_AUTO_PROPAGATE();
    ...  when != ERRP_AUTO_PROPAGATE();
(
(
    error_append_hint(errp, ...);
|
    error_prepend(errp, ...);
|
    error_vprepend(errp, ...);
)
    ... when any
|
    Error *local_err = NULL;
    ...
(
    error_propagate_prepend(errp, local_err, ...);
|
    error_propagate(errp, local_err);
)
    ...
)
 }


// Match functions with propagation of local error to errp.
// We want to refer these functions in several following rules, but I
// don't know a proper way to inherit a function, not just its name
// (to not match another functions with same name in following rules).
// Not-proper way is as follows: rename errp parameter in functions
// header and match it in following rules. Rename it back after all
// transformations.
//
// The simplest case of propagation scheme is single definition of
// local_err with at most one error_propagate_prepend or
// error_propagate on each control-flow. Still, we want to match more
// complex schemes too. We'll warn them with help of further rules.
@rule1 disable optional_qualifier exists@
identifier fn, local_err;
symbol errp;
@@

 fn(..., Error **
-    errp
+    ____
    , ...)
 {
     ...
     Error *local_err = NULL;
     ...
(
     error_propagate_prepend(errp, local_err, ...);
|
     error_propagate(errp, local_err);
)
     ...
 }


// Warn several Error * definitions.
@check1 disable optional_qualifier exists@
identifier fn, _errp, local_err, local_err2;
position p1, p2;
@@

 fn(..., Error **_errp, ...)
 {
     ...
     Error *local_err = NULL;@p1
     ... when any
     Error *local_err2 = NULL;@p2
     ... when any
 }

@ script:python @
fn << check1.fn;
p1 << check1.p1;
p2 << check1.p2;
@@

print('Warning: function {} has several definitions of '
      'Error * local variable: at {}:{} and then at {}:{}'.format(
          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))

// Warn several propagations in control flow.
@check2 disable optional_qualifier exists@
identifier fn, _errp;
position p1, p2;
@@

 fn(..., Error **_errp, ...)
 {
     ...
(
     error_propagate_prepend(_errp, ...);@p1
|
     error_propagate(_errp, ...);@p1
)
     ...
(
     error_propagate_prepend(_errp, ...);@p2
|
     error_propagate(_errp, ...);@p2
)
     ... when any
 }

@ script:python @
fn << check2.fn;
p1 << check2.p1;
p2 << check2.p2;
@@

print('Warning: function {} propagates to errp several times in '
      'one control flow: at {}:{} and then at {}:{}'.format(
          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))

// Convert special case with goto separately.
// I tried merging this into the following rule the obvious way, but
// it made Coccinelle hang on block.c
//
// Note interesting thing: if we don't do it here, and try to fixup
// "out: }" things later after all transformations (the rule will be
// the same, just without error_propagate() call), coccinelle fails to
// match this "out: }".
@ disable optional_qualifier@
identifier fn, rule1.local_err, out;
symbol errp;
@@

 fn(..., Error ** ____, ...)
 {
     <...
-    goto out;
+    return;
     ...>
- out:
-    error_propagate(errp, local_err);
 }

// Convert most of local_err related stuff.
//
// Note, that we update everything related to matched by rule1
// function name and local_err name. We may match something not
// related to the pattern matched by rule1. For example, local_err may
// be defined with the same name in different blocks inside one
// function, and in one block follow the propagation pattern and in
// other block doesn't. Or we may have several functions with the same
// name (for different configurations).
//
// Note also that errp-cleaning functions
//   error_free_errp
//   error_report_errp
//   error_reportf_errp
//   warn_report_errp
//   warn_reportf_errp
// are not yet implemented. They must call corresponding Error* -
// freeing function and then set *errp to NULL, to avoid further
// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
// For example, error_free_errp may look like this:
//
//    void error_free_errp(Error **errp)
//    {
//        error_free(*errp);
//        *errp = NULL;
//    }
@ disable optional_qualifier exists@
identifier fn, rule1.local_err;
expression list args;
symbol errp;
@@

 fn(..., Error ** ____, ...)
 {
     <...
(
-    Error *local_err = NULL;
|

// Convert error clearing functions
(
-    error_free(local_err);
+    error_free_errp(errp);
|
-    error_report_err(local_err);
+    error_report_errp(errp);
|
-    error_reportf_err(local_err, args);
+    error_reportf_errp(errp, args);
|
-    warn_report_err(local_err);
+    warn_report_errp(errp);
|
-    warn_reportf_err(local_err, args);
+    warn_reportf_errp(errp, args);
)
?-    local_err = NULL;

|
-    error_propagate_prepend(errp, local_err, args);
+    error_prepend(errp, args);
|
-    error_propagate(errp, local_err);
|
-    &local_err
+    errp
)
     ...>
 }

// Convert remaining local_err usage. For example, different kinds of
// error checking in if conditionals. We can't merge this into
// previous hunk, as this conflicts with other substitutions in it (at
// least with "- local_err = NULL").
@ disable optional_qualifier@
identifier fn, rule1.local_err;
symbol errp;
@@

 fn(..., Error ** ____, ...)
 {
     <...
-    local_err
+    *errp
     ...>
 }

// Always use the same pattern for checking error
@ disable optional_qualifier@
identifier fn;
symbol errp;
@@

 fn(..., Error ** ____, ...)
 {
     <...
-    *errp != NULL
+    *errp
     ...>
 }

// Revert temporary ___ identifier.
@ disable optional_qualifier@
identifier fn;
@@

 fn(..., Error **
-   ____
+   errp
    , ...)
 {
     ...
 }
Eric Blake March 13, 2020, 10:12 p.m. UTC | #11
On 3/13/20 4:54 PM, Markus Armbruster wrote:

> 
> I append my hacked up version of auto-propagated-errp.cocci.  It
> produces the same patch as yours for the complete tree.
> 
> 
> 
> // Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
> //

> //
> // Usage example:
> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
> //  --macro-file scripts/cocci-macro-file.h --in-place \
> //  --no-show-diff --max-width 80 FILES...
> //
> // Note: --max-width 80 is needed because coccinelle default is less
> // than 80, and without this parameter coccinelle may reindent some
> // lines which fit into 80 characters but not to coccinelle default,
> // which in turn produces extra patch hunks for no reason.

Do we really need this note?  And/or should we update other Coccinelle 
script examples to mention --max-width?

> 
> // Switch unusual Error ** parameter names to errp
> // (this is necessary to use ERRP_AUTO_PROPAGATE).
> //
> // Disable optional_qualifier to skip functions with
> // "Error *const *errp" parameter.
> //
> // Skip functions with "assert(_errp && *_errp)" statement, because
> // that signals unusual semantics, and the parameter name may well
> // serve a purpose. (like nbd_iter_channel_error()).
> //
> // Skip util/error.c to not touch, for example, error_propagate() and
> // error_propagate_prepend().
> @ depends on !(file in "util/error.c") disable optional_qualifier@

The comments are definitely helpful.

> identifier fn;
> identifier _errp != errp;
> @@
> 
>   fn(...,
> -   Error **_errp
> +   Error **errp
>      ,...)
>   {
> (
>       ... when != assert(_errp && *_errp)
> &
>       <...
> -    _errp
> +    errp
>       ...>
> )
>   }
> 
> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
> // necessary
> //
> // Note, that without "when any" the final "..." does not mach
> // something matched by previous pattern, i.e. the rule will not match
> // double error_prepend in control flow like in
> // vfio_set_irq_signaling().

How likely are we that this comment might go stale over time?  But I'm 
not opposed to it.

> //
> // Note, "exists" says that we want apply rule even if it matches not
> // on all possible control flows (otherwise, it will not match

s/matches not on/does not match on/

> // standard pattern when error_propagate() call is in if branch).
> @ disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
> 
>   fn(..., Error **errp, ...)
>   {
> +   ERRP_AUTO_PROPAGATE();
>      ...  when != ERRP_AUTO_PROPAGATE();
> (
> (
>      error_append_hint(errp, ...);
> |
>      error_prepend(errp, ...);
> |
>      error_vprepend(errp, ...);
> )
>      ... when any
> |
>      Error *local_err = NULL;
>      ...
> (
>      error_propagate_prepend(errp, local_err, ...);
> |
>      error_propagate(errp, local_err);
> )
>      ...
> )
>   }
> 
> 
> // Match functions with propagation of local error to errp.
> // We want to refer these functions in several following rules, but I
> // don't know a proper way to inherit a function, not just its name
> // (to not match another functions with same name in following rules).
> // Not-proper way is as follows: rename errp parameter in functions
> // header and match it in following rules. Rename it back after all
> // transformations.
> //
> // The simplest case of propagation scheme is single definition of
> // local_err with at most one error_propagate_prepend or
> // error_propagate on each control-flow. Still, we want to match more
> // complex schemes too. We'll warn them with help of further rules.

We'll warn for those with the help of further rules.

> @rule1 disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
> 
>   fn(..., Error **
> -    errp
> +    ____
>      , ...)
>   {
>       ...
>       Error *local_err = NULL;
>       ...
> (
>       error_propagate_prepend(errp, local_err, ...);
> |
>       error_propagate(errp, local_err);
> )
>       ...
>   }
> 
> 
> // Warn several Error * definitions.

// Warn when there are several Error * definitions.


> @check1 disable optional_qualifier exists@
> identifier fn, _errp, local_err, local_err2;
> position p1, p2;
> @@
> 
>   fn(..., Error **_errp, ...)
>   {
>       ...
>       Error *local_err = NULL;@p1
>       ... when any
>       Error *local_err2 = NULL;@p2
>       ... when any
>   }
> 
> @ script:python @
> fn << check1.fn;
> p1 << check1.p1;
> p2 << check1.p2;
> @@
> 
> print('Warning: function {} has several definitions of '
>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> 
> // Warn several propagations in control flow.

// Warn when several propagations are in the control flow.

> @check2 disable optional_qualifier exists@
> identifier fn, _errp;
> position p1, p2;
> @@
> 
>   fn(..., Error **_errp, ...)
>   {
>       ...
> (
>       error_propagate_prepend(_errp, ...);@p1
> |
>       error_propagate(_errp, ...);@p1
> )
>       ...
> (
>       error_propagate_prepend(_errp, ...);@p2
> |
>       error_propagate(_errp, ...);@p2
> )
>       ... when any
>   }
> 
> @ script:python @
> fn << check2.fn;
> p1 << check2.p1;
> p2 << check2.p2;
> @@
> 
> print('Warning: function {} propagates to errp several times in '
>        'one control flow: at {}:{} and then at {}:{}'.format(
>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> 
> // Convert special case with goto separately.
> // I tried merging this into the following rule the obvious way, but
> // it made Coccinelle hang on block.c
> //
> // Note interesting thing: if we don't do it here, and try to fixup
> // "out: }" things later after all transformations (the rule will be
> // the same, just without error_propagate() call), coccinelle fails to
> // match this "out: }".
> @ disable optional_qualifier@
> identifier fn, rule1.local_err, out;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    goto out;
> +    return;
>       ...>
> - out:
> -    error_propagate(errp, local_err);
>   }
> 
> // Convert most of local_err related stuff.
> //
> // Note, that we update everything related to matched by rule1

either 'related to' or 'matched by', but not both.

> // function name and local_err name. We may match something not
> // related to the pattern matched by rule1. For example, local_err may
> // be defined with the same name in different blocks inside one
> // function, and in one block follow the propagation pattern and in
> // other block doesn't. Or we may have several functions with the same
> // name (for different configurations).
> //
> // Note also that errp-cleaning functions
> //   error_free_errp
> //   error_report_errp
> //   error_reportf_errp
> //   warn_report_errp
> //   warn_reportf_errp
> // are not yet implemented. They must call corresponding Error* -
> // freeing function and then set *errp to NULL, to avoid further
> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).

Do we need this part of the patch if we aren't using it?  Or can it be 
added incrementally later when we actually do have those functions added?

> // For example, error_free_errp may look like this:
> //
> //    void error_free_errp(Error **errp)
> //    {
> //        error_free(*errp);
> //        *errp = NULL;
> //    }
> @ disable optional_qualifier exists@
> identifier fn, rule1.local_err;
> expression list args;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> (
> -    Error *local_err = NULL;
> |
> 
> // Convert error clearing functions
> (
> -    error_free(local_err);
> +    error_free_errp(errp);
> |
> -    error_report_err(local_err);
> +    error_report_errp(errp);
> |
> -    error_reportf_err(local_err, args);
> +    error_reportf_errp(errp, args);
> |
> -    warn_report_err(local_err);
> +    warn_report_errp(errp);
> |
> -    warn_reportf_err(local_err, args);
> +    warn_reportf_errp(errp, args);
> )
> ?-    local_err = NULL;
> 
> |
> -    error_propagate_prepend(errp, local_err, args);
> +    error_prepend(errp, args);
> |
> -    error_propagate(errp, local_err);
> |
> -    &local_err
> +    errp
> )
>       ...>
>   }
> 
> // Convert remaining local_err usage. For example, different kinds of
> // error checking in if conditionals. We can't merge this into
> // previous hunk, as this conflicts with other substitutions in it (at
> // least with "- local_err = NULL").
> @ disable optional_qualifier@
> identifier fn, rule1.local_err;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    local_err
> +    *errp
>       ...>
>   }
> 
> // Always use the same pattern for checking error
> @ disable optional_qualifier@
> identifier fn;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    *errp != NULL
> +    *errp
>       ...>
>   }
> 
> // Revert temporary ___ identifier.
> @ disable optional_qualifier@
> identifier fn;
> @@
> 
>   fn(..., Error **
> -   ____
> +   errp
>      , ...)
>   {
>       ...
>   }
> 
> 

Ultimately, the proof is in the pudding - if we are happy with the 
conversion and the warnings produced by this script, and the amount of 
manual touchup to address those warnings, then I'm happy to accept the 
script even if I didn't fully check what it does (here, I'm trusting 
what Vladimir and Markus have been doing in their back-and-forth 
refinements of the script).
Markus Armbruster March 15, 2020, 4:38 p.m. UTC | #12
Eric Blake <eblake@redhat.com> writes:

> On 3/13/20 4:54 PM, Markus Armbruster wrote:
>
>>
>> I append my hacked up version of auto-propagated-errp.cocci.  It
>> produces the same patch as yours for the complete tree.
>>
>>
>>
>> // Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>> //
>
>> //
>> // Usage example:
>> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>> //  --macro-file scripts/cocci-macro-file.h --in-place \
>> //  --no-show-diff --max-width 80 FILES...
>> //
>> // Note: --max-width 80 is needed because coccinelle default is less
>> // than 80, and without this parameter coccinelle may reindent some
>> // lines which fit into 80 characters but not to coccinelle default,
>> // which in turn produces extra patch hunks for no reason.
>
> Do we really need this note?  And/or should we update other Coccinelle
> script examples to mention --max-width?

What makes this Coccinelle script special is its rule chaining hack.  We
want to transform certain functions by applying a sequence of rules.  We
want to chain these rules together, i.e. have subsequent rules match
only where the first rule matches.  We do this by renaming the Error
**errp parameter to ___ in the first rule, and back to errp in the last
rule.  The two renames cancel out, but of course Coccinelle doesn't
special-case that, but does what it always does when it touches long
lines: it wraps them.  This leads to unwanted patch hunks wrapping
formal parameter lists.

Increasing Coccinelle's line width limit just a bit gets rid of almost
all of them.

>> // Switch unusual Error ** parameter names to errp
>> // (this is necessary to use ERRP_AUTO_PROPAGATE).
>> //
>> // Disable optional_qualifier to skip functions with
>> // "Error *const *errp" parameter.
>> //
>> // Skip functions with "assert(_errp && *_errp)" statement, because
>> // that signals unusual semantics, and the parameter name may well
>> // serve a purpose. (like nbd_iter_channel_error()).
>> //
>> // Skip util/error.c to not touch, for example, error_propagate() and
>> // error_propagate_prepend().
>> @ depends on !(file in "util/error.c") disable optional_qualifier@
>
> The comments are definitely helpful.

Oh boy, they are!

>> identifier fn;
>> identifier _errp != errp;
>> @@
>>
>>   fn(...,
>> -   Error **_errp
>> +   Error **errp
>>      ,...)
>>   {
>> (
>>       ... when != assert(_errp && *_errp)
>> &
>>       <...
>> -    _errp
>> +    errp
>>       ...>
>> )
>>   }
>>
>> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>> // necessary
>> //
>> // Note, that without "when any" the final "..." does not mach
>> // something matched by previous pattern, i.e. the rule will not match
>> // double error_prepend in control flow like in
>> // vfio_set_irq_signaling().
>
> How likely are we that this comment might go stale over time?  But I'm
> not opposed to it.

My plan is to complete the conversion in 5.1.  The script should become
uninteresting soon after.  Comments that risk going stale don't bother
me.

>> //
>> // Note, "exists" says that we want apply rule even if it matches not
>> // on all possible control flows (otherwise, it will not match
>
> s/matches not on/does not match on/
>
>> // standard pattern when error_propagate() call is in if branch).
>> @ disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **errp, ...)
>>   {
>> +   ERRP_AUTO_PROPAGATE();
>>      ...  when != ERRP_AUTO_PROPAGATE();
>> (
>> (
>>      error_append_hint(errp, ...);
>> |
>>      error_prepend(errp, ...);
>> |
>>      error_vprepend(errp, ...);
>> )
>>      ... when any
>> |
>>      Error *local_err = NULL;
>>      ...
>> (
>>      error_propagate_prepend(errp, local_err, ...);
>> |
>>      error_propagate(errp, local_err);
>> )
>>      ...
>> )
>>   }
>>
>>
>> // Match functions with propagation of local error to errp.
>> // We want to refer these functions in several following rules, but I
>> // don't know a proper way to inherit a function, not just its name
>> // (to not match another functions with same name in following rules).
>> // Not-proper way is as follows: rename errp parameter in functions
>> // header and match it in following rules. Rename it back after all
>> // transformations.
>> //
>> // The simplest case of propagation scheme is single definition of
>> // local_err with at most one error_propagate_prepend or
>> // error_propagate on each control-flow. Still, we want to match more
>> // complex schemes too. We'll warn them with help of further rules.
>
> We'll warn for those with the help of further rules.
>
>> @rule1 disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **
>> -    errp
>> +    ____
>>      , ...)
>>   {
>>       ...
>>       Error *local_err = NULL;
>>       ...
>> (
>>       error_propagate_prepend(errp, local_err, ...);
>> |
>>       error_propagate(errp, local_err);
>> )
>>       ...
>>   }
>>
>>
>> // Warn several Error * definitions.
>
> // Warn when there are several Error * definitions.
>
>
>> @check1 disable optional_qualifier exists@
>> identifier fn, _errp, local_err, local_err2;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>>       Error *local_err = NULL;@p1
>>       ... when any
>>       Error *local_err2 = NULL;@p2
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check1.fn;
>> p1 << check1.p1;
>> p2 << check1.p2;
>> @@
>>
>> print('Warning: function {} has several definitions of '
>>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Warn several propagations in control flow.
>
> // Warn when several propagations are in the control flow.
>
>> @check2 disable optional_qualifier exists@
>> identifier fn, _errp;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>> (
>>       error_propagate_prepend(_errp, ...);@p1
>> |
>>       error_propagate(_errp, ...);@p1
>> )
>>       ...
>> (
>>       error_propagate_prepend(_errp, ...);@p2
>> |
>>       error_propagate(_errp, ...);@p2
>> )
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check2.fn;
>> p1 << check2.p1;
>> p2 << check2.p2;
>> @@
>>
>> print('Warning: function {} propagates to errp several times in '
>>        'one control flow: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Convert special case with goto separately.
>> // I tried merging this into the following rule the obvious way, but
>> // it made Coccinelle hang on block.c
>> //
>> // Note interesting thing: if we don't do it here, and try to fixup
>> // "out: }" things later after all transformations (the rule will be
>> // the same, just without error_propagate() call), coccinelle fails to
>> // match this "out: }".
>> @ disable optional_qualifier@
>> identifier fn, rule1.local_err, out;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    goto out;
>> +    return;
>>       ...>
>> - out:
>> -    error_propagate(errp, local_err);
>>   }
>>
>> // Convert most of local_err related stuff.
>> //
>> // Note, that we update everything related to matched by rule1
>
> either 'related to' or 'matched by', but not both.
>
>> // function name and local_err name. We may match something not
>> // related to the pattern matched by rule1. For example, local_err may
>> // be defined with the same name in different blocks inside one
>> // function, and in one block follow the propagation pattern and in
>> // other block doesn't. Or we may have several functions with the same
>> // name (for different configurations).
>> //
>> // Note also that errp-cleaning functions
>> //   error_free_errp
>> //   error_report_errp
>> //   error_reportf_errp
>> //   warn_report_errp
>> //   warn_reportf_errp
>> // are not yet implemented. They must call corresponding Error* -
>> // freeing function and then set *errp to NULL, to avoid further
>> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>
> Do we need this part of the patch if we aren't using it?  Or can it be
> added incrementally later when we actually do have those functions
> added?

When I asked a similar question, Vladimir pointed out that transforming
these functions is required for correctness.

If we keep the rule and add the functions only when it's used, the
compiler will tell us when it's used.

If we add the rule only when we believe it's used, we risk silent
incorrect transformations.

>> // For example, error_free_errp may look like this:
>> //
>> //    void error_free_errp(Error **errp)
>> //    {
>> //        error_free(*errp);
>> //        *errp = NULL;
>> //    }
>> @ disable optional_qualifier exists@
>> identifier fn, rule1.local_err;
>> expression list args;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> (
>> -    Error *local_err = NULL;
>> |
>>
>> // Convert error clearing functions
>> (
>> -    error_free(local_err);
>> +    error_free_errp(errp);
>> |
>> -    error_report_err(local_err);
>> +    error_report_errp(errp);
>> |
>> -    error_reportf_err(local_err, args);
>> +    error_reportf_errp(errp, args);
>> |
>> -    warn_report_err(local_err);
>> +    warn_report_errp(errp);
>> |
>> -    warn_reportf_err(local_err, args);
>> +    warn_reportf_errp(errp, args);
>> )
>> ?-    local_err = NULL;
>>
>> |
>> -    error_propagate_prepend(errp, local_err, args);
>> +    error_prepend(errp, args);
>> |
>> -    error_propagate(errp, local_err);
>> |
>> -    &local_err
>> +    errp
>> )
>>       ...>
>>   }
>>
>> // Convert remaining local_err usage. For example, different kinds of
>> // error checking in if conditionals. We can't merge this into
>> // previous hunk, as this conflicts with other substitutions in it (at
>> // least with "- local_err = NULL").
>> @ disable optional_qualifier@
>> identifier fn, rule1.local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    local_err
>> +    *errp
>>       ...>
>>   }
>>
>> // Always use the same pattern for checking error
>> @ disable optional_qualifier@
>> identifier fn;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    *errp != NULL
>> +    *errp
>>       ...>
>>   }
>>
>> // Revert temporary ___ identifier.
>> @ disable optional_qualifier@
>> identifier fn;
>> @@
>>
>>   fn(..., Error **
>> -   ____
>> +   errp
>>      , ...)
>>   {
>>       ...
>>   }
>>
>>
>
> Ultimately, the proof is in the pudding - if we are happy with the
> conversion and the warnings produced by this script, and the amount of
> manual touchup to address those warnings, then I'm happy to accept the
> script even if I didn't fully check what it does (here, I'm trusting
> what Vladimir and Markus have been doing in their back-and-forth
> refinements of the script).

I decided that the patches produced by this script are too large to be
reviewed by a single person: the monotony blinds you a few percent in.
Instead, I spent my time on understanding the script, building trust in
its workings, and searching its output for unusual patterns.

Patches to subsystems are hopefully small enough for review by subsystem
experts.
Vladimir Sementsov-Ogievskiy March 16, 2020, 7:12 a.m. UTC | #13
On 14.03.2020 00:54, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> 13.03.2020 18:42, Markus Armbruster wrote:
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>
>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>> out now as is.
>>>>>
>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>
>>>>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>>>>> does corresponding changes in code (look for details in
>>>>>> include/qapi/error.h)
>>>>>>
>>>>>> Usage example:
>>>>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>>     --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>>>>     --max-width 80 FILES...
>>>>>>
>>>>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>>>>> ---
>>>>>>
>>>>>> Cc: Eric Blake <eblake@redhat.com>
>>>>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>>>>> Cc: Max Reitz <mreitz@redhat.com>
>>>>>> Cc: Greg Kurz <groug@kaod.org>
>>>>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>>>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>>>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>>>>> Cc: Paul Durrant <paul@xen.org>
>>>>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>>>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>>>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>>>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>>>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>>>>> Cc: Markus Armbruster <armbru@redhat.com>
>>>>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>>>>> Cc: qemu-devel@nongnu.org
>>>>>> Cc: qemu-block@nongnu.org
>>>>>> Cc: xen-devel@lists.xenproject.org
>>>>>>
>>>>>>     scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>>>>     include/qapi/error.h                          |   3 +
>>>>>>     MAINTAINERS                                   |   1 +
>>>>>>     3 files changed, 331 insertions(+)
>>>>>>     create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>
>>>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>> new file mode 100644
>>>>>> index 0000000000..7dac2dcfa4
>>>>>> --- /dev/null
>>>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>> @@ -0,0 +1,327 @@
>>>>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>>>>> +//
>>>>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>>>>> +//
>>>>>> +// This program is free software; you can redistribute it and/or
>>>>>> +// modify it under the terms of the GNU General Public License as
>>>>>> +// published by the Free Software Foundation; either version 2 of the
>>>>>> +// License, or (at your option) any later version.
>>>>>> +//
>>>>>> +// This program is distributed in the hope that it will be useful,
>>>>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>>>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>>>>> +// GNU General Public License for more details.
>>>>>> +//
>>>>>> +// You should have received a copy of the GNU General Public License
>>>>>> +// along with this program.  If not, see
>>>>>> +// <http://www.gnu.org/licenses/>.
>>>>>> +//
>>>>>> +// Usage example:
>>>>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>>>>> +//  --no-show-diff --max-width 80 FILES...
>>>>>> +//
>>>>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>>>>> +// than 80, and without this parameter coccinelle may reindent some
>>>>>> +// lines which fit into 80 characters but not to coccinelle default,
>>>>>> +// which in turn produces extra patch hunks for no reason.
>>>>>
>>>>> This is about unwanted reformatting of parameter lists due to the ___
>>>>> chaining hack.  --max-width 80 makes that less likely, but not
>>>>> impossible.
>>>>>
>>>>> We can search for unwanted reformatting of parameter lists.  I think
>>>>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>>>>> tree, I get one false positive (not a parameter list), and one hit:
>>>>>
>>>>>        @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>>>>             }
>>>>>         }
>>>>>
>>>>>        -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>>>>        +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>>>>        +                               Error **errp)
>>>>>         {
>>>>>        +    ERRP_AUTO_PROPAGATE();
>>>>>             int i;
>>>>>
>>>>>             if (!props) {
>>>>>
>>>>> Reformatting, but not unwanted.
>>>>
>>>> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
>>>> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.
>>>
>>> Agree.
>>>
>>>>>
>>>>> The --max-width 80 hack is good enough for me.
>>>>>
>>>>> It does result in slightly long transformed lines, e.g. this one in
>>>>> replication.c:
>>>>>
>>>>>        @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>>>>                 s->mode = REPLICATION_MODE_PRIMARY;
>>>>>                 top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>>>>                 if (top_id) {
>>>>>        -            error_setg(&local_err, "The primary side does not support option top-id");
>>>>>        +            error_setg(errp, "The primary side does not support option top-id");
>>>>>                     goto fail;
>>>>>                 }
>>>>>             } else if (!strcmp(mode, "secondary")) {
>>>>>
>>>>> v8 did break this line (that's how I found it).  However, v9 still
>>>>> shortens the line, just not below the target.  All your + lines look
>>>>> quite unlikely to lengthen lines.  Let's not worry about this.
>>>>>
>>>>>> +// Switch unusual Error ** parameter names to errp
>>>>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>>>>> +//
>>>>>> +// Disable optional_qualifier to skip functions with
>>>>>> +// "Error *const *errp" parameter.
>>>>>> +//
>>>>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>>>>> +// that signals unusual semantics, and the parameter name may well
>>>>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>>>>> +//
>>>>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>>>>> +// error_propagate_prepend().
>>>>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>>>>> +identifier fn;
>>>>>> +identifier _errp != errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(...,
>>>>>> +-   Error **_errp
>>>>>> ++   Error **errp
>>>>>> +    ,...)
>>>>>> + {
>>>>>> +(
>>>>>> +     ... when != assert(_errp && *_errp)
>>>>>> +&
>>>>>> +     <...
>>>>>> +-    _errp
>>>>>> ++    errp
>>>>>> +     ...>
>>>>>> +)
>>>>>> + }
>>>>>> +
>>>>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>>>>> +// necessary
>>>>>> +//
>>>>>> +// Note, that without "when any" the final "..." does not mach
>>>>>> +// something matched by previous pattern, i.e. the rule will not match
>>>>>> +// double error_prepend in control flow like in
>>>>>> +// vfio_set_irq_signaling().
>>>>>> +//
>>>>>> +// Note, "exists" says that we want apply rule even if it matches not
>>>>>> +// on all possible control flows (otherwise, it will not match
>>>>>> +// standard pattern when error_propagate() call is in if branch).
>>>>>> +@ disable optional_qualifier exists@
>>>>>> +identifier fn, local_err;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error **errp, ...)
>>>>>> + {
>>>>>> ++   ERRP_AUTO_PROPAGATE();
>>>>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>>>>> +(
>>>>>> +(
>>>>>> +    error_append_hint(errp, ...);
>>>>>> +|
>>>>>> +    error_prepend(errp, ...);
>>>>>> +|
>>>>>> +    error_vprepend(errp, ...);
>>>>>> +)
>>>>>> +    ... when any
>>>>>> +|
>>>>>> +    Error *local_err = NULL;
>>>>>> +    ...
>>>>>> +(
>>>>>> +    error_propagate_prepend(errp, local_err, ...);
>>>>>> +|
>>>>>> +    error_propagate(errp, local_err);
>>>>>> +)
>>>>>> +    ...
>>>>>> +)
>>>>>> + }
>>>>>> +
>>>>>> +
>>>>>> +// Match functions with propagation of local error to errp.
>>>>>> +// We want to refer these functions in several following rules, but I
>>>>>> +// don't know a proper way to inherit a function, not just its name
>>>>>> +// (to not match another functions with same name in following rules).
>>>>>> +// Not-proper way is as follows: rename errp parameter in functions
>>>>>> +// header and match it in following rules. Rename it back after all
>>>>>> +// transformations.
>>>>>> +//
>>>>>> +// The simplest case of propagation scheme is single definition of
>>>>>> +// local_err with at most one error_propagate_prepend or
>>>>>> +// error_propagate on each control-flow. Still, we want to match more
>>>>>> +// complex schemes too. We'll warn them with help of further rules.
>>>>>
>>>>> I think what we actually want is to examine instances of this pattern to
>>>>> figure out whether and how we want to transform them.  Perhaps:
>>>>>
>>>>>        // The common case is a single definition of local_err with at most one
>>>>>        // error_propagate_prepend() or error_propagate() on each control-flow
>>>>>        // path. Instances of this case we convert with this script. Functions
>>>>
>>>> For me, sounds a bit like "other things we don't convert".
>>>> Actually we convert other things too.
>>>
>>> What other patterns of error propagation do we convert?
>>
>> Something like in xen_block_device_destroy, why not? Otherwise, it's better to avoid
>> matching things like xen_block_device_destroy, not just warn them.
>> But I'd prefer to proceed now as is to fit into 5.0.. Too much time already
>> spent on this. So, I'm OK with your wording too.
> 
> Let's scratch "Instances of this case we convert with this script."

OK

> 
>>>>>        // with multiple definitions or propagates we want to examine
>>>>>        // manually. Later rules emit warnings to guide us to them.
>>>>>
>>>>>> +@rule1 disable optional_qualifier exists@
>>>>>> +identifier fn, local_err;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error **
>>>>>> +-    errp
>>>>>> ++    ____
>>>>>> +    , ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> +     Error *local_err = NULL;
>>>>>> +     ...
>>>>>> +(
>>>>>> +     error_propagate_prepend(errp, local_err, ...);
>>>>>> +|
>>>>>> +     error_propagate(errp, local_err);
>>>>>> +)
>>>>>> +     ...
>>>>>> + }
>>>>>> +
>>>>>> +
>>>>>> +// Warn several Error * definitions.
>>>>>> +@check1 disable optional_qualifier exists@
>>>>>> +identifier fn = rule1.fn, local_err, local_err2;
>>>>>
>>>>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>>>>> particular reason for the difference?
>>>>
>>>> I didn't find other way to ref check1.fn in next python rule. It just don't
>>>> work if I write here just rule1.fn.
>>>>
>>>>>
>>>>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>>>>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>>>>> everywhere, then apply the script to the complete tree, I get the same
>>>>> result.
>>>>
>>>> I think, it's more efficient to reuse names from previous rules. I think it should
>>>> work faster (more information, less extra matching).
>>>
>>> Nope.  With my hacked up script (patch appended) Coccinelle is actually
>>> *faster* for the .[ch] touched by this series: with your unmodified
>>> script, it takes a bit over 12s on my box, with mine around 7s.  Output
>>> is identical.
>>>
>>> Never guess performance, always measure it :)
>>
>> Hmm, whole tree results would be better proof
>>
>>>
>>> Two notes on my script:
>>>
>>> * Unlike yours, it recognizes double-propagation in my test case.
>>>     Discussed below.
>>>
>>> * Its "several definitions of" warning includes positions.  That turned
>>>     out to be useless, but I've been too lazy to take that out again.
>>>
>>>>>
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> +     Error *local_err = NULL;
>>>>>> +     ... when any
>>>>>> +     Error *local_err2 = NULL;
>>>>>> +     ... when any
>>>>>> + }
> 
> This flags functions that have more than one declaration along any
> control flow path.  It doesn't flag this one:
> 
>      void gnat(bool b, Error **errp)
>      {
>          if (b) {
>              Error *local_err = NULL;
>              foo(arg, &local_err);
>              error_propagate(errp, local_err);
>          } else {
>              Error *local_err = NULL;
>              bar(arg, &local_err);
>              error_propagate(errp, local_err);
>          }
>      }
> 
> The Coccinelle script does the right thing for this one regardless.
> 
> I'd prefer to have such functions flagged, too.  But spending time on
> convincing Coccinelle to do it for me is not worthwhile; I can simply
> search the diff produced by Coccinelle for deletions of declarations
> that are not indented exactly four spaces.
> 
> But if we keep this rule, we should adjust its comment
> 
>      // Warn several Error * definitions.
> 
> because it sure suggests it also catches functions like the one I gave
> above.

Hmm, yes.. We can write "Warn several Error * definitions in _one_ 
control flow (it's not so trivial to match _any_ case with several 
definitions with coccinelle)" or something like this.

> 
>>>>>> +
>>>>>> +@ script:python @
>>>>>> +fn << check1.fn;
>>>>>> +@@
>>>>>> +
>>>>>> +print('Warning: function {} has several definitions of '
>>>>>> +      'Error * local variable'.format(fn))
>>>>>> +
>>>>>> +// Warn several propagations in control flow.
>>>>>> +@check2 disable optional_qualifier exists@
>>>>>> +identifier fn = rule1.fn;
>>>>>> +symbol errp;
>>>>>> +position p1, p2;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> +(
>>>>>> +     error_propagate_prepend(errp, ...);@p1
>>>>>> +|
>>>>>> +     error_propagate(errp, ...);@p1
>>>>>> +)
>>>>>> +     ...
>>>>>> +(
>>>>>> +     error_propagate_prepend(errp, ...);@p2
>>>>>> +|
>>>>>> +     error_propagate(errp, ...);@p2
>>>>>> +)
>>>>>> +     ... when any
>>>>>> + }
>>>>>> +
>>>>>
>>>>> Hmm, we don't catch the example I used in review of v8:
>>>>>
>>>>>        extern foo(int, Error **);
>>>>>        extern bar(int, Error **);
>>>>>
>>>>>        void frob(Error **errp)
>>>>>        {
>>>>>            Error *local_err = NULL;
>>>>>            int arg;
>>>>>
>>>>>            foo(arg, errp);
>>>>>            bar(arg, &local_err);
>>>>>            error_propagate(errp, local_err);
>>>>>            bar(arg + 1, &local_err);
>>>>>            error_propagate(errp, local_err);
>>>>>        }
>>>>>
>>>>> I believe this is because rule1 does not match here.
>>>>
>>>> Yes, rule1 wants at least one code flow with non-doubled propagation.
>>>>
>>>>>
>>>>> If I change the rule as follows, it catches the example:
>>>>>
>>>>>        @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>>>>
>>>>>         // Warn several propagations in control flow.
>>>>>         @check2 disable optional_qualifier exists@
>>>>>        -identifier fn = rule1.fn;
>>>>>        -symbol errp;
>>>>>        +identifier fn, _errp;
>>>>>         position p1, p2;
>>>>>         @@
>>>>>
>>>>>        - fn(..., Error ** ____, ...)
>>>>>        + fn(..., Error **_errp, ...)
>>>>>          {
>>>>>              ...
>>>>>         (
>>>>>        -     error_propagate_prepend(errp, ...);@p1
>>>>>        +     error_propagate_prepend(_errp, ...);@p1
>>>>>         |
>>>>>        -     error_propagate(errp, ...);@p1
>>>>>        +     error_propagate(_errp, ...);@p1
>>>>>         )
>>>>>              ...
>>>>>         (
>>>>>        -     error_propagate_prepend(errp, ...);@p2
>>>>>        +     error_propagate_prepend(_errp, ...);@p2
>>>>>         |
>>>>>        -     error_propagate(errp, ...);@p2
>>>>>        +     error_propagate(_errp, ...);@p2
>>>>>         )
>>>>>              ... when any
>>>>>          }
>>>>>
>>>>> To my mild surprise, it still doesn't find anything in our tree.
>>>>>
>>>>> Should we decouple the previous rule from rule1, too?  I tested the
>>>>> following on the whole tree:
>>>>
>>>> I don't think so. Why to check what we are not going to convert? If we want
>>>> to check side things, it's better to do it in other coccinelle script..
>>>
>>> Misunderstanding?  The rules are still chained together via the ___
>>> hack, just not via function name, because that's unreliable and
>>> redundant.
>>
>> Strange.. Then, how can it match something not matched by rule1?
> 
> I think I got confused when I wrote the "Misunderstanding?" paragraph.
> 
> Let me try again.
> 
> First rule check2.
> 
> The common case is a at most one propagation to @errp along any control
> flow path.  We trust your Coccinelle script to convert that alright.
> 
> Any other propagation to @errp I want to review.  Whether the script
> attempts a conversion or not is unimportant, as long as it points me to
> the function to review.
> 
> Rule rule1 matches functions that propagate to @errp once along at least
> one control flow path.
> 
> Unchained from rule rule1, rule check2 flags any function that
> propagates to @errp multiple times along any control flow path.
> 
> Chained to rule1, it flags only functions that also have a path with
> single propagation.
> 
> In other words, the unchained rule flags *all* multi-propagations to
> @errp, while the chained rule flags only the ones the script attempts to
> convert.  The former is much more useful to me.
> 
> Now rule check1.  It flags functions with multiple declarations along
> any control flow path.  Again, chaining it to rule1 restricts it to the
> functions we attempt to convert.  Makes it less useful to me.  However,
> because my desire to review multiple declarations in function we don't
> attempt to convert is lower than my desire to review multiple
> propagations to @errp in such functions, chaining check1 is tolerable
> for me.  But why chain check1 if we don't chain check2?
> 

OK, let's unchain them.

>>
>>>
>>>>>
>>>>>        @@ -136,10 +136,10 @@ symbol errp;
>>>>>
>>>>>         // Warn several Error * definitions.
>>>>>         @check1 disable optional_qualifier exists@
>>>>>        -identifier fn = rule1.fn, local_err, local_err2;
>>>>>        +identifier fn, _errp, local_err, local_err2;
>>>>>         @@
>>>>>
>>>>>        - fn(..., Error ** ____, ...)
>>>>>        + fn(..., Error **_errp, ...)
>>>>>          {
>>>>>              ...
>>>>>              Error *local_err = NULL;
>>>>>
>>>>> Warnings remain unchanged.
>>>>>
>>>>>> +@ script:python @
>>>>>> +fn << check2.fn;
>>>>>> +p1 << check2.p1;
>>>>>> +p2 << check2.p2;
>>>>>> +@@
>>>>>> +
>>>>>> +print('Warning: function {} propagates to errp several times in '
>>>>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>>> +
>>>>>> +// Convert special case with goto separately.
>>>>>> +// I tried merging this into the following rule the obvious way, but
>>>>>> +// it made Coccinelle hang on block.c
>>>>>> +//
>>>>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>>>>> +// "out: }" things later after all transformations (the rule will be
>>>>>> +// the same, just without error_propagate() call), coccinelle fails to
>>>>>> +// match this "out: }".
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn, rule1.local_err, out;
>>>>>
>>>>> As explained above, I doubt the need for rule1.fn.  We do need
>>>>> rule1.local_err to avoid unwanted transformations.  More of the same
>>>>> below.
>>>>
>>>> Logically, I want to inherit from rule1. So why not to stress it by inheriting
>>>> fn variable? It's just a correct thing to do.
>>>> And I hope it helps coccinelle to work more efficiently.
>>>>
>>>>>
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +-    goto out;
>>>>>> ++    return;
>>>>>> +     ...>
>>>>>> +- out:
>>>>>> +-    error_propagate(errp, local_err);
>>>>>> + }
>>>>>> +
>>>>>> +// Convert most of local_err related stuff.
>>>>>> +//
>>>>>> +// Note, that we update everything related to matched by rule1
>>>>>> +// function name and local_err name. We may match something not
>>>>>> +// related to the pattern matched by rule1. For example, local_err may
>>>>>> +// be defined with the same name in different blocks inside one
>>>>>> +// function, and in one block follow the propagation pattern and in
>>>>>> +// other block doesn't. Or we may have several functions with the same
>>>>>> +// name (for different configurations).
>>>>>> +//
>>>>>> +// Note also that errp-cleaning functions
>>>>>> +//   error_free_errp
>>>>>> +//   error_report_errp
>>>>>> +//   error_reportf_errp
>>>>>> +//   warn_report_errp
>>>>>> +//   warn_reportf_errp
>>>>>> +// are not yet implemented. They must call corresponding Error* -
>>>>>> +// freeing function and then set *errp to NULL, to avoid further
>>>>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>>>>> +// For example, error_free_errp may look like this:
>>>>>> +//
>>>>>> +//    void error_free_errp(Error **errp)
>>>>>> +//    {
>>>>>> +//        error_free(*errp);
>>>>>> +//        *errp = NULL;
>>>>>> +//    }
>>>>>> +@ disable optional_qualifier exists@
>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>> +expression list args;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +(
>>>>>> +-    Error *local_err = NULL;
>>>>>> +|
>>>>>> +
>>>>>> +// Convert error clearing functions
>>>>>> +(
>>>>>> +-    error_free(local_err);
>>>>>> ++    error_free_errp(errp);
>>>>>> +|
>>>>>> +-    error_report_err(local_err);
>>>>>> ++    error_report_errp(errp);
>>>>>> +|
>>>>>> +-    error_reportf_err(local_err, args);
>>>>>> ++    error_reportf_errp(errp, args);
>>>>>> +|
>>>>>> +-    warn_report_err(local_err);
>>>>>> ++    warn_report_errp(errp);
>>>>>> +|
>>>>>> +-    warn_reportf_err(local_err, args);
>>>>>> ++    warn_reportf_errp(errp, args);
>>>>>> +)
>>>>>> +?-    local_err = NULL;
>>>>>> +
>>>>>> +|
>>>>>> +-    error_propagate_prepend(errp, local_err, args);
>>>>>> ++    error_prepend(errp, args);
>>>>>> +|
>>>>>> +-    error_propagate(errp, local_err);
>>>>>> +|
>>>>>> +-    &local_err
>>>>>> ++    errp
>>>>>> +)
>>>>>> +     ...>
>>>>>> + }
>>>>>> +
>>>>>> +// Convert remaining local_err usage. For example, different kinds of
>>>>>> +// error checking in if conditionals. We can't merge this into
>>>>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>>>>> +// least with "- local_err = NULL").
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +-    local_err
>>>>>> ++    *errp
>>>>>> +     ...>
>>>>>> + }
>>>>>> +
>>>>>> +// Always use the same pattern for checking error
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +-    *errp != NULL
>>>>>> ++    *errp
>>>>>> +     ...>
>>>>>> + }
>>>>>> +
>>>>>> +// Revert temporary ___ identifier.
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error **
>>>>>> +-   ____
>>>>>> ++   errp
>>>>>> +    , ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> + }
>>>>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>>>>> index 30140d9bfe..56c133520d 100644
>>>>>> --- a/include/qapi/error.h
>>>>>> +++ b/include/qapi/error.h
>>>>>> @@ -214,6 +214,9 @@
>>>>>>      *         }
>>>>>>      *         ...
>>>>>>      *     }
>>>>>> + *
>>>>>> + * For mass-conversion use script
>>>>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>      */
>>>>>>       #ifndef ERROR_H
>>>>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>>>>> index 857f969aa1..047f1b9714 100644
>>>>>> --- a/MAINTAINERS
>>>>>> +++ b/MAINTAINERS
>>>>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>>>>     F: qapi/error.json
>>>>>>     F: util/error.c
>>>>>>     F: util/qemu-error.c
>>>>>> +F: scripts/coccinelle/*err*.cocci
>>>>>>       GDB stub
>>>>>>     M: Alex Bennée <alex.bennee@linaro.org>
>>>>>
>>>
>>>
>>>   From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
>>> From: Markus Armbruster <armbru@redhat.com>
>>> Date: Fri, 13 Mar 2020 14:27:57 +0100
>>> Subject: [PATCH] fixup! scripts: Coccinelle script to use
>>>    ERRP_AUTO_PROPAGATE()
>>>
>>> ---
>>>    scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
>>>    1 file changed, 20 insertions(+), 17 deletions(-)
>>>
>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>> index 7dac2dcfa4..43b0b0e63b 100644
>>> --- a/scripts/coccinelle/auto-propagated-errp.cocci
>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>> @@ -136,45 +136,48 @@ symbol errp;
>>>      // Warn several Error * definitions.
>>>    @check1 disable optional_qualifier exists@
>>> -identifier fn = rule1.fn, local_err, local_err2;
>>> +identifier fn, _errp, local_err, local_err2;
>>> +position p1, p2;
>>
>>
>> Hmm, seems like I forget to define ____ as symbol in my patch
> 
> Coccinelle defaults to symbol.

But for errp we saw warnings simetimes.

> 
>>>    @@
>>>    - fn(..., Error ** ____, ...)
>>> + fn(..., Error **_errp, ...)
>>
>> Ahmm.. it will break compilation?
>>
>> Or, how will it work when _errp defined as meta variable is only in "+..." line? Should it be symbol instead, or just not defined?
> 
> Misunderstanding?  It's a diff between your .cocci and mine. 

Oops, yes, sorry. Patches to coccinelle scripts are tricky thing.

> My version
> is
> 
>      // Warn several Error * definitions.
>      @check1 disable optional_qualifier exists@
>      identifier fn, _errp, local_err, local_err2;
>      position p1, p2;
>      @@
> 
>       fn(..., Error **_errp, ...)
>       {
>           ...
>           Error *local_err = NULL;@p1
>           ... when any
>           Error *local_err2 = NULL;@p2
>           ... when any
>       }
> 
>      @ script:python @
>      fn << check1.fn;
>      p1 << check1.p1;
>      p2 << check1.p2;
>      @@
> 
>>>     {
>>>         ...
>>> -     Error *local_err = NULL;
>>> +     Error *local_err = NULL;@p1
>>
>> Why to do -/+ here? Nothing changed..
>>
>>>         ... when any
>>> -     Error *local_err2 = NULL;
>>> +     Error *local_err2 = NULL;@p2
>>>         ... when any
>>>     }
>>>      @ script:python @
>>>    fn << check1.fn;
>>> +p1 << check1.p1;
>>> +p2 << check1.p2;
>>>    @@
>>>      print('Warning: function {} has several definitions of '
>>> -      'Error * local variable'.format(fn))
>>> +      'Error * local variable: at {}:{} and then at {}:{}'.format(
>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>      // Warn several propagations in control flow.
>>>    @check2 disable optional_qualifier exists@
>>> -identifier fn = rule1.fn;
>>> -symbol errp;
>>> +identifier fn, _errp;
>>>    position p1, p2;
>>>    @@
>>>    - fn(..., Error ** ____, ...)
>>> + fn(..., Error **_errp, ...)
>>>     {
>>>         ...
>>>    (
>>> -     error_propagate_prepend(errp, ...);@p1
>>> +     error_propagate_prepend(_errp, ...);@p1
>>>    |
>>> -     error_propagate(errp, ...);@p1
>>> +     error_propagate(_errp, ...);@p1
>>>    )
>>>         ...
>>>    (
>>> -     error_propagate_prepend(errp, ...);@p2
>>> +     error_propagate_prepend(_errp, ...);@p2
>>>    |
>>> -     error_propagate(errp, ...);@p2
>>> +     error_propagate(_errp, ...);@p2
>>>    )
>>
>> You change some occurrences of errp to _errp, but not all. It breaks compilation.
>>
>>>         ... when any
>>>     }
>>> @@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
>>>    // the same, just without error_propagate() call), coccinelle fails to
>>>    // match this "out: }".
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn, rule1.local_err, out;
>>> +identifier fn, rule1.local_err, out;
>>
>> Hmm. If it improves performance it is strange.. But I can live with this change.
>>
>>>    symbol errp;
>>>    @@
>>>    @@ -239,7 +242,7 @@ symbol errp;
>>>    //        *errp = NULL;
>>>    //    }
>>>    @ disable optional_qualifier exists@
>>> -identifier rule1.fn, rule1.local_err;
>>> +identifier fn, rule1.local_err;
>>>    expression list args;
>>>    symbol errp;
>>>    @@
>>> @@ -287,7 +290,7 @@ symbol errp;
>>>    // previous hunk, as this conflicts with other substitutions in it (at
>>>    // least with "- local_err = NULL").
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn, rule1.local_err;
>>> +identifier fn, rule1.local_err;
>>>    symbol errp;
>>>    @@
>>>    @@ -301,7 +304,7 @@ symbol errp;
>>>      // Always use the same pattern for checking error
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn;
>>> +identifier fn;
>>>    symbol errp;
>>>    @@
>>>    @@ -315,7 +318,7 @@ symbol errp;
>>>      // Revert temporary ___ identifier.
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn;
>>> +identifier fn;
>>>    @@
>>>       fn(..., Error **
>>>
> 
> I append my hacked up version of auto-propagated-errp.cocci.  It
> produces the same patch as yours for the complete tree.
> 
> 
> 
> // Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
> //
> // Copyright (c) 2020 Virtuozzo International GmbH.
> //
> // This program is free software; you can redistribute it and/or
> // modify it under the terms of the GNU General Public License as
> // published by the Free Software Foundation; either version 2 of the
> // License, or (at your option) any later version.
> //
> // This program is distributed in the hope that it will be useful,
> // but WITHOUT ANY WARRANTY; without even the implied warranty of
> // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> // GNU General Public License for more details.
> //
> // You should have received a copy of the GNU General Public License
> // along with this program.  If not, see
> // <http://www.gnu.org/licenses/>.
> //
> // Usage example:
> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
> //  --macro-file scripts/cocci-macro-file.h --in-place \
> //  --no-show-diff --max-width 80 FILES...
> //
> // Note: --max-width 80 is needed because coccinelle default is less
> // than 80, and without this parameter coccinelle may reindent some
> // lines which fit into 80 characters but not to coccinelle default,
> // which in turn produces extra patch hunks for no reason.
> 
> // Switch unusual Error ** parameter names to errp
> // (this is necessary to use ERRP_AUTO_PROPAGATE).
> //
> // Disable optional_qualifier to skip functions with
> // "Error *const *errp" parameter.
> //
> // Skip functions with "assert(_errp && *_errp)" statement, because
> // that signals unusual semantics, and the parameter name may well
> // serve a purpose. (like nbd_iter_channel_error()).
> //
> // Skip util/error.c to not touch, for example, error_propagate() and
> // error_propagate_prepend().
> @ depends on !(file in "util/error.c") disable optional_qualifier@
> identifier fn;
> identifier _errp != errp;
> @@
> 
>   fn(...,
> -   Error **_errp
> +   Error **errp
>      ,...)
>   {
> (
>       ... when != assert(_errp && *_errp)
> &
>       <...
> -    _errp
> +    errp
>       ...>
> )
>   }
> 
> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
> // necessary
> //
> // Note, that without "when any" the final "..." does not mach
> // something matched by previous pattern, i.e. the rule will not match
> // double error_prepend in control flow like in
> // vfio_set_irq_signaling().
> //
> // Note, "exists" says that we want apply rule even if it matches not
> // on all possible control flows (otherwise, it will not match
> // standard pattern when error_propagate() call is in if branch).
> @ disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
> 
>   fn(..., Error **errp, ...)
>   {
> +   ERRP_AUTO_PROPAGATE();
>      ...  when != ERRP_AUTO_PROPAGATE();
> (
> (
>      error_append_hint(errp, ...);
> |
>      error_prepend(errp, ...);
> |
>      error_vprepend(errp, ...);
> )
>      ... when any
> |
>      Error *local_err = NULL;
>      ...
> (
>      error_propagate_prepend(errp, local_err, ...);
> |
>      error_propagate(errp, local_err);
> )
>      ...
> )
>   }
> 
> 
> // Match functions with propagation of local error to errp.
> // We want to refer these functions in several following rules, but I
> // don't know a proper way to inherit a function, not just its name
> // (to not match another functions with same name in following rules).
> // Not-proper way is as follows: rename errp parameter in functions
> // header and match it in following rules. Rename it back after all
> // transformations.
> //
> // The simplest case of propagation scheme is single definition of
> // local_err with at most one error_propagate_prepend or
> // error_propagate on each control-flow. Still, we want to match more
> // complex schemes too. We'll warn them with help of further rules.
> @rule1 disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
> 
>   fn(..., Error **
> -    errp
> +    ____
>      , ...)
>   {
>       ...
>       Error *local_err = NULL;
>       ...
> (
>       error_propagate_prepend(errp, local_err, ...);
> |
>       error_propagate(errp, local_err);
> )
>       ...
>   }
> 
> 
> // Warn several Error * definitions.
> @check1 disable optional_qualifier exists@
> identifier fn, _errp, local_err, local_err2;
> position p1, p2;
> @@
> 
>   fn(..., Error **_errp, ...)
>   {
>       ...
>       Error *local_err = NULL;@p1
>       ... when any
>       Error *local_err2 = NULL;@p2
>       ... when any
>   }
> 
> @ script:python @
> fn << check1.fn;
> p1 << check1.p1;
> p2 << check1.p2;
> @@
> 
> print('Warning: function {} has several definitions of '
>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> 
> // Warn several propagations in control flow.
> @check2 disable optional_qualifier exists@
> identifier fn, _errp;
> position p1, p2;
> @@
> 
>   fn(..., Error **_errp, ...)
>   {
>       ...
> (
>       error_propagate_prepend(_errp, ...);@p1
> |
>       error_propagate(_errp, ...);@p1
> )
>       ...
> (
>       error_propagate_prepend(_errp, ...);@p2
> |
>       error_propagate(_errp, ...);@p2
> )
>       ... when any
>   }
> 
> @ script:python @
> fn << check2.fn;
> p1 << check2.p1;
> p2 << check2.p2;
> @@
> 
> print('Warning: function {} propagates to errp several times in '
>        'one control flow: at {}:{} and then at {}:{}'.format(
>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> 
> // Convert special case with goto separately.
> // I tried merging this into the following rule the obvious way, but
> // it made Coccinelle hang on block.c
> //
> // Note interesting thing: if we don't do it here, and try to fixup
> // "out: }" things later after all transformations (the rule will be
> // the same, just without error_propagate() call), coccinelle fails to
> // match this "out: }".
> @ disable optional_qualifier@
> identifier fn, rule1.local_err, out;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    goto out;
> +    return;
>       ...>
> - out:
> -    error_propagate(errp, local_err);
>   }
> 
> // Convert most of local_err related stuff.
> //
> // Note, that we update everything related to matched by rule1
> // function name and local_err name. We may match something not
> // related to the pattern matched by rule1. For example, local_err may
> // be defined with the same name in different blocks inside one
> // function, and in one block follow the propagation pattern and in
> // other block doesn't. Or we may have several functions with the same
> // name (for different configurations).
> //
> // Note also that errp-cleaning functions
> //   error_free_errp
> //   error_report_errp
> //   error_reportf_errp
> //   warn_report_errp
> //   warn_reportf_errp
> // are not yet implemented. They must call corresponding Error* -
> // freeing function and then set *errp to NULL, to avoid further
> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
> // For example, error_free_errp may look like this:
> //
> //    void error_free_errp(Error **errp)
> //    {
> //        error_free(*errp);
> //        *errp = NULL;
> //    }
> @ disable optional_qualifier exists@
> identifier fn, rule1.local_err;
> expression list args;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> (
> -    Error *local_err = NULL;
> |
> 
> // Convert error clearing functions
> (
> -    error_free(local_err);
> +    error_free_errp(errp);
> |
> -    error_report_err(local_err);
> +    error_report_errp(errp);
> |
> -    error_reportf_err(local_err, args);
> +    error_reportf_errp(errp, args);
> |
> -    warn_report_err(local_err);
> +    warn_report_errp(errp);
> |
> -    warn_reportf_err(local_err, args);// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
//
// Copyright (c) 2020 Virtuozzo International GmbH.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see
// <http://www.gnu.org/licenses/>.
//
// Usage example:
// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
//  --macro-file scripts/cocci-macro-file.h --in-place \
//  --no-show-diff --max-width 80 FILES...
//
// Note: --max-width 80 is needed because coccinelle default is less
// than 80, and without this parameter coccinelle may reindent some
// lines which fit into 80 characters but not to coccinelle default,
// which in turn produces extra patch hunks for no reason.

// Switch unusual Error ** parameter names to errp
// (this is necessary to use ERRP_AUTO_PROPAGATE).
//
// Disable optional_qualifier to skip functions with
// "Error *const *errp" parameter.
//
// Skip functions with "assert(_errp && *_errp)" statement, because
// that signals unusual semantics, and the parameter name may well
// serve a purpose. (like nbd_iter_channel_error()).
//
// Skip util/error.c to not touch, for example, error_propagate() and
// error_propagate_prepend().
@ depends on !(file in "util/error.c") disable optional_qualifier@
identifier fn;
identifier _errp != errp;
@@

  fn(...,
-   Error **_errp
+   Error **errp
     ,...)
  {
(
      ... when != assert(_errp && *_errp)
&
      <...
-    _errp
+    errp
      ...>
)
  }

// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
// necessary
//
// Note, that without "when any" the final "..." does not mach
// something matched by previous pattern, i.e. the rule will not match
// double error_prepend in control flow like in
// vfio_set_irq_signaling().
//
// Note, "exists" says that we want apply rule even if it matches not
// on all possible control flows (otherwise, it will not match
// standard pattern when error_propagate() call is in if branch).
@ disable optional_qualifier exists@
identifier fn, local_err;
symbol errp;
@@

  fn(..., Error **errp, ...)
  {
+   ERRP_AUTO_PROPAGATE();
     ...  when != ERRP_AUTO_PROPAGATE();
(
(
     error_append_hint(errp, ...);
|
     error_prepend(errp, ...);
|
     error_vprepend(errp, ...);
)
     ... when any
|
     Error *local_err = NULL;
     ...
(
     error_propagate_prepend(errp, local_err, ...);
|
     error_propagate(errp, local_err);
)
     ...
)
  }


// Match functions with propagation of local error to errp.
// We want to refer these functions in several following rules, but I
// don't know a proper way to inherit a function, not just its name
// (to not match another functions with same name in following rules).
// Not-proper way is as follows: rename errp parameter in functions
// header and match it in following rules. Rename it back after all
// transformations.
//
// The simplest case of propagation scheme is single definition of
// local_err with at most one error_propagate_prepend or
// error_propagate on each control-flow. Still, we want to match more
// complex schemes too. We'll warn them with help of further rules.
@rule1 disable optional_qualifier exists@
identifier fn, local_err;
symbol errp;
@@

  fn(..., Error **
-    errp
+    ____
     , ...)
  {
      ...
      Error *local_err = NULL;
      ...
(
      error_propagate_prepend(errp, local_err, ...);
|
      error_propagate(errp, local_err);
)
      ...
  }


// Warn several Error * definitions.
@check1 disable optional_qualifier exists@
identifier fn, _errp, local_err, local_err2;
position p1, p2;
@@

  fn(..., Error **_errp, ...)
  {
      ...
      Error *local_err = NULL;@p1
      ... when any
      Error *local_err2 = NULL;@p2
      ... when any
  }

@ script:python @
fn << check1.fn;
p1 << check1.p1;
p2 << check1.p2;
@@

print('Warning: function {} has several definitions of '
       'Error * local variable: at {}:{} and then at {}:{}'.format(
           fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))

// Warn several propagations in control flow.
@check2 disable optional_qualifier exists@
identifier fn, _errp;
position p1, p2;
@@

  fn(..., Error **_errp, ...)
  {
      ...
(
      error_propagate_prepend(_errp, ...);@p1
|
      error_propagate(_errp, ...);@p1
)
      ...
(
      error_propagate_prepend(_errp, ...);@p2
|
      error_propagate(_errp, ...);@p2
)
      ... when any
  }

@ script:python @
fn << check2.fn;
p1 << check2.p1;
p2 << check2.p2;
@@

print('Warning: function {} propagates to errp several times in '
       'one control flow: at {}:{} and then at {}:{}'.format(
           fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))

// Convert special case with goto separately.
// I tried merging this into the following rule the obvious way, but
// it made Coccinelle hang on block.c
//
// Note interesting thing: if we don't do it here, and try to fixup
// "out: }" things later after all transformations (the rule will be
// the same, just without error_propagate() call), coccinelle fails to
// match this "out: }".
@ disable optional_qualifier@
identifier fn, rule1.local_err, out;
symbol errp;
@@

  fn(..., Error ** ____, ...)
  {
      <...
-    goto out;
+    return;
      ...>
- out:
-    error_propagate(errp, local_err);
  }

// Convert most of local_err related stuff.
//
// Note, that we update everything related to matched by rule1
// function name and local_err name. We may match something not
// related to the pattern matched by rule1. For example, local_err may
// be defined with the same name in different blocks inside one
// function, and in one block follow the propagation pattern and in
// other block doesn't. Or we may have several functions with the same
// name (for different configurations).
//
// Note also that errp-cleaning functions
//   error_free_errp
//   error_report_errp
//   error_reportf_errp
//   warn_report_errp
//   warn_reportf_errp
// are not yet implemented. They must call corresponding Error* -
// freeing function and then set *errp to NULL, to avoid further
// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
// For example, error_free_errp may look like this:
//
//    void error_free_errp(Error **errp)
//    {
//        error_free(*errp);
//        *errp = NULL;
//    }
@ disable optional_qualifier exists@
identifier fn, rule1.local_err;
expression list args;
symbol errp;
@@

  fn(..., Error ** ____, ...)
  {
      <...
(
-    Error *local_err = NULL;
|

// Convert error clearing functions
(
-    error_free(local_err);
+    error_free_errp(errp);
|
-    error_report_err(local_err);
+    error_report_errp(errp);
|
-    error_reportf_err(local_err, args);
+    error_reportf_errp(errp, args);
|
-    warn_report_err(local_err);
+    warn_report_errp(errp);
|
-    warn_reportf_err(local_err, args);
+    warn_reportf_errp(errp, args);
)
?-    local_err = NULL;

|
-    error_propagate_prepend(errp, local_err, args);
+    error_prepend(errp, args);
|
-    error_propagate(errp, local_err);
|
-    &local_err
+    errp
)
      ...>
  }

// Convert remaining local_err usage. For example, different kinds of
// error checking in if conditionals. We can't merge this into
// previous hunk, as this conflicts with other substitutions in it (at
// least with "- local_err = NULL").
@ disable optional_qualifier@
identifier fn, rule1.local_err;
symbol errp;
@@

  fn(..., Error ** ____, ...)
  {
      <...
-    local_err
+    *errp
      ...>
  }

// Always use the same pattern for checking error
@ disable optional_qualifier@
identifier fn;
symbol errp;
@@

  fn(..., Error ** ____, ...)
  {
      <...
-    *errp != NULL
+    *errp
      ...>
  }

// Revert temporary ___ identifier.
@ disable optional_qualifier@
identifier fn;
@@

  fn(..., Error **
-   ____
+   errp
     , ...)
  {
      ...
  }

> +    warn_reportf_errp(errp, args);
> )
> ?-    local_err = NULL;
> 
> |
> -    error_propagate_prepend(errp, local_err, args);
> +    error_prepend(errp, args);
> |
> -    error_propagate(errp, local_err);
> |
> -    &local_err
> +    errp
> )
>       ...>
>   }
> 
> // Convert remaining local_err usage. For example, different kinds of
> // error checking in if conditionals. We can't merge this into
> // previous hunk, as this conflicts with other substitutions in it (at
> // least with "- local_err = NULL").
> @ disable optional_qualifier@
> identifier fn, rule1.local_err;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    local_err
> +    *errp
>       ...>
>   }
> 
> // Always use the same pattern for checking error
> @ disable optional_qualifier@
> identifier fn;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    *errp != NULL
> +    *errp
>       ...>
>   }
> 
> // Revert temporary ___ identifier.
> @ disable optional_qualifier@
> identifier fn;
> @@
> 
>   fn(..., Error **
> -   ____
> +   errp
>      , ...)
>   {
>       ...
>   }
> 

OK, I almost OK with it, the only thing I doubt a bit is the following:

We want to keep rule1.local_err inheritance to keep connection with
local_err definition.

Interesting, when we have both rule1.fn and rule1.local_err inherited,
do we inherit them in separate (i.e. all possible combinations of fn
and local_err symbols from rule1) or do we inherit a pair, i.e. only
fn/local_err pairs, found by rule1? If the latter is correct, that
with your script we loss this pair inheritance, and go to all possible
combinations of fn and local_err from rule1, possibly adding some wrong
conversion (OK, you've checked that no such cases in current code tree).

So, dropping inheritance in check-rules makes sence, as it may match 
(and warn) more interesting cases.

But for other rules, I'd prefere to be safer, and explictly inherit all
actually inherited identifiers.. Still, I feel, we'll never be 
absolutely safe with coccinelle :)

--
Best regrads,
Vladimir
Markus Armbruster March 16, 2020, 8:21 a.m. UTC | #14
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> On 14.03.2020 00:54, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>
>>> 13.03.2020 18:42, Markus Armbruster wrote:
>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>
>>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>>> out now as is.
>>>>>>
>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>
>>>>>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>>>>>> does corresponding changes in code (look for details in
>>>>>>> include/qapi/error.h)
>>>>>>>
>>>>>>> Usage example:
>>>>>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>>>     --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>>>>>     --max-width 80 FILES...
>>>>>>>
>>>>>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>>>>>> ---
>>>>>>>
>>>>>>> Cc: Eric Blake <eblake@redhat.com>
>>>>>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>>>>>> Cc: Max Reitz <mreitz@redhat.com>
>>>>>>> Cc: Greg Kurz <groug@kaod.org>
>>>>>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>>>>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>>>>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>>>>>> Cc: Paul Durrant <paul@xen.org>
>>>>>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>>>>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>>>>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>>>>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>>>>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>>>>>> Cc: Markus Armbruster <armbru@redhat.com>
>>>>>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>>>>>> Cc: qemu-devel@nongnu.org
>>>>>>> Cc: qemu-block@nongnu.org
>>>>>>> Cc: xen-devel@lists.xenproject.org
>>>>>>>
>>>>>>>     scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>>>>>     include/qapi/error.h                          |   3 +
>>>>>>>     MAINTAINERS                                   |   1 +
>>>>>>>     3 files changed, 331 insertions(+)
>>>>>>>     create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>>
>>>>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>> new file mode 100644
>>>>>>> index 0000000000..7dac2dcfa4
>>>>>>> --- /dev/null
>>>>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>> @@ -0,0 +1,327 @@
>>>>>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>>>>>> +//
>>>>>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>>>>>> +//
>>>>>>> +// This program is free software; you can redistribute it and/or
>>>>>>> +// modify it under the terms of the GNU General Public License as
>>>>>>> +// published by the Free Software Foundation; either version 2 of the
>>>>>>> +// License, or (at your option) any later version.
>>>>>>> +//
>>>>>>> +// This program is distributed in the hope that it will be useful,
>>>>>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>>>>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>>>>>> +// GNU General Public License for more details.
>>>>>>> +//
>>>>>>> +// You should have received a copy of the GNU General Public License
>>>>>>> +// along with this program.  If not, see
>>>>>>> +// <http://www.gnu.org/licenses/>.
>>>>>>> +//
>>>>>>> +// Usage example:
>>>>>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>>>>>> +//  --no-show-diff --max-width 80 FILES...
>>>>>>> +//
>>>>>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>>>>>> +// than 80, and without this parameter coccinelle may reindent some
>>>>>>> +// lines which fit into 80 characters but not to coccinelle default,
>>>>>>> +// which in turn produces extra patch hunks for no reason.
>>>>>>
>>>>>> This is about unwanted reformatting of parameter lists due to the ___
>>>>>> chaining hack.  --max-width 80 makes that less likely, but not
>>>>>> impossible.
>>>>>>
>>>>>> We can search for unwanted reformatting of parameter lists.  I think
>>>>>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>>>>>> tree, I get one false positive (not a parameter list), and one hit:
>>>>>>
>>>>>>        @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>>>>>             }
>>>>>>         }
>>>>>>
>>>>>>        -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>>>>>        +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>>>>>        +                               Error **errp)
>>>>>>         {
>>>>>>        +    ERRP_AUTO_PROPAGATE();
>>>>>>             int i;
>>>>>>
>>>>>>             if (!props) {
>>>>>>
>>>>>> Reformatting, but not unwanted.
>>>>>
>>>>> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
>>>>> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.
>>>>
>>>> Agree.
>>>>
>>>>>>
>>>>>> The --max-width 80 hack is good enough for me.
>>>>>>
>>>>>> It does result in slightly long transformed lines, e.g. this one in
>>>>>> replication.c:
>>>>>>
>>>>>>        @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>>>>>                 s->mode = REPLICATION_MODE_PRIMARY;
>>>>>>                 top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>>>>>                 if (top_id) {
>>>>>>        -            error_setg(&local_err, "The primary side does not support option top-id");
>>>>>>        +            error_setg(errp, "The primary side does not support option top-id");
>>>>>>                     goto fail;
>>>>>>                 }
>>>>>>             } else if (!strcmp(mode, "secondary")) {
>>>>>>
>>>>>> v8 did break this line (that's how I found it).  However, v9 still
>>>>>> shortens the line, just not below the target.  All your + lines look
>>>>>> quite unlikely to lengthen lines.  Let's not worry about this.
>>>>>>
>>>>>>> +// Switch unusual Error ** parameter names to errp
>>>>>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>>>>>> +//
>>>>>>> +// Disable optional_qualifier to skip functions with
>>>>>>> +// "Error *const *errp" parameter.
>>>>>>> +//
>>>>>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>>>>>> +// that signals unusual semantics, and the parameter name may well
>>>>>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>>>>>> +//
>>>>>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>>>>>> +// error_propagate_prepend().
>>>>>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>>>>>> +identifier fn;
>>>>>>> +identifier _errp != errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(...,
>>>>>>> +-   Error **_errp
>>>>>>> ++   Error **errp
>>>>>>> +    ,...)
>>>>>>> + {
>>>>>>> +(
>>>>>>> +     ... when != assert(_errp && *_errp)
>>>>>>> +&
>>>>>>> +     <...
>>>>>>> +-    _errp
>>>>>>> ++    errp
>>>>>>> +     ...>
>>>>>>> +)
>>>>>>> + }
>>>>>>> +
>>>>>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>>>>>> +// necessary
>>>>>>> +//
>>>>>>> +// Note, that without "when any" the final "..." does not mach
>>>>>>> +// something matched by previous pattern, i.e. the rule will not match
>>>>>>> +// double error_prepend in control flow like in
>>>>>>> +// vfio_set_irq_signaling().
>>>>>>> +//
>>>>>>> +// Note, "exists" says that we want apply rule even if it matches not
>>>>>>> +// on all possible control flows (otherwise, it will not match
>>>>>>> +// standard pattern when error_propagate() call is in if branch).
>>>>>>> +@ disable optional_qualifier exists@
>>>>>>> +identifier fn, local_err;
>>>>>>> +symbol errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error **errp, ...)
>>>>>>> + {
>>>>>>> ++   ERRP_AUTO_PROPAGATE();
>>>>>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>>>>>> +(
>>>>>>> +(
>>>>>>> +    error_append_hint(errp, ...);
>>>>>>> +|
>>>>>>> +    error_prepend(errp, ...);
>>>>>>> +|
>>>>>>> +    error_vprepend(errp, ...);
>>>>>>> +)
>>>>>>> +    ... when any
>>>>>>> +|
>>>>>>> +    Error *local_err = NULL;
>>>>>>> +    ...
>>>>>>> +(
>>>>>>> +    error_propagate_prepend(errp, local_err, ...);
>>>>>>> +|
>>>>>>> +    error_propagate(errp, local_err);
>>>>>>> +)
>>>>>>> +    ...
>>>>>>> +)
>>>>>>> + }
>>>>>>> +
>>>>>>> +
>>>>>>> +// Match functions with propagation of local error to errp.
>>>>>>> +// We want to refer these functions in several following rules, but I
>>>>>>> +// don't know a proper way to inherit a function, not just its name
>>>>>>> +// (to not match another functions with same name in following rules).
>>>>>>> +// Not-proper way is as follows: rename errp parameter in functions
>>>>>>> +// header and match it in following rules. Rename it back after all
>>>>>>> +// transformations.
>>>>>>> +//
>>>>>>> +// The simplest case of propagation scheme is single definition of
>>>>>>> +// local_err with at most one error_propagate_prepend or
>>>>>>> +// error_propagate on each control-flow. Still, we want to match more
>>>>>>> +// complex schemes too. We'll warn them with help of further rules.
>>>>>>
>>>>>> I think what we actually want is to examine instances of this pattern to
>>>>>> figure out whether and how we want to transform them.  Perhaps:
>>>>>>
>>>>>>        // The common case is a single definition of local_err with at most one
>>>>>>        // error_propagate_prepend() or error_propagate() on each control-flow
>>>>>>        // path. Instances of this case we convert with this script. Functions
>>>>>
>>>>> For me, sounds a bit like "other things we don't convert".
>>>>> Actually we convert other things too.
>>>>
>>>> What other patterns of error propagation do we convert?
>>>
>>> Something like in xen_block_device_destroy, why not? Otherwise, it's better to avoid
>>> matching things like xen_block_device_destroy, not just warn them.
>>> But I'd prefer to proceed now as is to fit into 5.0.. Too much time already
>>> spent on this. So, I'm OK with your wording too.
>>
>> Let's scratch "Instances of this case we convert with this script."
>
> OK
>
>>
>>>>>>        // with multiple definitions or propagates we want to examine
>>>>>>        // manually. Later rules emit warnings to guide us to them.
>>>>>>
>>>>>>> +@rule1 disable optional_qualifier exists@
>>>>>>> +identifier fn, local_err;
>>>>>>> +symbol errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error **
>>>>>>> +-    errp
>>>>>>> ++    ____
>>>>>>> +    , ...)
>>>>>>> + {
>>>>>>> +     ...
>>>>>>> +     Error *local_err = NULL;
>>>>>>> +     ...
>>>>>>> +(
>>>>>>> +     error_propagate_prepend(errp, local_err, ...);
>>>>>>> +|
>>>>>>> +     error_propagate(errp, local_err);
>>>>>>> +)
>>>>>>> +     ...
>>>>>>> + }
>>>>>>> +
>>>>>>> +
>>>>>>> +// Warn several Error * definitions.
>>>>>>> +@check1 disable optional_qualifier exists@
>>>>>>> +identifier fn = rule1.fn, local_err, local_err2;
>>>>>>
>>>>>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>>>>>> particular reason for the difference?
>>>>>
>>>>> I didn't find other way to ref check1.fn in next python rule. It just don't
>>>>> work if I write here just rule1.fn.
>>>>>
>>>>>>
>>>>>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>>>>>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>>>>>> everywhere, then apply the script to the complete tree, I get the same
>>>>>> result.
>>>>>
>>>>> I think, it's more efficient to reuse names from previous rules. I think it should
>>>>> work faster (more information, less extra matching).
>>>>
>>>> Nope.  With my hacked up script (patch appended) Coccinelle is actually
>>>> *faster* for the .[ch] touched by this series: with your unmodified
>>>> script, it takes a bit over 12s on my box, with mine around 7s.  Output
>>>> is identical.
>>>>
>>>> Never guess performance, always measure it :)
>>>
>>> Hmm, whole tree results would be better proof
>>>
>>>>
>>>> Two notes on my script:
>>>>
>>>> * Unlike yours, it recognizes double-propagation in my test case.
>>>>     Discussed below.
>>>>
>>>> * Its "several definitions of" warning includes positions.  That turned
>>>>     out to be useless, but I've been too lazy to take that out again.
>>>>
>>>>>>
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>> + {
>>>>>>> +     ...
>>>>>>> +     Error *local_err = NULL;
>>>>>>> +     ... when any
>>>>>>> +     Error *local_err2 = NULL;
>>>>>>> +     ... when any
>>>>>>> + }
>>
>> This flags functions that have more than one declaration along any
>> control flow path.  It doesn't flag this one:
>>
>>      void gnat(bool b, Error **errp)
>>      {
>>          if (b) {
>>              Error *local_err = NULL;
>>              foo(arg, &local_err);
>>              error_propagate(errp, local_err);
>>          } else {
>>              Error *local_err = NULL;
>>              bar(arg, &local_err);
>>              error_propagate(errp, local_err);
>>          }
>>      }
>>
>> The Coccinelle script does the right thing for this one regardless.
>>
>> I'd prefer to have such functions flagged, too.  But spending time on
>> convincing Coccinelle to do it for me is not worthwhile; I can simply
>> search the diff produced by Coccinelle for deletions of declarations
>> that are not indented exactly four spaces.
>>
>> But if we keep this rule, we should adjust its comment
>>
>>      // Warn several Error * definitions.
>>
>> because it sure suggests it also catches functions like the one I gave
>> above.
>
> Hmm, yes.. We can write "Warn several Error * definitions in _one_
> control flow (it's not so trivial to match _any_ case with several
> definitions with coccinelle)" or something like this.

Ha, "trivial" reminds me of a story.  The math professor, after having
spent a good chunk of his lecture developing a proof on the blackboad
turns to the audience to explain why this little part doesn't require
proof with the words familiar to any math student "and this is trivial."
Pause, puzzled look...  "Is it trivial?"  Pause, storms out of the
lecture hall.  A minute or three pass.  Professor comes back beaming,
"it is trivial!", and proceeds with the proof.

My point is: it might be trivial with Coccinelle once you know how to do
it.  We don't.

Suggest "(can't figure out how to match several definitions regardless
of control flow)".

>
>>
>>>>>>> +
>>>>>>> +@ script:python @
>>>>>>> +fn << check1.fn;
>>>>>>> +@@
>>>>>>> +
>>>>>>> +print('Warning: function {} has several definitions of '
>>>>>>> +      'Error * local variable'.format(fn))
>>>>>>> +
>>>>>>> +// Warn several propagations in control flow.
>>>>>>> +@check2 disable optional_qualifier exists@
>>>>>>> +identifier fn = rule1.fn;
>>>>>>> +symbol errp;
>>>>>>> +position p1, p2;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>> + {
>>>>>>> +     ...
>>>>>>> +(
>>>>>>> +     error_propagate_prepend(errp, ...);@p1
>>>>>>> +|
>>>>>>> +     error_propagate(errp, ...);@p1
>>>>>>> +)
>>>>>>> +     ...
>>>>>>> +(
>>>>>>> +     error_propagate_prepend(errp, ...);@p2
>>>>>>> +|
>>>>>>> +     error_propagate(errp, ...);@p2
>>>>>>> +)
>>>>>>> +     ... when any
>>>>>>> + }
>>>>>>> +
>>>>>>
>>>>>> Hmm, we don't catch the example I used in review of v8:
>>>>>>
>>>>>>        extern foo(int, Error **);
>>>>>>        extern bar(int, Error **);
>>>>>>
>>>>>>        void frob(Error **errp)
>>>>>>        {
>>>>>>            Error *local_err = NULL;
>>>>>>            int arg;
>>>>>>
>>>>>>            foo(arg, errp);
>>>>>>            bar(arg, &local_err);
>>>>>>            error_propagate(errp, local_err);
>>>>>>            bar(arg + 1, &local_err);
>>>>>>            error_propagate(errp, local_err);
>>>>>>        }
>>>>>>
>>>>>> I believe this is because rule1 does not match here.
>>>>>
>>>>> Yes, rule1 wants at least one code flow with non-doubled propagation.
>>>>>
>>>>>>
>>>>>> If I change the rule as follows, it catches the example:
>>>>>>
>>>>>>        @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>>>>>
>>>>>>         // Warn several propagations in control flow.
>>>>>>         @check2 disable optional_qualifier exists@
>>>>>>        -identifier fn = rule1.fn;
>>>>>>        -symbol errp;
>>>>>>        +identifier fn, _errp;
>>>>>>         position p1, p2;
>>>>>>         @@
>>>>>>
>>>>>>        - fn(..., Error ** ____, ...)
>>>>>>        + fn(..., Error **_errp, ...)
>>>>>>          {
>>>>>>              ...
>>>>>>         (
>>>>>>        -     error_propagate_prepend(errp, ...);@p1
>>>>>>        +     error_propagate_prepend(_errp, ...);@p1
>>>>>>         |
>>>>>>        -     error_propagate(errp, ...);@p1
>>>>>>        +     error_propagate(_errp, ...);@p1
>>>>>>         )
>>>>>>              ...
>>>>>>         (
>>>>>>        -     error_propagate_prepend(errp, ...);@p2
>>>>>>        +     error_propagate_prepend(_errp, ...);@p2
>>>>>>         |
>>>>>>        -     error_propagate(errp, ...);@p2
>>>>>>        +     error_propagate(_errp, ...);@p2
>>>>>>         )
>>>>>>              ... when any
>>>>>>          }
>>>>>>
>>>>>> To my mild surprise, it still doesn't find anything in our tree.
>>>>>>
>>>>>> Should we decouple the previous rule from rule1, too?  I tested the
>>>>>> following on the whole tree:
>>>>>
>>>>> I don't think so. Why to check what we are not going to convert? If we want
>>>>> to check side things, it's better to do it in other coccinelle script..
>>>>
>>>> Misunderstanding?  The rules are still chained together via the ___
>>>> hack, just not via function name, because that's unreliable and
>>>> redundant.
>>>
>>> Strange.. Then, how can it match something not matched by rule1?
>>
>> I think I got confused when I wrote the "Misunderstanding?" paragraph.
>>
>> Let me try again.
>>
>> First rule check2.
>>
>> The common case is a at most one propagation to @errp along any control
>> flow path.  We trust your Coccinelle script to convert that alright.
>>
>> Any other propagation to @errp I want to review.  Whether the script
>> attempts a conversion or not is unimportant, as long as it points me to
>> the function to review.
>>
>> Rule rule1 matches functions that propagate to @errp once along at least
>> one control flow path.
>>
>> Unchained from rule rule1, rule check2 flags any function that
>> propagates to @errp multiple times along any control flow path.
>>
>> Chained to rule1, it flags only functions that also have a path with
>> single propagation.
>>
>> In other words, the unchained rule flags *all* multi-propagations to
>> @errp, while the chained rule flags only the ones the script attempts to
>> convert.  The former is much more useful to me.
>>
>> Now rule check1.  It flags functions with multiple declarations along
>> any control flow path.  Again, chaining it to rule1 restricts it to the
>> functions we attempt to convert.  Makes it less useful to me.  However,
>> because my desire to review multiple declarations in function we don't
>> attempt to convert is lower than my desire to review multiple
>> propagations to @errp in such functions, chaining check1 is tolerable
>> for me.  But why chain check1 if we don't chain check2?
>>
>
> OK, let's unchain them.
>
>>>
>>>>
>>>>>>
>>>>>>        @@ -136,10 +136,10 @@ symbol errp;
>>>>>>
>>>>>>         // Warn several Error * definitions.
>>>>>>         @check1 disable optional_qualifier exists@
>>>>>>        -identifier fn = rule1.fn, local_err, local_err2;
>>>>>>        +identifier fn, _errp, local_err, local_err2;
>>>>>>         @@
>>>>>>
>>>>>>        - fn(..., Error ** ____, ...)
>>>>>>        + fn(..., Error **_errp, ...)
>>>>>>          {
>>>>>>              ...
>>>>>>              Error *local_err = NULL;
>>>>>>
>>>>>> Warnings remain unchanged.
>>>>>>
>>>>>>> +@ script:python @
>>>>>>> +fn << check2.fn;
>>>>>>> +p1 << check2.p1;
>>>>>>> +p2 << check2.p2;
>>>>>>> +@@
>>>>>>> +
>>>>>>> +print('Warning: function {} propagates to errp several times in '
>>>>>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>>>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>>>> +
>>>>>>> +// Convert special case with goto separately.
>>>>>>> +// I tried merging this into the following rule the obvious way, but
>>>>>>> +// it made Coccinelle hang on block.c
>>>>>>> +//
>>>>>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>>>>>> +// "out: }" things later after all transformations (the rule will be
>>>>>>> +// the same, just without error_propagate() call), coccinelle fails to
>>>>>>> +// match this "out: }".
>>>>>>> +@ disable optional_qualifier@
>>>>>>> +identifier rule1.fn, rule1.local_err, out;
>>>>>>
>>>>>> As explained above, I doubt the need for rule1.fn.  We do need
>>>>>> rule1.local_err to avoid unwanted transformations.  More of the same
>>>>>> below.
>>>>>
>>>>> Logically, I want to inherit from rule1. So why not to stress it by inheriting
>>>>> fn variable? It's just a correct thing to do.
>>>>> And I hope it helps coccinelle to work more efficiently.
>>>>>
>>>>>>
>>>>>>> +symbol errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>> + {
>>>>>>> +     <...
>>>>>>> +-    goto out;
>>>>>>> ++    return;
>>>>>>> +     ...>
>>>>>>> +- out:
>>>>>>> +-    error_propagate(errp, local_err);
>>>>>>> + }
>>>>>>> +
>>>>>>> +// Convert most of local_err related stuff.
>>>>>>> +//
>>>>>>> +// Note, that we update everything related to matched by rule1
>>>>>>> +// function name and local_err name. We may match something not
>>>>>>> +// related to the pattern matched by rule1. For example, local_err may
>>>>>>> +// be defined with the same name in different blocks inside one
>>>>>>> +// function, and in one block follow the propagation pattern and in
>>>>>>> +// other block doesn't. Or we may have several functions with the same
>>>>>>> +// name (for different configurations).
>>>>>>> +//
>>>>>>> +// Note also that errp-cleaning functions
>>>>>>> +//   error_free_errp
>>>>>>> +//   error_report_errp
>>>>>>> +//   error_reportf_errp
>>>>>>> +//   warn_report_errp
>>>>>>> +//   warn_reportf_errp
>>>>>>> +// are not yet implemented. They must call corresponding Error* -
>>>>>>> +// freeing function and then set *errp to NULL, to avoid further
>>>>>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>>>>>> +// For example, error_free_errp may look like this:
>>>>>>> +//
>>>>>>> +//    void error_free_errp(Error **errp)
>>>>>>> +//    {
>>>>>>> +//        error_free(*errp);
>>>>>>> +//        *errp = NULL;
>>>>>>> +//    }
>>>>>>> +@ disable optional_qualifier exists@
>>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>>> +expression list args;
>>>>>>> +symbol errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>> + {
>>>>>>> +     <...
>>>>>>> +(
>>>>>>> +-    Error *local_err = NULL;
>>>>>>> +|
>>>>>>> +
>>>>>>> +// Convert error clearing functions
>>>>>>> +(
>>>>>>> +-    error_free(local_err);
>>>>>>> ++    error_free_errp(errp);
>>>>>>> +|
>>>>>>> +-    error_report_err(local_err);
>>>>>>> ++    error_report_errp(errp);
>>>>>>> +|
>>>>>>> +-    error_reportf_err(local_err, args);
>>>>>>> ++    error_reportf_errp(errp, args);
>>>>>>> +|
>>>>>>> +-    warn_report_err(local_err);
>>>>>>> ++    warn_report_errp(errp);
>>>>>>> +|
>>>>>>> +-    warn_reportf_err(local_err, args);
>>>>>>> ++    warn_reportf_errp(errp, args);
>>>>>>> +)
>>>>>>> +?-    local_err = NULL;
>>>>>>> +
>>>>>>> +|
>>>>>>> +-    error_propagate_prepend(errp, local_err, args);
>>>>>>> ++    error_prepend(errp, args);
>>>>>>> +|
>>>>>>> +-    error_propagate(errp, local_err);
>>>>>>> +|
>>>>>>> +-    &local_err
>>>>>>> ++    errp
>>>>>>> +)
>>>>>>> +     ...>
>>>>>>> + }
>>>>>>> +
>>>>>>> +// Convert remaining local_err usage. For example, different kinds of
>>>>>>> +// error checking in if conditionals. We can't merge this into
>>>>>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>>>>>> +// least with "- local_err = NULL").
>>>>>>> +@ disable optional_qualifier@
>>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>>> +symbol errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>> + {
>>>>>>> +     <...
>>>>>>> +-    local_err
>>>>>>> ++    *errp
>>>>>>> +     ...>
>>>>>>> + }
>>>>>>> +
>>>>>>> +// Always use the same pattern for checking error
>>>>>>> +@ disable optional_qualifier@
>>>>>>> +identifier rule1.fn;
>>>>>>> +symbol errp;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>> + {
>>>>>>> +     <...
>>>>>>> +-    *errp != NULL
>>>>>>> ++    *errp
>>>>>>> +     ...>
>>>>>>> + }
>>>>>>> +
>>>>>>> +// Revert temporary ___ identifier.
>>>>>>> +@ disable optional_qualifier@
>>>>>>> +identifier rule1.fn;
>>>>>>> +@@
>>>>>>> +
>>>>>>> + fn(..., Error **
>>>>>>> +-   ____
>>>>>>> ++   errp
>>>>>>> +    , ...)
>>>>>>> + {
>>>>>>> +     ...
>>>>>>> + }
>>>>>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>>>>>> index 30140d9bfe..56c133520d 100644
>>>>>>> --- a/include/qapi/error.h
>>>>>>> +++ b/include/qapi/error.h
>>>>>>> @@ -214,6 +214,9 @@
>>>>>>>      *         }
>>>>>>>      *         ...
>>>>>>>      *     }
>>>>>>> + *
>>>>>>> + * For mass-conversion use script
>>>>>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>>      */
>>>>>>>       #ifndef ERROR_H
>>>>>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>>>>>> index 857f969aa1..047f1b9714 100644
>>>>>>> --- a/MAINTAINERS
>>>>>>> +++ b/MAINTAINERS
>>>>>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>>>>>     F: qapi/error.json
>>>>>>>     F: util/error.c
>>>>>>>     F: util/qemu-error.c
>>>>>>> +F: scripts/coccinelle/*err*.cocci
>>>>>>>       GDB stub
>>>>>>>     M: Alex Bennée <alex.bennee@linaro.org>
>>>>>>
>>>>
>>>>
>>>>   From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
>>>> From: Markus Armbruster <armbru@redhat.com>
>>>> Date: Fri, 13 Mar 2020 14:27:57 +0100
>>>> Subject: [PATCH] fixup! scripts: Coccinelle script to use
>>>>    ERRP_AUTO_PROPAGATE()
>>>>
>>>> ---
>>>>    scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
>>>>    1 file changed, 20 insertions(+), 17 deletions(-)
>>>>
>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>> index 7dac2dcfa4..43b0b0e63b 100644
>>>> --- a/scripts/coccinelle/auto-propagated-errp.cocci
>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>> @@ -136,45 +136,48 @@ symbol errp;
>>>>      // Warn several Error * definitions.
>>>>    @check1 disable optional_qualifier exists@
>>>> -identifier fn = rule1.fn, local_err, local_err2;
>>>> +identifier fn, _errp, local_err, local_err2;
>>>> +position p1, p2;
>>>
>>>
>>> Hmm, seems like I forget to define ____ as symbol in my patch
>>
>> Coccinelle defaults to symbol.
>
> But for errp we saw warnings simetimes.

I believe it warns when you use rely on the symbol default while also
using it as something else in other rules.

Feel free to explicitly define it as symbol.

>>>>    @@
>>>>    - fn(..., Error ** ____, ...)
>>>> + fn(..., Error **_errp, ...)
>>>
>>> Ahmm.. it will break compilation?
>>>
>>> Or, how will it work when _errp defined as meta variable is only in "+..." line? Should it be symbol instead, or just not defined?
>>
>> Misunderstanding?  It's a diff between your .cocci and mine. 
>
> Oops, yes, sorry. Patches to coccinelle scripts are tricky thing.
>
>> My version
>> is
>>
>>      // Warn several Error * definitions.
>>      @check1 disable optional_qualifier exists@
>>      identifier fn, _errp, local_err, local_err2;
>>      position p1, p2;
>>      @@
>>
>>       fn(..., Error **_errp, ...)
>>       {
>>           ...
>>           Error *local_err = NULL;@p1
>>           ... when any
>>           Error *local_err2 = NULL;@p2
>>           ... when any
>>       }
>>
>>      @ script:python @
>>      fn << check1.fn;
>>      p1 << check1.p1;
>>      p2 << check1.p2;
>>      @@
>>
>>>>     {
>>>>         ...
>>>> -     Error *local_err = NULL;
>>>> +     Error *local_err = NULL;@p1
>>>
>>> Why to do -/+ here? Nothing changed..
>>>
>>>>         ... when any
>>>> -     Error *local_err2 = NULL;
>>>> +     Error *local_err2 = NULL;@p2
>>>>         ... when any
>>>>     }
>>>>      @ script:python @
>>>>    fn << check1.fn;
>>>> +p1 << check1.p1;
>>>> +p2 << check1.p2;
>>>>    @@
>>>>      print('Warning: function {} has several definitions of '
>>>> -      'Error * local variable'.format(fn))
>>>> +      'Error * local variable: at {}:{} and then at {}:{}'.format(
>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>      // Warn several propagations in control flow.
>>>>    @check2 disable optional_qualifier exists@
>>>> -identifier fn = rule1.fn;
>>>> -symbol errp;
>>>> +identifier fn, _errp;
>>>>    position p1, p2;
>>>>    @@
>>>>    - fn(..., Error ** ____, ...)
>>>> + fn(..., Error **_errp, ...)
>>>>     {
>>>>         ...
>>>>    (
>>>> -     error_propagate_prepend(errp, ...);@p1
>>>> +     error_propagate_prepend(_errp, ...);@p1
>>>>    |
>>>> -     error_propagate(errp, ...);@p1
>>>> +     error_propagate(_errp, ...);@p1
>>>>    )
>>>>         ...
>>>>    (
>>>> -     error_propagate_prepend(errp, ...);@p2
>>>> +     error_propagate_prepend(_errp, ...);@p2
>>>>    |
>>>> -     error_propagate(errp, ...);@p2
>>>> +     error_propagate(_errp, ...);@p2
>>>>    )
>>>
>>> You change some occurrences of errp to _errp, but not all. It breaks compilation.
>>>
>>>>         ... when any
>>>>     }
>>>> @@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
>>>>    // the same, just without error_propagate() call), coccinelle fails to
>>>>    // match this "out: }".
>>>>    @ disable optional_qualifier@
>>>> -identifier rule1.fn, rule1.local_err, out;
>>>> +identifier fn, rule1.local_err, out;
>>>
>>> Hmm. If it improves performance it is strange.. But I can live with this change.
>>>
>>>>    symbol errp;
>>>>    @@
>>>>    @@ -239,7 +242,7 @@ symbol errp;
>>>>    //        *errp = NULL;
>>>>    //    }
>>>>    @ disable optional_qualifier exists@
>>>> -identifier rule1.fn, rule1.local_err;
>>>> +identifier fn, rule1.local_err;
>>>>    expression list args;
>>>>    symbol errp;
>>>>    @@
>>>> @@ -287,7 +290,7 @@ symbol errp;
>>>>    // previous hunk, as this conflicts with other substitutions in it (at
>>>>    // least with "- local_err = NULL").
>>>>    @ disable optional_qualifier@
>>>> -identifier rule1.fn, rule1.local_err;
>>>> +identifier fn, rule1.local_err;
>>>>    symbol errp;
>>>>    @@
>>>>    @@ -301,7 +304,7 @@ symbol errp;
>>>>      // Always use the same pattern for checking error
>>>>    @ disable optional_qualifier@
>>>> -identifier rule1.fn;
>>>> +identifier fn;
>>>>    symbol errp;
>>>>    @@
>>>>    @@ -315,7 +318,7 @@ symbol errp;
>>>>      // Revert temporary ___ identifier.
>>>>    @ disable optional_qualifier@
>>>> -identifier rule1.fn;
>>>> +identifier fn;
>>>>    @@
>>>>       fn(..., Error **
>>>>
>>
>> I append my hacked up version of auto-propagated-errp.cocci.  It
>> produces the same patch as yours for the complete tree.
>>
>>
>>
>> // Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>> //
>> // Copyright (c) 2020 Virtuozzo International GmbH.
>> //
>> // This program is free software; you can redistribute it and/or
>> // modify it under the terms of the GNU General Public License as
>> // published by the Free Software Foundation; either version 2 of the
>> // License, or (at your option) any later version.
>> //
>> // This program is distributed in the hope that it will be useful,
>> // but WITHOUT ANY WARRANTY; without even the implied warranty of
>> // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> // GNU General Public License for more details.
>> //
>> // You should have received a copy of the GNU General Public License
>> // along with this program.  If not, see
>> // <http://www.gnu.org/licenses/>.
>> //
>> // Usage example:
>> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>> //  --macro-file scripts/cocci-macro-file.h --in-place \
>> //  --no-show-diff --max-width 80 FILES...
>> //
>> // Note: --max-width 80 is needed because coccinelle default is less
>> // than 80, and without this parameter coccinelle may reindent some
>> // lines which fit into 80 characters but not to coccinelle default,
>> // which in turn produces extra patch hunks for no reason.
>>
>> // Switch unusual Error ** parameter names to errp
>> // (this is necessary to use ERRP_AUTO_PROPAGATE).
>> //
>> // Disable optional_qualifier to skip functions with
>> // "Error *const *errp" parameter.
>> //
>> // Skip functions with "assert(_errp && *_errp)" statement, because
>> // that signals unusual semantics, and the parameter name may well
>> // serve a purpose. (like nbd_iter_channel_error()).
>> //
>> // Skip util/error.c to not touch, for example, error_propagate() and
>> // error_propagate_prepend().
>> @ depends on !(file in "util/error.c") disable optional_qualifier@
>> identifier fn;
>> identifier _errp != errp;
>> @@
>>
>>   fn(...,
>> -   Error **_errp
>> +   Error **errp
>>      ,...)
>>   {
>> (
>>       ... when != assert(_errp && *_errp)
>> &
>>       <...
>> -    _errp
>> +    errp
>>       ...>
>> )
>>   }
>>
>> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>> // necessary
>> //
>> // Note, that without "when any" the final "..." does not mach
>> // something matched by previous pattern, i.e. the rule will not match
>> // double error_prepend in control flow like in
>> // vfio_set_irq_signaling().
>> //
>> // Note, "exists" says that we want apply rule even if it matches not
>> // on all possible control flows (otherwise, it will not match
>> // standard pattern when error_propagate() call is in if branch).
>> @ disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **errp, ...)
>>   {
>> +   ERRP_AUTO_PROPAGATE();
>>      ...  when != ERRP_AUTO_PROPAGATE();
>> (
>> (
>>      error_append_hint(errp, ...);
>> |
>>      error_prepend(errp, ...);
>> |
>>      error_vprepend(errp, ...);
>> )
>>      ... when any
>> |
>>      Error *local_err = NULL;
>>      ...
>> (
>>      error_propagate_prepend(errp, local_err, ...);
>> |
>>      error_propagate(errp, local_err);
>> )
>>      ...
>> )
>>   }
>>
>>
>> // Match functions with propagation of local error to errp.
>> // We want to refer these functions in several following rules, but I
>> // don't know a proper way to inherit a function, not just its name
>> // (to not match another functions with same name in following rules).
>> // Not-proper way is as follows: rename errp parameter in functions
>> // header and match it in following rules. Rename it back after all
>> // transformations.
>> //
>> // The simplest case of propagation scheme is single definition of
>> // local_err with at most one error_propagate_prepend or
>> // error_propagate on each control-flow. Still, we want to match more
>> // complex schemes too. We'll warn them with help of further rules.
>> @rule1 disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **
>> -    errp
>> +    ____
>>      , ...)
>>   {
>>       ...
>>       Error *local_err = NULL;
>>       ...
>> (
>>       error_propagate_prepend(errp, local_err, ...);
>> |
>>       error_propagate(errp, local_err);
>> )
>>       ...
>>   }
>>
>>
>> // Warn several Error * definitions.
>> @check1 disable optional_qualifier exists@
>> identifier fn, _errp, local_err, local_err2;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>>       Error *local_err = NULL;@p1
>>       ... when any
>>       Error *local_err2 = NULL;@p2
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check1.fn;
>> p1 << check1.p1;
>> p2 << check1.p2;
>> @@
>>
>> print('Warning: function {} has several definitions of '
>>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Warn several propagations in control flow.
>> @check2 disable optional_qualifier exists@
>> identifier fn, _errp;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>> (
>>       error_propagate_prepend(_errp, ...);@p1
>> |
>>       error_propagate(_errp, ...);@p1
>> )
>>       ...
>> (
>>       error_propagate_prepend(_errp, ...);@p2
>> |
>>       error_propagate(_errp, ...);@p2
>> )
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check2.fn;
>> p1 << check2.p1;
>> p2 << check2.p2;
>> @@
>>
>> print('Warning: function {} propagates to errp several times in '
>>        'one control flow: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Convert special case with goto separately.
>> // I tried merging this into the following rule the obvious way, but
>> // it made Coccinelle hang on block.c
>> //
>> // Note interesting thing: if we don't do it here, and try to fixup
>> // "out: }" things later after all transformations (the rule will be
>> // the same, just without error_propagate() call), coccinelle fails to
>> // match this "out: }".
>> @ disable optional_qualifier@
>> identifier fn, rule1.local_err, out;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    goto out;
>> +    return;
>>       ...>
>> - out:
>> -    error_propagate(errp, local_err);
>>   }
>>
>> // Convert most of local_err related stuff.
>> //
>> // Note, that we update everything related to matched by rule1
>> // function name and local_err name. We may match something not
>> // related to the pattern matched by rule1. For example, local_err may
>> // be defined with the same name in different blocks inside one
>> // function, and in one block follow the propagation pattern and in
>> // other block doesn't. Or we may have several functions with the same
>> // name (for different configurations).
>> //
>> // Note also that errp-cleaning functions
>> //   error_free_errp
>> //   error_report_errp
>> //   error_reportf_errp
>> //   warn_report_errp
>> //   warn_reportf_errp
>> // are not yet implemented. They must call corresponding Error* -
>> // freeing function and then set *errp to NULL, to avoid further
>> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>> // For example, error_free_errp may look like this:
>> //
>> //    void error_free_errp(Error **errp)
>> //    {
>> //        error_free(*errp);
>> //        *errp = NULL;
>> //    }
>> @ disable optional_qualifier exists@
>> identifier fn, rule1.local_err;
>> expression list args;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> (
>> -    Error *local_err = NULL;
>> |
>>
>> // Convert error clearing functions
>> (
>> -    error_free(local_err);
>> +    error_free_errp(errp);
>> |
>> -    error_report_err(local_err);
>> +    error_report_errp(errp);
>> |
>> -    error_reportf_err(local_err, args);
>> +    error_reportf_errp(errp, args);
>> |
>> -    warn_report_err(local_err);
>> +    warn_report_errp(errp);
>> |
>> -    warn_reportf_err(local_err, args);// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
> //
> // Copyright (c) 2020 Virtuozzo International GmbH.
> //
> // This program is free software; you can redistribute it and/or
> // modify it under the terms of the GNU General Public License as
> // published by the Free Software Foundation; either version 2 of the
> // License, or (at your option) any later version.
> //
> // This program is distributed in the hope that it will be useful,
> // but WITHOUT ANY WARRANTY; without even the implied warranty of
> // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> // GNU General Public License for more details.
> //
> // You should have received a copy of the GNU General Public License
> // along with this program.  If not, see
> // <http://www.gnu.org/licenses/>.
> //
> // Usage example:
> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
> //  --macro-file scripts/cocci-macro-file.h --in-place \
> //  --no-show-diff --max-width 80 FILES...
> //
> // Note: --max-width 80 is needed because coccinelle default is less
> // than 80, and without this parameter coccinelle may reindent some
> // lines which fit into 80 characters but not to coccinelle default,
> // which in turn produces extra patch hunks for no reason.
>
> // Switch unusual Error ** parameter names to errp
> // (this is necessary to use ERRP_AUTO_PROPAGATE).
> //
> // Disable optional_qualifier to skip functions with
> // "Error *const *errp" parameter.
> //
> // Skip functions with "assert(_errp && *_errp)" statement, because
> // that signals unusual semantics, and the parameter name may well
> // serve a purpose. (like nbd_iter_channel_error()).
> //
> // Skip util/error.c to not touch, for example, error_propagate() and
> // error_propagate_prepend().
> @ depends on !(file in "util/error.c") disable optional_qualifier@
> identifier fn;
> identifier _errp != errp;
> @@
>
>  fn(...,
> -   Error **_errp
> +   Error **errp
>     ,...)
>  {
> (
>      ... when != assert(_errp && *_errp)
> &
>      <...
> -    _errp
> +    errp
>      ...>
> )
>  }
>
> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
> // necessary
> //
> // Note, that without "when any" the final "..." does not mach
> // something matched by previous pattern, i.e. the rule will not match
> // double error_prepend in control flow like in
> // vfio_set_irq_signaling().
> //
> // Note, "exists" says that we want apply rule even if it matches not
> // on all possible control flows (otherwise, it will not match
> // standard pattern when error_propagate() call is in if branch).
> @ disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
>
>  fn(..., Error **errp, ...)
>  {
> +   ERRP_AUTO_PROPAGATE();
>     ...  when != ERRP_AUTO_PROPAGATE();
> (
> (
>     error_append_hint(errp, ...);
> |
>     error_prepend(errp, ...);
> |
>     error_vprepend(errp, ...);
> )
>     ... when any
> |
>     Error *local_err = NULL;
>     ...
> (
>     error_propagate_prepend(errp, local_err, ...);
> |
>     error_propagate(errp, local_err);
> )
>     ...
> )
>  }
>
>
> // Match functions with propagation of local error to errp.
> // We want to refer these functions in several following rules, but I
> // don't know a proper way to inherit a function, not just its name
> // (to not match another functions with same name in following rules).
> // Not-proper way is as follows: rename errp parameter in functions
> // header and match it in following rules. Rename it back after all
> // transformations.
> //
> // The simplest case of propagation scheme is single definition of
> // local_err with at most one error_propagate_prepend or
> // error_propagate on each control-flow. Still, we want to match more
> // complex schemes too. We'll warn them with help of further rules.
> @rule1 disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
>
>  fn(..., Error **
> -    errp
> +    ____
>     , ...)
>  {
>      ...
>      Error *local_err = NULL;
>      ...
> (
>      error_propagate_prepend(errp, local_err, ...);
> |
>      error_propagate(errp, local_err);
> )
>      ...
>  }
>
>
> // Warn several Error * definitions.
> @check1 disable optional_qualifier exists@
> identifier fn, _errp, local_err, local_err2;
> position p1, p2;
> @@
>
>  fn(..., Error **_errp, ...)
>  {
>      ...
>      Error *local_err = NULL;@p1
>      ... when any
>      Error *local_err2 = NULL;@p2
>      ... when any
>  }
>
> @ script:python @
> fn << check1.fn;
> p1 << check1.p1;
> p2 << check1.p2;
> @@
>
> print('Warning: function {} has several definitions of '
>       'Error * local variable: at {}:{} and then at {}:{}'.format(
>           fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>
> // Warn several propagations in control flow.
> @check2 disable optional_qualifier exists@
> identifier fn, _errp;
> position p1, p2;
> @@
>
>  fn(..., Error **_errp, ...)
>  {
>      ...
> (
>      error_propagate_prepend(_errp, ...);@p1
> |
>      error_propagate(_errp, ...);@p1
> )
>      ...
> (
>      error_propagate_prepend(_errp, ...);@p2
> |
>      error_propagate(_errp, ...);@p2
> )
>      ... when any
>  }
>
> @ script:python @
> fn << check2.fn;
> p1 << check2.p1;
> p2 << check2.p2;
> @@
>
> print('Warning: function {} propagates to errp several times in '
>       'one control flow: at {}:{} and then at {}:{}'.format(
>           fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>
> // Convert special case with goto separately.
> // I tried merging this into the following rule the obvious way, but
> // it made Coccinelle hang on block.c
> //
> // Note interesting thing: if we don't do it here, and try to fixup
> // "out: }" things later after all transformations (the rule will be
> // the same, just without error_propagate() call), coccinelle fails to
> // match this "out: }".
> @ disable optional_qualifier@
> identifier fn, rule1.local_err, out;
> symbol errp;
> @@
>
>  fn(..., Error ** ____, ...)
>  {
>      <...
> -    goto out;
> +    return;
>      ...>
> - out:
> -    error_propagate(errp, local_err);
>  }
>
> // Convert most of local_err related stuff.
> //
> // Note, that we update everything related to matched by rule1
> // function name and local_err name. We may match something not
> // related to the pattern matched by rule1. For example, local_err may
> // be defined with the same name in different blocks inside one
> // function, and in one block follow the propagation pattern and in
> // other block doesn't. Or we may have several functions with the same
> // name (for different configurations).
> //
> // Note also that errp-cleaning functions
> //   error_free_errp
> //   error_report_errp
> //   error_reportf_errp
> //   warn_report_errp
> //   warn_reportf_errp
> // are not yet implemented. They must call corresponding Error* -
> // freeing function and then set *errp to NULL, to avoid further
> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
> // For example, error_free_errp may look like this:
> //
> //    void error_free_errp(Error **errp)
> //    {
> //        error_free(*errp);
> //        *errp = NULL;
> //    }
> @ disable optional_qualifier exists@
> identifier fn, rule1.local_err;
> expression list args;
> symbol errp;
> @@
>
>  fn(..., Error ** ____, ...)
>  {
>      <...
> (
> -    Error *local_err = NULL;
> |
>
> // Convert error clearing functions
> (
> -    error_free(local_err);
> +    error_free_errp(errp);
> |
> -    error_report_err(local_err);
> +    error_report_errp(errp);
> |
> -    error_reportf_err(local_err, args);
> +    error_reportf_errp(errp, args);
> |
> -    warn_report_err(local_err);
> +    warn_report_errp(errp);
> |
> -    warn_reportf_err(local_err, args);
> +    warn_reportf_errp(errp, args);
> )
> ?-    local_err = NULL;
>
> |
> -    error_propagate_prepend(errp, local_err, args);
> +    error_prepend(errp, args);
> |
> -    error_propagate(errp, local_err);
> |
> -    &local_err
> +    errp
> )
>      ...>
>  }
>
> // Convert remaining local_err usage. For example, different kinds of
> // error checking in if conditionals. We can't merge this into
> // previous hunk, as this conflicts with other substitutions in it (at
> // least with "- local_err = NULL").
> @ disable optional_qualifier@
> identifier fn, rule1.local_err;
> symbol errp;
> @@
>
>  fn(..., Error ** ____, ...)
>  {
>      <...
> -    local_err
> +    *errp
>      ...>
>  }
>
> // Always use the same pattern for checking error
> @ disable optional_qualifier@
> identifier fn;
> symbol errp;
> @@
>
>  fn(..., Error ** ____, ...)
>  {
>      <...
> -    *errp != NULL
> +    *errp
>      ...>
>  }
>
> // Revert temporary ___ identifier.
> @ disable optional_qualifier@
> identifier fn;
> @@
>
>  fn(..., Error **
> -   ____
> +   errp
>     , ...)
>  {
>      ...
>  }
>
>> +    warn_reportf_errp(errp, args);
>> )
>> ?-    local_err = NULL;
>>
>> |
>> -    error_propagate_prepend(errp, local_err, args);
>> +    error_prepend(errp, args);
>> |
>> -    error_propagate(errp, local_err);
>> |
>> -    &local_err
>> +    errp
>> )
>>       ...>
>>   }
>>
>> // Convert remaining local_err usage. For example, different kinds of
>> // error checking in if conditionals. We can't merge this into
>> // previous hunk, as this conflicts with other substitutions in it (at
>> // least with "- local_err = NULL").
>> @ disable optional_qualifier@
>> identifier fn, rule1.local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    local_err
>> +    *errp
>>       ...>
>>   }
>>
>> // Always use the same pattern for checking error
>> @ disable optional_qualifier@
>> identifier fn;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    *errp != NULL
>> +    *errp
>>       ...>
>>   }
>>
>> // Revert temporary ___ identifier.
>> @ disable optional_qualifier@
>> identifier fn;
>> @@
>>
>>   fn(..., Error **
>> -   ____
>> +   errp
>>      , ...)
>>   {
>>       ...
>>   }
>>
>
> OK, I almost OK with it, the only thing I doubt a bit is the following:
>
> We want to keep rule1.local_err inheritance to keep connection with
> local_err definition.

Yes.

> Interesting, when we have both rule1.fn and rule1.local_err inherited,
> do we inherit them in separate (i.e. all possible combinations of fn
> and local_err symbols from rule1) or do we inherit a pair, i.e. only
> fn/local_err pairs, found by rule1? If the latter is correct, that
> with your script we loss this pair inheritance, and go to all possible
> combinations of fn and local_err from rule1, possibly adding some wrong
> conversion (OK, you've checked that no such cases in current code tree).

The chaining "identifier rule1.FOO" is by name.  It's reliable only as
long as there is exactly one instance of the name.

We already discussed the case of the function name: if there are two
instances of foo(), and rule1 matches only one of them, then we
nevertheless apply the rules chained to rule1 to both.  Because that can
be wrong, you came up with the ___ trick, which chains reliably.

The same issue exists with the variable name: if there are two instances
of @local_err, and rule1 matches only one of them, then we nevertheless
apply the rules chained to rule1 to both.  Can also be wrong.

What are the conditions for "wrong"?

Because the ___ chaining is reliable, we know rule1 matched the
function, i.e. it has a parameter Error **errp, and it has a automatic
variable Error *local_err = NULL.

We're good as long as *all* identifiers @local_err in this function are
declared that way.  This seems quite likely.  It's not certain, though.

Since nested declarations of Error ** variables are rare, we can rely on
review to ensure we transform these functions correctly.

> So, dropping inheritance in check-rules makes sence, as it may match
> (and warn) more interesting cases.
>
> But for other rules, I'd prefere to be safer, and explictly inherit all
> actually inherited identifiers..

I still can't see what chaining by function name in addition to the ___
chaining buys us.

>                                  Still, I feel, we'll never be
> absolutely safe with coccinelle :)

Right, although this particular problem is not really Coccinelle's
fault.  Blindly treating all instances of a certain identifier in a
certain area the same regardless of how they are bound to declarations
is fundamentally unreliable, regardless of your actual tooling.
Vladimir Sementsov-Ogievskiy March 17, 2020, 9:29 a.m. UTC | #15
16.03.2020 11:21, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> On 14.03.2020 00:54, Markus Armbruster wrote:
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>
>>>> 13.03.2020 18:42, Markus Armbruster wrote:
>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>
>>>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>>>> out now as is.
>>>>>>>
>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>>
>>>>>>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>>>>>>> does corresponding changes in code (look for details in
>>>>>>>> include/qapi/error.h)
>>>>>>>>
>>>>>>>> Usage example:
>>>>>>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>>>>      --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>>>>>>      --max-width 80 FILES...
>>>>>>>>
>>>>>>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>>>>>>> ---
>>>>>>>>
>>>>>>>> Cc: Eric Blake <eblake@redhat.com>
>>>>>>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>>>>>>> Cc: Max Reitz <mreitz@redhat.com>
>>>>>>>> Cc: Greg Kurz <groug@kaod.org>
>>>>>>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>>>>>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>>>>>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>>>>>>> Cc: Paul Durrant <paul@xen.org>
>>>>>>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>>>>>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>>>>>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>>>>>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>>>>>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>>>>>>> Cc: Markus Armbruster <armbru@redhat.com>
>>>>>>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>>>>>>> Cc: qemu-devel@nongnu.org
>>>>>>>> Cc: qemu-block@nongnu.org
>>>>>>>> Cc: xen-devel@lists.xenproject.org
>>>>>>>>
>>>>>>>>      scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>>>>>>      include/qapi/error.h                          |   3 +
>>>>>>>>      MAINTAINERS                                   |   1 +
>>>>>>>>      3 files changed, 331 insertions(+)
>>>>>>>>      create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>>>
>>>>>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>>> new file mode 100644
>>>>>>>> index 0000000000..7dac2dcfa4
>>>>>>>> --- /dev/null
>>>>>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>>> @@ -0,0 +1,327 @@
>>>>>>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>>>>>>> +//
>>>>>>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>>>>>>> +//
>>>>>>>> +// This program is free software; you can redistribute it and/or
>>>>>>>> +// modify it under the terms of the GNU General Public License as
>>>>>>>> +// published by the Free Software Foundation; either version 2 of the
>>>>>>>> +// License, or (at your option) any later version.
>>>>>>>> +//
>>>>>>>> +// This program is distributed in the hope that it will be useful,
>>>>>>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>>>>>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>>>>>>> +// GNU General Public License for more details.
>>>>>>>> +//
>>>>>>>> +// You should have received a copy of the GNU General Public License
>>>>>>>> +// along with this program.  If not, see
>>>>>>>> +// <http://www.gnu.org/licenses/>.
>>>>>>>> +//
>>>>>>>> +// Usage example:
>>>>>>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>>>>>>> +//  --no-show-diff --max-width 80 FILES...
>>>>>>>> +//
>>>>>>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>>>>>>> +// than 80, and without this parameter coccinelle may reindent some
>>>>>>>> +// lines which fit into 80 characters but not to coccinelle default,
>>>>>>>> +// which in turn produces extra patch hunks for no reason.
>>>>>>>
>>>>>>> This is about unwanted reformatting of parameter lists due to the ___
>>>>>>> chaining hack.  --max-width 80 makes that less likely, but not
>>>>>>> impossible.
>>>>>>>
>>>>>>> We can search for unwanted reformatting of parameter lists.  I think
>>>>>>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>>>>>>> tree, I get one false positive (not a parameter list), and one hit:
>>>>>>>
>>>>>>>         @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>>>>>>              }
>>>>>>>          }
>>>>>>>
>>>>>>>         -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>>>>>>         +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>>>>>>         +                               Error **errp)
>>>>>>>          {
>>>>>>>         +    ERRP_AUTO_PROPAGATE();
>>>>>>>              int i;
>>>>>>>
>>>>>>>              if (!props) {
>>>>>>>
>>>>>>> Reformatting, but not unwanted.
>>>>>>
>>>>>> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
>>>>>> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.
>>>>>
>>>>> Agree.
>>>>>
>>>>>>>
>>>>>>> The --max-width 80 hack is good enough for me.
>>>>>>>
>>>>>>> It does result in slightly long transformed lines, e.g. this one in
>>>>>>> replication.c:
>>>>>>>
>>>>>>>         @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>>>>>>                  s->mode = REPLICATION_MODE_PRIMARY;
>>>>>>>                  top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>>>>>>                  if (top_id) {
>>>>>>>         -            error_setg(&local_err, "The primary side does not support option top-id");
>>>>>>>         +            error_setg(errp, "The primary side does not support option top-id");
>>>>>>>                      goto fail;
>>>>>>>                  }
>>>>>>>              } else if (!strcmp(mode, "secondary")) {
>>>>>>>
>>>>>>> v8 did break this line (that's how I found it).  However, v9 still
>>>>>>> shortens the line, just not below the target.  All your + lines look
>>>>>>> quite unlikely to lengthen lines.  Let's not worry about this.
>>>>>>>
>>>>>>>> +// Switch unusual Error ** parameter names to errp
>>>>>>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>>>>>>> +//
>>>>>>>> +// Disable optional_qualifier to skip functions with
>>>>>>>> +// "Error *const *errp" parameter.
>>>>>>>> +//
>>>>>>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>>>>>>> +// that signals unusual semantics, and the parameter name may well
>>>>>>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>>>>>>> +//
>>>>>>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>>>>>>> +// error_propagate_prepend().
>>>>>>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>>>>>>> +identifier fn;
>>>>>>>> +identifier _errp != errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(...,
>>>>>>>> +-   Error **_errp
>>>>>>>> ++   Error **errp
>>>>>>>> +    ,...)
>>>>>>>> + {
>>>>>>>> +(
>>>>>>>> +     ... when != assert(_errp && *_errp)
>>>>>>>> +&
>>>>>>>> +     <...
>>>>>>>> +-    _errp
>>>>>>>> ++    errp
>>>>>>>> +     ...>
>>>>>>>> +)
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>>>>>>> +// necessary
>>>>>>>> +//
>>>>>>>> +// Note, that without "when any" the final "..." does not mach
>>>>>>>> +// something matched by previous pattern, i.e. the rule will not match
>>>>>>>> +// double error_prepend in control flow like in
>>>>>>>> +// vfio_set_irq_signaling().
>>>>>>>> +//
>>>>>>>> +// Note, "exists" says that we want apply rule even if it matches not
>>>>>>>> +// on all possible control flows (otherwise, it will not match
>>>>>>>> +// standard pattern when error_propagate() call is in if branch).
>>>>>>>> +@ disable optional_qualifier exists@
>>>>>>>> +identifier fn, local_err;
>>>>>>>> +symbol errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error **errp, ...)
>>>>>>>> + {
>>>>>>>> ++   ERRP_AUTO_PROPAGATE();
>>>>>>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>>>>>>> +(
>>>>>>>> +(
>>>>>>>> +    error_append_hint(errp, ...);
>>>>>>>> +|
>>>>>>>> +    error_prepend(errp, ...);
>>>>>>>> +|
>>>>>>>> +    error_vprepend(errp, ...);
>>>>>>>> +)
>>>>>>>> +    ... when any
>>>>>>>> +|
>>>>>>>> +    Error *local_err = NULL;
>>>>>>>> +    ...
>>>>>>>> +(
>>>>>>>> +    error_propagate_prepend(errp, local_err, ...);
>>>>>>>> +|
>>>>>>>> +    error_propagate(errp, local_err);
>>>>>>>> +)
>>>>>>>> +    ...
>>>>>>>> +)
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +
>>>>>>>> +// Match functions with propagation of local error to errp.
>>>>>>>> +// We want to refer these functions in several following rules, but I
>>>>>>>> +// don't know a proper way to inherit a function, not just its name
>>>>>>>> +// (to not match another functions with same name in following rules).
>>>>>>>> +// Not-proper way is as follows: rename errp parameter in functions
>>>>>>>> +// header and match it in following rules. Rename it back after all
>>>>>>>> +// transformations.
>>>>>>>> +//
>>>>>>>> +// The simplest case of propagation scheme is single definition of
>>>>>>>> +// local_err with at most one error_propagate_prepend or
>>>>>>>> +// error_propagate on each control-flow. Still, we want to match more
>>>>>>>> +// complex schemes too. We'll warn them with help of further rules.
>>>>>>>
>>>>>>> I think what we actually want is to examine instances of this pattern to
>>>>>>> figure out whether and how we want to transform them.  Perhaps:
>>>>>>>
>>>>>>>         // The common case is a single definition of local_err with at most one
>>>>>>>         // error_propagate_prepend() or error_propagate() on each control-flow
>>>>>>>         // path. Instances of this case we convert with this script. Functions
>>>>>>
>>>>>> For me, sounds a bit like "other things we don't convert".
>>>>>> Actually we convert other things too.
>>>>>
>>>>> What other patterns of error propagation do we convert?
>>>>
>>>> Something like in xen_block_device_destroy, why not? Otherwise, it's better to avoid
>>>> matching things like xen_block_device_destroy, not just warn them.
>>>> But I'd prefer to proceed now as is to fit into 5.0.. Too much time already
>>>> spent on this. So, I'm OK with your wording too.
>>>
>>> Let's scratch "Instances of this case we convert with this script."
>>
>> OK
>>
>>>
>>>>>>>         // with multiple definitions or propagates we want to examine
>>>>>>>         // manually. Later rules emit warnings to guide us to them.
>>>>>>>
>>>>>>>> +@rule1 disable optional_qualifier exists@
>>>>>>>> +identifier fn, local_err;
>>>>>>>> +symbol errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error **
>>>>>>>> +-    errp
>>>>>>>> ++    ____
>>>>>>>> +    , ...)
>>>>>>>> + {
>>>>>>>> +     ...
>>>>>>>> +     Error *local_err = NULL;
>>>>>>>> +     ...
>>>>>>>> +(
>>>>>>>> +     error_propagate_prepend(errp, local_err, ...);
>>>>>>>> +|
>>>>>>>> +     error_propagate(errp, local_err);
>>>>>>>> +)
>>>>>>>> +     ...
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +
>>>>>>>> +// Warn several Error * definitions.
>>>>>>>> +@check1 disable optional_qualifier exists@
>>>>>>>> +identifier fn = rule1.fn, local_err, local_err2;
>>>>>>>
>>>>>>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>>>>>>> particular reason for the difference?
>>>>>>
>>>>>> I didn't find other way to ref check1.fn in next python rule. It just don't
>>>>>> work if I write here just rule1.fn.
>>>>>>
>>>>>>>
>>>>>>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>>>>>>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>>>>>>> everywhere, then apply the script to the complete tree, I get the same
>>>>>>> result.
>>>>>>
>>>>>> I think, it's more efficient to reuse names from previous rules. I think it should
>>>>>> work faster (more information, less extra matching).
>>>>>
>>>>> Nope.  With my hacked up script (patch appended) Coccinelle is actually
>>>>> *faster* for the .[ch] touched by this series: with your unmodified
>>>>> script, it takes a bit over 12s on my box, with mine around 7s.  Output
>>>>> is identical.
>>>>>
>>>>> Never guess performance, always measure it :)
>>>>
>>>> Hmm, whole tree results would be better proof
>>>>
>>>>>
>>>>> Two notes on my script:
>>>>>
>>>>> * Unlike yours, it recognizes double-propagation in my test case.
>>>>>      Discussed below.
>>>>>
>>>>> * Its "several definitions of" warning includes positions.  That turned
>>>>>      out to be useless, but I've been too lazy to take that out again.
>>>>>
>>>>>>>
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>> + {
>>>>>>>> +     ...
>>>>>>>> +     Error *local_err = NULL;
>>>>>>>> +     ... when any
>>>>>>>> +     Error *local_err2 = NULL;
>>>>>>>> +     ... when any
>>>>>>>> + }
>>>
>>> This flags functions that have more than one declaration along any
>>> control flow path.  It doesn't flag this one:
>>>
>>>       void gnat(bool b, Error **errp)
>>>       {
>>>           if (b) {
>>>               Error *local_err = NULL;
>>>               foo(arg, &local_err);
>>>               error_propagate(errp, local_err);
>>>           } else {
>>>               Error *local_err = NULL;
>>>               bar(arg, &local_err);
>>>               error_propagate(errp, local_err);
>>>           }
>>>       }
>>>
>>> The Coccinelle script does the right thing for this one regardless.
>>>
>>> I'd prefer to have such functions flagged, too.  But spending time on
>>> convincing Coccinelle to do it for me is not worthwhile; I can simply
>>> search the diff produced by Coccinelle for deletions of declarations
>>> that are not indented exactly four spaces.
>>>
>>> But if we keep this rule, we should adjust its comment
>>>
>>>       // Warn several Error * definitions.
>>>
>>> because it sure suggests it also catches functions like the one I gave
>>> above.
>>
>> Hmm, yes.. We can write "Warn several Error * definitions in _one_
>> control flow (it's not so trivial to match _any_ case with several
>> definitions with coccinelle)" or something like this.
> 
> Ha, "trivial" reminds me of a story.  The math professor, after having
> spent a good chunk of his lecture developing a proof on the blackboad
> turns to the audience to explain why this little part doesn't require
> proof with the words familiar to any math student "and this is trivial."
> Pause, puzzled look...  "Is it trivial?"  Pause, storms out of the
> lecture hall.  A minute or three pass.  Professor comes back beaming,
> "it is trivial!", and proceeds with the proof.
> 
> My point is: it might be trivial with Coccinelle once you know how to do
> it.  We don't.
> 
> Suggest "(can't figure out how to match several definitions regardless
> of control flow)".

Wrong too, because I can:) for example, chaining two rules, catching the
positions of definition and check that they are different.. Or, some
cheating with python script.. That's why I wrote "not trivial",

So, most correct would be "(can't figure out how to simply match several definitions regardless
 > of control flow)".

But again, coccinelle is for matching control flows, so its probably impossible to match such thing..

> 
>>
>>>
>>>>>>>> +
>>>>>>>> +@ script:python @
>>>>>>>> +fn << check1.fn;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> +print('Warning: function {} has several definitions of '
>>>>>>>> +      'Error * local variable'.format(fn))
>>>>>>>> +
>>>>>>>> +// Warn several propagations in control flow.
>>>>>>>> +@check2 disable optional_qualifier exists@
>>>>>>>> +identifier fn = rule1.fn;
>>>>>>>> +symbol errp;
>>>>>>>> +position p1, p2;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>> + {
>>>>>>>> +     ...
>>>>>>>> +(
>>>>>>>> +     error_propagate_prepend(errp, ...);@p1
>>>>>>>> +|
>>>>>>>> +     error_propagate(errp, ...);@p1
>>>>>>>> +)
>>>>>>>> +     ...
>>>>>>>> +(
>>>>>>>> +     error_propagate_prepend(errp, ...);@p2
>>>>>>>> +|
>>>>>>>> +     error_propagate(errp, ...);@p2
>>>>>>>> +)
>>>>>>>> +     ... when any
>>>>>>>> + }
>>>>>>>> +
>>>>>>>
>>>>>>> Hmm, we don't catch the example I used in review of v8:
>>>>>>>
>>>>>>>         extern foo(int, Error **);
>>>>>>>         extern bar(int, Error **);
>>>>>>>
>>>>>>>         void frob(Error **errp)
>>>>>>>         {
>>>>>>>             Error *local_err = NULL;
>>>>>>>             int arg;
>>>>>>>
>>>>>>>             foo(arg, errp);
>>>>>>>             bar(arg, &local_err);
>>>>>>>             error_propagate(errp, local_err);
>>>>>>>             bar(arg + 1, &local_err);
>>>>>>>             error_propagate(errp, local_err);
>>>>>>>         }
>>>>>>>
>>>>>>> I believe this is because rule1 does not match here.
>>>>>>
>>>>>> Yes, rule1 wants at least one code flow with non-doubled propagation.
>>>>>>
>>>>>>>
>>>>>>> If I change the rule as follows, it catches the example:
>>>>>>>
>>>>>>>         @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>>>>>>
>>>>>>>          // Warn several propagations in control flow.
>>>>>>>          @check2 disable optional_qualifier exists@
>>>>>>>         -identifier fn = rule1.fn;
>>>>>>>         -symbol errp;
>>>>>>>         +identifier fn, _errp;
>>>>>>>          position p1, p2;
>>>>>>>          @@
>>>>>>>
>>>>>>>         - fn(..., Error ** ____, ...)
>>>>>>>         + fn(..., Error **_errp, ...)
>>>>>>>           {
>>>>>>>               ...
>>>>>>>          (
>>>>>>>         -     error_propagate_prepend(errp, ...);@p1
>>>>>>>         +     error_propagate_prepend(_errp, ...);@p1
>>>>>>>          |
>>>>>>>         -     error_propagate(errp, ...);@p1
>>>>>>>         +     error_propagate(_errp, ...);@p1
>>>>>>>          )
>>>>>>>               ...
>>>>>>>          (
>>>>>>>         -     error_propagate_prepend(errp, ...);@p2
>>>>>>>         +     error_propagate_prepend(_errp, ...);@p2
>>>>>>>          |
>>>>>>>         -     error_propagate(errp, ...);@p2
>>>>>>>         +     error_propagate(_errp, ...);@p2
>>>>>>>          )
>>>>>>>               ... when any
>>>>>>>           }
>>>>>>>
>>>>>>> To my mild surprise, it still doesn't find anything in our tree.
>>>>>>>
>>>>>>> Should we decouple the previous rule from rule1, too?  I tested the
>>>>>>> following on the whole tree:
>>>>>>
>>>>>> I don't think so. Why to check what we are not going to convert? If we want
>>>>>> to check side things, it's better to do it in other coccinelle script..
>>>>>
>>>>> Misunderstanding?  The rules are still chained together via the ___
>>>>> hack, just not via function name, because that's unreliable and
>>>>> redundant.
>>>>
>>>> Strange.. Then, how can it match something not matched by rule1?
>>>
>>> I think I got confused when I wrote the "Misunderstanding?" paragraph.
>>>
>>> Let me try again.
>>>
>>> First rule check2.
>>>
>>> The common case is a at most one propagation to @errp along any control
>>> flow path.  We trust your Coccinelle script to convert that alright.
>>>
>>> Any other propagation to @errp I want to review.  Whether the script
>>> attempts a conversion or not is unimportant, as long as it points me to
>>> the function to review.
>>>
>>> Rule rule1 matches functions that propagate to @errp once along at least
>>> one control flow path.
>>>
>>> Unchained from rule rule1, rule check2 flags any function that
>>> propagates to @errp multiple times along any control flow path.
>>>
>>> Chained to rule1, it flags only functions that also have a path with
>>> single propagation.
>>>
>>> In other words, the unchained rule flags *all* multi-propagations to
>>> @errp, while the chained rule flags only the ones the script attempts to
>>> convert.  The former is much more useful to me.
>>>
>>> Now rule check1.  It flags functions with multiple declarations along
>>> any control flow path.  Again, chaining it to rule1 restricts it to the
>>> functions we attempt to convert.  Makes it less useful to me.  However,
>>> because my desire to review multiple declarations in function we don't
>>> attempt to convert is lower than my desire to review multiple
>>> propagations to @errp in such functions, chaining check1 is tolerable
>>> for me.  But why chain check1 if we don't chain check2?
>>>
>>
>> OK, let's unchain them.
>>
>>>>
>>>>>
>>>>>>>
>>>>>>>         @@ -136,10 +136,10 @@ symbol errp;
>>>>>>>
>>>>>>>          // Warn several Error * definitions.
>>>>>>>          @check1 disable optional_qualifier exists@
>>>>>>>         -identifier fn = rule1.fn, local_err, local_err2;
>>>>>>>         +identifier fn, _errp, local_err, local_err2;
>>>>>>>          @@
>>>>>>>
>>>>>>>         - fn(..., Error ** ____, ...)
>>>>>>>         + fn(..., Error **_errp, ...)
>>>>>>>           {
>>>>>>>               ...
>>>>>>>               Error *local_err = NULL;
>>>>>>>
>>>>>>> Warnings remain unchanged.
>>>>>>>
>>>>>>>> +@ script:python @
>>>>>>>> +fn << check2.fn;
>>>>>>>> +p1 << check2.p1;
>>>>>>>> +p2 << check2.p2;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> +print('Warning: function {} propagates to errp several times in '
>>>>>>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>>>>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>>>>> +
>>>>>>>> +// Convert special case with goto separately.
>>>>>>>> +// I tried merging this into the following rule the obvious way, but
>>>>>>>> +// it made Coccinelle hang on block.c
>>>>>>>> +//
>>>>>>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>>>>>>> +// "out: }" things later after all transformations (the rule will be
>>>>>>>> +// the same, just without error_propagate() call), coccinelle fails to
>>>>>>>> +// match this "out: }".
>>>>>>>> +@ disable optional_qualifier@
>>>>>>>> +identifier rule1.fn, rule1.local_err, out;
>>>>>>>
>>>>>>> As explained above, I doubt the need for rule1.fn.  We do need
>>>>>>> rule1.local_err to avoid unwanted transformations.  More of the same
>>>>>>> below.
>>>>>>
>>>>>> Logically, I want to inherit from rule1. So why not to stress it by inheriting
>>>>>> fn variable? It's just a correct thing to do.
>>>>>> And I hope it helps coccinelle to work more efficiently.
>>>>>>
>>>>>>>
>>>>>>>> +symbol errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>> + {
>>>>>>>> +     <...
>>>>>>>> +-    goto out;
>>>>>>>> ++    return;
>>>>>>>> +     ...>
>>>>>>>> +- out:
>>>>>>>> +-    error_propagate(errp, local_err);
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +// Convert most of local_err related stuff.
>>>>>>>> +//
>>>>>>>> +// Note, that we update everything related to matched by rule1
>>>>>>>> +// function name and local_err name. We may match something not
>>>>>>>> +// related to the pattern matched by rule1. For example, local_err may
>>>>>>>> +// be defined with the same name in different blocks inside one
>>>>>>>> +// function, and in one block follow the propagation pattern and in
>>>>>>>> +// other block doesn't. Or we may have several functions with the same
>>>>>>>> +// name (for different configurations).
>>>>>>>> +//
>>>>>>>> +// Note also that errp-cleaning functions
>>>>>>>> +//   error_free_errp
>>>>>>>> +//   error_report_errp
>>>>>>>> +//   error_reportf_errp
>>>>>>>> +//   warn_report_errp
>>>>>>>> +//   warn_reportf_errp
>>>>>>>> +// are not yet implemented. They must call corresponding Error* -
>>>>>>>> +// freeing function and then set *errp to NULL, to avoid further
>>>>>>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>>>>>>> +// For example, error_free_errp may look like this:
>>>>>>>> +//
>>>>>>>> +//    void error_free_errp(Error **errp)
>>>>>>>> +//    {
>>>>>>>> +//        error_free(*errp);
>>>>>>>> +//        *errp = NULL;
>>>>>>>> +//    }
>>>>>>>> +@ disable optional_qualifier exists@
>>>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>>>> +expression list args;
>>>>>>>> +symbol errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>> + {
>>>>>>>> +     <...
>>>>>>>> +(
>>>>>>>> +-    Error *local_err = NULL;
>>>>>>>> +|
>>>>>>>> +
>>>>>>>> +// Convert error clearing functions
>>>>>>>> +(
>>>>>>>> +-    error_free(local_err);
>>>>>>>> ++    error_free_errp(errp);
>>>>>>>> +|
>>>>>>>> +-    error_report_err(local_err);
>>>>>>>> ++    error_report_errp(errp);
>>>>>>>> +|
>>>>>>>> +-    error_reportf_err(local_err, args);
>>>>>>>> ++    error_reportf_errp(errp, args);
>>>>>>>> +|
>>>>>>>> +-    warn_report_err(local_err);
>>>>>>>> ++    warn_report_errp(errp);
>>>>>>>> +|
>>>>>>>> +-    warn_reportf_err(local_err, args);
>>>>>>>> ++    warn_reportf_errp(errp, args);
>>>>>>>> +)
>>>>>>>> +?-    local_err = NULL;
>>>>>>>> +
>>>>>>>> +|
>>>>>>>> +-    error_propagate_prepend(errp, local_err, args);
>>>>>>>> ++    error_prepend(errp, args);
>>>>>>>> +|
>>>>>>>> +-    error_propagate(errp, local_err);
>>>>>>>> +|
>>>>>>>> +-    &local_err
>>>>>>>> ++    errp
>>>>>>>> +)
>>>>>>>> +     ...>
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +// Convert remaining local_err usage. For example, different kinds of
>>>>>>>> +// error checking in if conditionals. We can't merge this into
>>>>>>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>>>>>>> +// least with "- local_err = NULL").
>>>>>>>> +@ disable optional_qualifier@
>>>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>>>> +symbol errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>> + {
>>>>>>>> +     <...
>>>>>>>> +-    local_err
>>>>>>>> ++    *errp
>>>>>>>> +     ...>
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +// Always use the same pattern for checking error
>>>>>>>> +@ disable optional_qualifier@
>>>>>>>> +identifier rule1.fn;
>>>>>>>> +symbol errp;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>> + {
>>>>>>>> +     <...
>>>>>>>> +-    *errp != NULL
>>>>>>>> ++    *errp
>>>>>>>> +     ...>
>>>>>>>> + }
>>>>>>>> +
>>>>>>>> +// Revert temporary ___ identifier.
>>>>>>>> +@ disable optional_qualifier@
>>>>>>>> +identifier rule1.fn;
>>>>>>>> +@@
>>>>>>>> +
>>>>>>>> + fn(..., Error **
>>>>>>>> +-   ____
>>>>>>>> ++   errp
>>>>>>>> +    , ...)
>>>>>>>> + {
>>>>>>>> +     ...
>>>>>>>> + }
>>>>>>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>>>>>>> index 30140d9bfe..56c133520d 100644
>>>>>>>> --- a/include/qapi/error.h
>>>>>>>> +++ b/include/qapi/error.h
>>>>>>>> @@ -214,6 +214,9 @@
>>>>>>>>       *         }
>>>>>>>>       *         ...
>>>>>>>>       *     }
>>>>>>>> + *
>>>>>>>> + * For mass-conversion use script
>>>>>>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>>>       */
>>>>>>>>        #ifndef ERROR_H
>>>>>>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>>>>>>> index 857f969aa1..047f1b9714 100644
>>>>>>>> --- a/MAINTAINERS
>>>>>>>> +++ b/MAINTAINERS
>>>>>>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>>>>>>      F: qapi/error.json
>>>>>>>>      F: util/error.c
>>>>>>>>      F: util/qemu-error.c
>>>>>>>> +F: scripts/coccinelle/*err*.cocci
>>>>>>>>        GDB stub
>>>>>>>>      M: Alex Bennée <alex.bennee@linaro.org>
>>>>>>>
>>>>>
>>>>>
>>>>>    From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
>>>>> From: Markus Armbruster <armbru@redhat.com>
>>>>> Date: Fri, 13 Mar 2020 14:27:57 +0100
>>>>> Subject: [PATCH] fixup! scripts: Coccinelle script to use
>>>>>     ERRP_AUTO_PROPAGATE()
>>>>>
>>>>> ---
>>>>>     scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
>>>>>     1 file changed, 20 insertions(+), 17 deletions(-)
>>>>>
>>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>> index 7dac2dcfa4..43b0b0e63b 100644
>>>>> --- a/scripts/coccinelle/auto-propagated-errp.cocci
>>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>> @@ -136,45 +136,48 @@ symbol errp;
>>>>>       // Warn several Error * definitions.
>>>>>     @check1 disable optional_qualifier exists@
>>>>> -identifier fn = rule1.fn, local_err, local_err2;
>>>>> +identifier fn, _errp, local_err, local_err2;
>>>>> +position p1, p2;
>>>>
>>>>
>>>> Hmm, seems like I forget to define ____ as symbol in my patch
>>>
>>> Coccinelle defaults to symbol.
>>
>> But for errp we saw warnings simetimes.
> 
> I believe it warns when you use rely on the symbol default while also
> using it as something else in other rules.
> 
> Feel free to explicitly define it as symbol.
> 
>>>>>     @@
>>>>>     - fn(..., Error ** ____, ...)
>>>>> + fn(..., Error **_errp, ...)
>>>>
>>>> Ahmm.. it will break compilation?
>>>>
>>>> Or, how will it work when _errp defined as meta variable is only in "+..." line? Should it be symbol instead, or just not defined?
>>>
>>> Misunderstanding?  It's a diff between your .cocci and mine.
>>
>> Oops, yes, sorry. Patches to coccinelle scripts are tricky thing.
>>
>>> My version
>>> is
>>>
>>>       // Warn several Error * definitions.
>>>       @check1 disable optional_qualifier exists@
>>>       identifier fn, _errp, local_err, local_err2;
>>>       position p1, p2;
>>>       @@
>>>
>>>        fn(..., Error **_errp, ...)
>>>        {
>>>            ...
>>>            Error *local_err = NULL;@p1
>>>            ... when any
>>>            Error *local_err2 = NULL;@p2
>>>            ... when any
>>>        }
>>>
>>>       @ script:python @
>>>       fn << check1.fn;
>>>       p1 << check1.p1;
>>>       p2 << check1.p2;
>>>       @@
>>>
>>>>>      {
>>>>>          ...
>>>>> -     Error *local_err = NULL;
>>>>> +     Error *local_err = NULL;@p1
>>>>
>>>> Why to do -/+ here? Nothing changed..
>>>>
>>>>>          ... when any
>>>>> -     Error *local_err2 = NULL;
>>>>> +     Error *local_err2 = NULL;@p2
>>>>>          ... when any
>>>>>      }
>>>>>       @ script:python @
>>>>>     fn << check1.fn;
>>>>> +p1 << check1.p1;
>>>>> +p2 << check1.p2;
>>>>>     @@
>>>>>       print('Warning: function {} has several definitions of '
>>>>> -      'Error * local variable'.format(fn))
>>>>> +      'Error * local variable: at {}:{} and then at {}:{}'.format(
>>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>>       // Warn several propagations in control flow.
>>>>>     @check2 disable optional_qualifier exists@
>>>>> -identifier fn = rule1.fn;
>>>>> -symbol errp;
>>>>> +identifier fn, _errp;
>>>>>     position p1, p2;
>>>>>     @@
>>>>>     - fn(..., Error ** ____, ...)
>>>>> + fn(..., Error **_errp, ...)
>>>>>      {
>>>>>          ...
>>>>>     (
>>>>> -     error_propagate_prepend(errp, ...);@p1
>>>>> +     error_propagate_prepend(_errp, ...);@p1
>>>>>     |
>>>>> -     error_propagate(errp, ...);@p1
>>>>> +     error_propagate(_errp, ...);@p1
>>>>>     )
>>>>>          ...
>>>>>     (
>>>>> -     error_propagate_prepend(errp, ...);@p2
>>>>> +     error_propagate_prepend(_errp, ...);@p2
>>>>>     |
>>>>> -     error_propagate(errp, ...);@p2
>>>>> +     error_propagate(_errp, ...);@p2
>>>>>     )
>>>>
>>>> You change some occurrences of errp to _errp, but not all. It breaks compilation.
>>>>
>>>>>          ... when any
>>>>>      }
>>>>> @@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
>>>>>     // the same, just without error_propagate() call), coccinelle fails to
>>>>>     // match this "out: }".
>>>>>     @ disable optional_qualifier@
>>>>> -identifier rule1.fn, rule1.local_err, out;
>>>>> +identifier fn, rule1.local_err, out;
>>>>
>>>> Hmm. If it improves performance it is strange.. But I can live with this change.
>>>>
>>>>>     symbol errp;
>>>>>     @@
>>>>>     @@ -239,7 +242,7 @@ symbol errp;
>>>>>     //        *errp = NULL;
>>>>>     //    }
>>>>>     @ disable optional_qualifier exists@
>>>>> -identifier rule1.fn, rule1.local_err;
>>>>> +identifier fn, rule1.local_err;
>>>>>     expression list args;
>>>>>     symbol errp;
>>>>>     @@
>>>>> @@ -287,7 +290,7 @@ symbol errp;
>>>>>     // previous hunk, as this conflicts with other substitutions in it (at
>>>>>     // least with "- local_err = NULL").
>>>>>     @ disable optional_qualifier@
>>>>> -identifier rule1.fn, rule1.local_err;
>>>>> +identifier fn, rule1.local_err;
>>>>>     symbol errp;
>>>>>     @@
>>>>>     @@ -301,7 +304,7 @@ symbol errp;
>>>>>       // Always use the same pattern for checking error
>>>>>     @ disable optional_qualifier@
>>>>> -identifier rule1.fn;
>>>>> +identifier fn;
>>>>>     symbol errp;
>>>>>     @@
>>>>>     @@ -315,7 +318,7 @@ symbol errp;
>>>>>       // Revert temporary ___ identifier.
>>>>>     @ disable optional_qualifier@
>>>>> -identifier rule1.fn;
>>>>> +identifier fn;
>>>>>     @@
>>>>>        fn(..., Error **
>>>>>
>>>
>>> I append my hacked up version of auto-propagated-errp.cocci.  It
>>> produces the same patch as yours for the complete tree.
>>>
>>>
>>>
>>> // Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>> //
>>> // Copyright (c) 2020 Virtuozzo International GmbH.
>>> //
>>> // This program is free software; you can redistribute it and/or
>>> // modify it under the terms of the GNU General Public License as
>>> // published by the Free Software Foundation; either version 2 of the
>>> // License, or (at your option) any later version.
>>> //
>>> // This program is distributed in the hope that it will be useful,
>>> // but WITHOUT ANY WARRANTY; without even the implied warranty of
>>> // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>> // GNU General Public License for more details.
>>> //
>>> // You should have received a copy of the GNU General Public License
>>> // along with this program.  If not, see
>>> // <http://www.gnu.org/licenses/>.
>>> //
>>> // Usage example:
>>> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>> //  --macro-file scripts/cocci-macro-file.h --in-place \
>>> //  --no-show-diff --max-width 80 FILES...
>>> //
>>> // Note: --max-width 80 is needed because coccinelle default is less
>>> // than 80, and without this parameter coccinelle may reindent some
>>> // lines which fit into 80 characters but not to coccinelle default,
>>> // which in turn produces extra patch hunks for no reason.
>>>
>>> // Switch unusual Error ** parameter names to errp
>>> // (this is necessary to use ERRP_AUTO_PROPAGATE).
>>> //
>>> // Disable optional_qualifier to skip functions with
>>> // "Error *const *errp" parameter.
>>> //
>>> // Skip functions with "assert(_errp && *_errp)" statement, because
>>> // that signals unusual semantics, and the parameter name may well
>>> // serve a purpose. (like nbd_iter_channel_error()).
>>> //
>>> // Skip util/error.c to not touch, for example, error_propagate() and
>>> // error_propagate_prepend().
>>> @ depends on !(file in "util/error.c") disable optional_qualifier@
>>> identifier fn;
>>> identifier _errp != errp;
>>> @@
>>>
>>>    fn(...,
>>> -   Error **_errp
>>> +   Error **errp
>>>       ,...)
>>>    {
>>> (
>>>        ... when != assert(_errp && *_errp)
>>> &
>>>        <...
>>> -    _errp
>>> +    errp
>>>        ...>
>>> )
>>>    }
>>>
>>> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>> // necessary
>>> //
>>> // Note, that without "when any" the final "..." does not mach
>>> // something matched by previous pattern, i.e. the rule will not match
>>> // double error_prepend in control flow like in
>>> // vfio_set_irq_signaling().
>>> //
>>> // Note, "exists" says that we want apply rule even if it matches not
>>> // on all possible control flows (otherwise, it will not match
>>> // standard pattern when error_propagate() call is in if branch).
>>> @ disable optional_qualifier exists@
>>> identifier fn, local_err;
>>> symbol errp;
>>> @@
>>>
>>>    fn(..., Error **errp, ...)
>>>    {
>>> +   ERRP_AUTO_PROPAGATE();
>>>       ...  when != ERRP_AUTO_PROPAGATE();
>>> (
>>> (
>>>       error_append_hint(errp, ...);
>>> |
>>>       error_prepend(errp, ...);
>>> |
>>>       error_vprepend(errp, ...);
>>> )
>>>       ... when any
>>> |
>>>       Error *local_err = NULL;
>>>       ...
>>> (
>>>       error_propagate_prepend(errp, local_err, ...);
>>> |
>>>       error_propagate(errp, local_err);
>>> )
>>>       ...
>>> )
>>>    }
>>>
>>>
>>> // Match functions with propagation of local error to errp.
>>> // We want to refer these functions in several following rules, but I
>>> // don't know a proper way to inherit a function, not just its name
>>> // (to not match another functions with same name in following rules).
>>> // Not-proper way is as follows: rename errp parameter in functions
>>> // header and match it in following rules. Rename it back after all
>>> // transformations.
>>> //
>>> // The simplest case of propagation scheme is single definition of
>>> // local_err with at most one error_propagate_prepend or
>>> // error_propagate on each control-flow. Still, we want to match more
>>> // complex schemes too. We'll warn them with help of further rules.
>>> @rule1 disable optional_qualifier exists@
>>> identifier fn, local_err;
>>> symbol errp;
>>> @@
>>>
>>>    fn(..., Error **
>>> -    errp
>>> +    ____
>>>       , ...)
>>>    {
>>>        ...
>>>        Error *local_err = NULL;
>>>        ...
>>> (
>>>        error_propagate_prepend(errp, local_err, ...);
>>> |
>>>        error_propagate(errp, local_err);
>>> )
>>>        ...
>>>    }
>>>
>>>
>>> // Warn several Error * definitions.
>>> @check1 disable optional_qualifier exists@
>>> identifier fn, _errp, local_err, local_err2;
>>> position p1, p2;
>>> @@
>>>
>>>    fn(..., Error **_errp, ...)
>>>    {
>>>        ...
>>>        Error *local_err = NULL;@p1
>>>        ... when any
>>>        Error *local_err2 = NULL;@p2
>>>        ... when any
>>>    }
>>>
>>> @ script:python @
>>> fn << check1.fn;
>>> p1 << check1.p1;
>>> p2 << check1.p2;
>>> @@
>>>
>>> print('Warning: function {} has several definitions of '
>>>         'Error * local variable: at {}:{} and then at {}:{}'.format(
>>>             fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>
>>> // Warn several propagations in control flow.
>>> @check2 disable optional_qualifier exists@
>>> identifier fn, _errp;
>>> position p1, p2;
>>> @@
>>>
>>>    fn(..., Error **_errp, ...)
>>>    {
>>>        ...
>>> (
>>>        error_propagate_prepend(_errp, ...);@p1
>>> |
>>>        error_propagate(_errp, ...);@p1
>>> )
>>>        ...
>>> (
>>>        error_propagate_prepend(_errp, ...);@p2
>>> |
>>>        error_propagate(_errp, ...);@p2
>>> )
>>>        ... when any
>>>    }
>>>
>>> @ script:python @
>>> fn << check2.fn;
>>> p1 << check2.p1;
>>> p2 << check2.p2;
>>> @@
>>>
>>> print('Warning: function {} propagates to errp several times in '
>>>         'one control flow: at {}:{} and then at {}:{}'.format(
>>>             fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>
>>> // Convert special case with goto separately.
>>> // I tried merging this into the following rule the obvious way, but
>>> // it made Coccinelle hang on block.c
>>> //
>>> // Note interesting thing: if we don't do it here, and try to fixup
>>> // "out: }" things later after all transformations (the rule will be
>>> // the same, just without error_propagate() call), coccinelle fails to
>>> // match this "out: }".
>>> @ disable optional_qualifier@
>>> identifier fn, rule1.local_err, out;
>>> symbol errp;
>>> @@
>>>
>>>    fn(..., Error ** ____, ...)
>>>    {
>>>        <...
>>> -    goto out;
>>> +    return;
>>>        ...>
>>> - out:
>>> -    error_propagate(errp, local_err);
>>>    }
>>>
>>> // Convert most of local_err related stuff.
>>> //
>>> // Note, that we update everything related to matched by rule1
>>> // function name and local_err name. We may match something not
>>> // related to the pattern matched by rule1. For example, local_err may
>>> // be defined with the same name in different blocks inside one
>>> // function, and in one block follow the propagation pattern and in
>>> // other block doesn't. Or we may have several functions with the same
>>> // name (for different configurations).
>>> //
>>> // Note also that errp-cleaning functions
>>> //   error_free_errp
>>> //   error_report_errp
>>> //   error_reportf_errp
>>> //   warn_report_errp
>>> //   warn_reportf_errp
>>> // are not yet implemented. They must call corresponding Error* -
>>> // freeing function and then set *errp to NULL, to avoid further
>>> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>> // For example, error_free_errp may look like this:
>>> //
>>> //    void error_free_errp(Error **errp)
>>> //    {
>>> //        error_free(*errp);
>>> //        *errp = NULL;
>>> //    }
>>> @ disable optional_qualifier exists@
>>> identifier fn, rule1.local_err;
>>> expression list args;
>>> symbol errp;
>>> @@
>>>
>>>    fn(..., Error ** ____, ...)
>>>    {
>>>        <...
>>> (
>>> -    Error *local_err = NULL;
>>> |
>>>
>>> // Convert error clearing functions
>>> (
>>> -    error_free(local_err);
>>> +    error_free_errp(errp);
>>> |
>>> -    error_report_err(local_err);
>>> +    error_report_errp(errp);
>>> |
>>> -    error_reportf_err(local_err, args);
>>> +    error_reportf_errp(errp, args);
>>> |
>>> -    warn_report_err(local_err);
>>> +    warn_report_errp(errp);
>>> |
>>> -    warn_reportf_err(local_err, args);// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>> //
>> // Copyright (c) 2020 Virtuozzo International GmbH.
>> //
>> // This program is free software; you can redistribute it and/or
>> // modify it under the terms of the GNU General Public License as
>> // published by the Free Software Foundation; either version 2 of the
>> // License, or (at your option) any later version.
>> //
>> // This program is distributed in the hope that it will be useful,
>> // but WITHOUT ANY WARRANTY; without even the implied warranty of
>> // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> // GNU General Public License for more details.
>> //
>> // You should have received a copy of the GNU General Public License
>> // along with this program.  If not, see
>> // <http://www.gnu.org/licenses/>.
>> //
>> // Usage example:
>> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>> //  --macro-file scripts/cocci-macro-file.h --in-place \
>> //  --no-show-diff --max-width 80 FILES...
>> //
>> // Note: --max-width 80 is needed because coccinelle default is less
>> // than 80, and without this parameter coccinelle may reindent some
>> // lines which fit into 80 characters but not to coccinelle default,
>> // which in turn produces extra patch hunks for no reason.
>>
>> // Switch unusual Error ** parameter names to errp
>> // (this is necessary to use ERRP_AUTO_PROPAGATE).
>> //
>> // Disable optional_qualifier to skip functions with
>> // "Error *const *errp" parameter.
>> //
>> // Skip functions with "assert(_errp && *_errp)" statement, because
>> // that signals unusual semantics, and the parameter name may well
>> // serve a purpose. (like nbd_iter_channel_error()).
>> //
>> // Skip util/error.c to not touch, for example, error_propagate() and
>> // error_propagate_prepend().
>> @ depends on !(file in "util/error.c") disable optional_qualifier@
>> identifier fn;
>> identifier _errp != errp;
>> @@
>>
>>   fn(...,
>> -   Error **_errp
>> +   Error **errp
>>      ,...)
>>   {
>> (
>>       ... when != assert(_errp && *_errp)
>> &
>>       <...
>> -    _errp
>> +    errp
>>       ...>
>> )
>>   }
>>
>> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>> // necessary
>> //
>> // Note, that without "when any" the final "..." does not mach
>> // something matched by previous pattern, i.e. the rule will not match
>> // double error_prepend in control flow like in
>> // vfio_set_irq_signaling().
>> //
>> // Note, "exists" says that we want apply rule even if it matches not
>> // on all possible control flows (otherwise, it will not match
>> // standard pattern when error_propagate() call is in if branch).
>> @ disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **errp, ...)
>>   {
>> +   ERRP_AUTO_PROPAGATE();
>>      ...  when != ERRP_AUTO_PROPAGATE();
>> (
>> (
>>      error_append_hint(errp, ...);
>> |
>>      error_prepend(errp, ...);
>> |
>>      error_vprepend(errp, ...);
>> )
>>      ... when any
>> |
>>      Error *local_err = NULL;
>>      ...
>> (
>>      error_propagate_prepend(errp, local_err, ...);
>> |
>>      error_propagate(errp, local_err);
>> )
>>      ...
>> )
>>   }
>>
>>
>> // Match functions with propagation of local error to errp.
>> // We want to refer these functions in several following rules, but I
>> // don't know a proper way to inherit a function, not just its name
>> // (to not match another functions with same name in following rules).
>> // Not-proper way is as follows: rename errp parameter in functions
>> // header and match it in following rules. Rename it back after all
>> // transformations.
>> //
>> // The simplest case of propagation scheme is single definition of
>> // local_err with at most one error_propagate_prepend or
>> // error_propagate on each control-flow. Still, we want to match more
>> // complex schemes too. We'll warn them with help of further rules.
>> @rule1 disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **
>> -    errp
>> +    ____
>>      , ...)
>>   {
>>       ...
>>       Error *local_err = NULL;
>>       ...
>> (
>>       error_propagate_prepend(errp, local_err, ...);
>> |
>>       error_propagate(errp, local_err);
>> )
>>       ...
>>   }
>>
>>
>> // Warn several Error * definitions.
>> @check1 disable optional_qualifier exists@
>> identifier fn, _errp, local_err, local_err2;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>>       Error *local_err = NULL;@p1
>>       ... when any
>>       Error *local_err2 = NULL;@p2
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check1.fn;
>> p1 << check1.p1;
>> p2 << check1.p2;
>> @@
>>
>> print('Warning: function {} has several definitions of '
>>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Warn several propagations in control flow.
>> @check2 disable optional_qualifier exists@
>> identifier fn, _errp;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>> (
>>       error_propagate_prepend(_errp, ...);@p1
>> |
>>       error_propagate(_errp, ...);@p1
>> )
>>       ...
>> (
>>       error_propagate_prepend(_errp, ...);@p2
>> |
>>       error_propagate(_errp, ...);@p2
>> )
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check2.fn;
>> p1 << check2.p1;
>> p2 << check2.p2;
>> @@
>>
>> print('Warning: function {} propagates to errp several times in '
>>        'one control flow: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Convert special case with goto separately.
>> // I tried merging this into the following rule the obvious way, but
>> // it made Coccinelle hang on block.c
>> //
>> // Note interesting thing: if we don't do it here, and try to fixup
>> // "out: }" things later after all transformations (the rule will be
>> // the same, just without error_propagate() call), coccinelle fails to
>> // match this "out: }".
>> @ disable optional_qualifier@
>> identifier fn, rule1.local_err, out;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    goto out;
>> +    return;
>>       ...>
>> - out:
>> -    error_propagate(errp, local_err);
>>   }
>>
>> // Convert most of local_err related stuff.
>> //
>> // Note, that we update everything related to matched by rule1
>> // function name and local_err name. We may match something not
>> // related to the pattern matched by rule1. For example, local_err may
>> // be defined with the same name in different blocks inside one
>> // function, and in one block follow the propagation pattern and in
>> // other block doesn't. Or we may have several functions with the same
>> // name (for different configurations).
>> //
>> // Note also that errp-cleaning functions
>> //   error_free_errp
>> //   error_report_errp
>> //   error_reportf_errp
>> //   warn_report_errp
>> //   warn_reportf_errp
>> // are not yet implemented. They must call corresponding Error* -
>> // freeing function and then set *errp to NULL, to avoid further
>> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>> // For example, error_free_errp may look like this:
>> //
>> //    void error_free_errp(Error **errp)
>> //    {
>> //        error_free(*errp);
>> //        *errp = NULL;
>> //    }
>> @ disable optional_qualifier exists@
>> identifier fn, rule1.local_err;
>> expression list args;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> (
>> -    Error *local_err = NULL;
>> |
>>
>> // Convert error clearing functions
>> (
>> -    error_free(local_err);
>> +    error_free_errp(errp);
>> |
>> -    error_report_err(local_err);
>> +    error_report_errp(errp);
>> |
>> -    error_reportf_err(local_err, args);
>> +    error_reportf_errp(errp, args);
>> |
>> -    warn_report_err(local_err);
>> +    warn_report_errp(errp);
>> |
>> -    warn_reportf_err(local_err, args);
>> +    warn_reportf_errp(errp, args);
>> )
>> ?-    local_err = NULL;
>>
>> |
>> -    error_propagate_prepend(errp, local_err, args);
>> +    error_prepend(errp, args);
>> |
>> -    error_propagate(errp, local_err);
>> |
>> -    &local_err
>> +    errp
>> )
>>       ...>
>>   }
>>
>> // Convert remaining local_err usage. For example, different kinds of
>> // error checking in if conditionals. We can't merge this into
>> // previous hunk, as this conflicts with other substitutions in it (at
>> // least with "- local_err = NULL").
>> @ disable optional_qualifier@
>> identifier fn, rule1.local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    local_err
>> +    *errp
>>       ...>
>>   }
>>
>> // Always use the same pattern for checking error
>> @ disable optional_qualifier@
>> identifier fn;
>> symbol errp;
>> @@
>>
>>   fn(..., Error ** ____, ...)
>>   {
>>       <...
>> -    *errp != NULL
>> +    *errp
>>       ...>
>>   }
>>
>> // Revert temporary ___ identifier.
>> @ disable optional_qualifier@
>> identifier fn;
>> @@
>>
>>   fn(..., Error **
>> -   ____
>> +   errp
>>      , ...)
>>   {
>>       ...
>>   }
>>
>>> +    warn_reportf_errp(errp, args);
>>> )
>>> ?-    local_err = NULL;
>>>
>>> |
>>> -    error_propagate_prepend(errp, local_err, args);
>>> +    error_prepend(errp, args);
>>> |
>>> -    error_propagate(errp, local_err);
>>> |
>>> -    &local_err
>>> +    errp
>>> )
>>>        ...>
>>>    }
>>>
>>> // Convert remaining local_err usage. For example, different kinds of
>>> // error checking in if conditionals. We can't merge this into
>>> // previous hunk, as this conflicts with other substitutions in it (at
>>> // least with "- local_err = NULL").
>>> @ disable optional_qualifier@
>>> identifier fn, rule1.local_err;
>>> symbol errp;
>>> @@
>>>
>>>    fn(..., Error ** ____, ...)
>>>    {
>>>        <...
>>> -    local_err
>>> +    *errp
>>>        ...>
>>>    }
>>>
>>> // Always use the same pattern for checking error
>>> @ disable optional_qualifier@
>>> identifier fn;
>>> symbol errp;
>>> @@
>>>
>>>    fn(..., Error ** ____, ...)
>>>    {
>>>        <...
>>> -    *errp != NULL
>>> +    *errp
>>>        ...>
>>>    }
>>>
>>> // Revert temporary ___ identifier.
>>> @ disable optional_qualifier@
>>> identifier fn;
>>> @@
>>>
>>>    fn(..., Error **
>>> -   ____
>>> +   errp
>>>       , ...)
>>>    {
>>>        ...
>>>    }
>>>
>>
>> OK, I almost OK with it, the only thing I doubt a bit is the following:
>>
>> We want to keep rule1.local_err inheritance to keep connection with
>> local_err definition.
> 
> Yes.
> 
>> Interesting, when we have both rule1.fn and rule1.local_err inherited,
>> do we inherit them in separate (i.e. all possible combinations of fn
>> and local_err symbols from rule1) or do we inherit a pair, i.e. only
>> fn/local_err pairs, found by rule1? If the latter is correct, that
>> with your script we loss this pair inheritance, and go to all possible
>> combinations of fn and local_err from rule1, possibly adding some wrong
>> conversion (OK, you've checked that no such cases in current code tree).
> 
> The chaining "identifier rule1.FOO" is by name.  It's reliable only as
> long as there is exactly one instance of the name.
> 
> We already discussed the case of the function name: if there are two
> instances of foo(), and rule1 matches only one of them, then we
> nevertheless apply the rules chained to rule1 to both.  Because that can
> be wrong, you came up with the ___ trick, which chains reliably.
> 
> The same issue exists with the variable name: if there are two instances
> of @local_err, and rule1 matches only one of them, then we nevertheless
> apply the rules chained to rule1 to both.  Can also be wrong.
> 
> What are the conditions for "wrong"?
> 
> Because the ___ chaining is reliable, we know rule1 matched the
> function, i.e. it has a parameter Error **errp, and it has a automatic
> variable Error *local_err = NULL.
> 
> We're good as long as *all* identifiers @local_err in this function are
> declared that way.  This seems quite likely.  It's not certain, though.
> 
> Since nested declarations of Error ** variables are rare, we can rely on
> review to ensure we transform these functions correctly.
> 
>> So, dropping inheritance in check-rules makes sence, as it may match
>> (and warn) more interesting cases.
>>
>> But for other rules, I'd prefere to be safer, and explictly inherit all
>> actually inherited identifiers..
> 
> I still can't see what chaining by function name in addition to the ___
> chaining buys us.

I'll check this thing soon. And resend today.

> 
>>                                   Still, I feel, we'll never be
>> absolutely safe with coccinelle :)
> 
> Right, although this particular problem is not really Coccinelle's
> fault.  Blindly treating all instances of a certain identifier in a
> certain area the same regardless of how they are bound to declarations
> is fundamentally unreliable, regardless of your actual tooling.
> 

Yes, still interesting, can coccinelle do more smart inheritance to match
exactly same object... I think, I need to CC coccinelle mailing list
to the next version
Markus Armbruster March 17, 2020, 10:39 a.m. UTC | #16
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 16.03.2020 11:21, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>
>>> On 14.03.2020 00:54, Markus Armbruster wrote:
>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>
>>>>> 13.03.2020 18:42, Markus Armbruster wrote:
>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>
>>>>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>>>>> out now as is.
>>>>>>>>
>>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
[...]
>>>>>>>>> +@@
>>>>>>>>> +
>>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>>> + {
>>>>>>>>> +     ...
>>>>>>>>> +     Error *local_err = NULL;
>>>>>>>>> +     ... when any
>>>>>>>>> +     Error *local_err2 = NULL;
>>>>>>>>> +     ... when any
>>>>>>>>> + }
>>>>
>>>> This flags functions that have more than one declaration along any
>>>> control flow path.  It doesn't flag this one:
>>>>
>>>>       void gnat(bool b, Error **errp)
>>>>       {
>>>>           if (b) {
>>>>               Error *local_err = NULL;
>>>>               foo(arg, &local_err);
>>>>               error_propagate(errp, local_err);
>>>>           } else {
>>>>               Error *local_err = NULL;
>>>>               bar(arg, &local_err);
>>>>               error_propagate(errp, local_err);
>>>>           }
>>>>       }
>>>>
>>>> The Coccinelle script does the right thing for this one regardless.
>>>>
>>>> I'd prefer to have such functions flagged, too.  But spending time on
>>>> convincing Coccinelle to do it for me is not worthwhile; I can simply
>>>> search the diff produced by Coccinelle for deletions of declarations
>>>> that are not indented exactly four spaces.
>>>>
>>>> But if we keep this rule, we should adjust its comment
>>>>
>>>>       // Warn several Error * definitions.
>>>>
>>>> because it sure suggests it also catches functions like the one I gave
>>>> above.
>>>
>>> Hmm, yes.. We can write "Warn several Error * definitions in _one_
>>> control flow (it's not so trivial to match _any_ case with several
>>> definitions with coccinelle)" or something like this.
>>
>> Ha, "trivial" reminds me of a story.  The math professor, after having
>> spent a good chunk of his lecture developing a proof on the blackboad
>> turns to the audience to explain why this little part doesn't require
>> proof with the words familiar to any math student "and this is trivial."
>> Pause, puzzled look...  "Is it trivial?"  Pause, storms out of the
>> lecture hall.  A minute or three pass.  Professor comes back beaming,
>> "it is trivial!", and proceeds with the proof.
>>
>> My point is: it might be trivial with Coccinelle once you know how to do
>> it.  We don't.
>>
>> Suggest "(can't figure out how to match several definitions regardless
>> of control flow)".
>
> Wrong too, because I can:) for example, chaining two rules, catching the
> positions of definition and check that they are different.. Or, some
> cheating with python script.. That's why I wrote "not trivial",
>
> So, most correct would be "(can't figure out how to simply match several definitions regardless
>> of control flow)".

Works for me.

> But again, coccinelle is for matching control flows, so its probably impossible to match such thing..
[...]
>>> OK, I almost OK with it, the only thing I doubt a bit is the following:
>>>
>>> We want to keep rule1.local_err inheritance to keep connection with
>>> local_err definition.
>>
>> Yes.
>>
>>> Interesting, when we have both rule1.fn and rule1.local_err inherited,
>>> do we inherit them in separate (i.e. all possible combinations of fn
>>> and local_err symbols from rule1) or do we inherit a pair, i.e. only
>>> fn/local_err pairs, found by rule1? If the latter is correct, that
>>> with your script we loss this pair inheritance, and go to all possible
>>> combinations of fn and local_err from rule1, possibly adding some wrong
>>> conversion (OK, you've checked that no such cases in current code tree).
>>
>> The chaining "identifier rule1.FOO" is by name.  It's reliable only as
>> long as there is exactly one instance of the name.
>>
>> We already discussed the case of the function name: if there are two
>> instances of foo(), and rule1 matches only one of them, then we
>> nevertheless apply the rules chained to rule1 to both.  Because that can
>> be wrong, you came up with the ___ trick, which chains reliably.
>>
>> The same issue exists with the variable name: if there are two instances
>> of @local_err, and rule1 matches only one of them, then we nevertheless
>> apply the rules chained to rule1 to both.  Can also be wrong.
>>
>> What are the conditions for "wrong"?
>>
>> Because the ___ chaining is reliable, we know rule1 matched the
>> function, i.e. it has a parameter Error **errp, and it has a automatic
>> variable Error *local_err = NULL.
>>
>> We're good as long as *all* identifiers @local_err in this function are
>> declared that way.  This seems quite likely.  It's not certain, though.
>>
>> Since nested declarations of Error ** variables are rare, we can rely on
>> review to ensure we transform these functions correctly.
>>
>>> So, dropping inheritance in check-rules makes sence, as it may match
>>> (and warn) more interesting cases.
>>>
>>> But for other rules, I'd prefere to be safer, and explictly inherit all
>>> actually inherited identifiers..
>>
>> I still can't see what chaining by function name in addition to the ___
>> chaining buys us.
>
> I'll check this thing soon. And resend today.
>
>>
>>>                                   Still, I feel, we'll never be
>>> absolutely safe with coccinelle :)
>>
>> Right, although this particular problem is not really Coccinelle's
>> fault.  Blindly treating all instances of a certain identifier in a
>> certain area the same regardless of how they are bound to declarations
>> is fundamentally unreliable, regardless of your actual tooling.
>>
>
> Yes, still interesting, can coccinelle do more smart inheritance to match
> exactly same object... I think, I need to CC coccinelle mailing list
> to the next version

I'love to get taught how to chain reliably.
Vladimir Sementsov-Ogievskiy March 17, 2020, 11:35 a.m. UTC | #17
17.03.2020 13:39, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> 16.03.2020 11:21, Markus Armbruster wrote:
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>
>>>> On 14.03.2020 00:54, Markus Armbruster wrote:
>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>
>>>>>> 13.03.2020 18:42, Markus Armbruster wrote:
>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>>
>>>>>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>>>>>> out now as is.
>>>>>>>>>
>>>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> [...]
>>>>>>>>>> +@@
>>>>>>>>>> +
>>>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>>>> + {
>>>>>>>>>> +     ...
>>>>>>>>>> +     Error *local_err = NULL;
>>>>>>>>>> +     ... when any
>>>>>>>>>> +     Error *local_err2 = NULL;
>>>>>>>>>> +     ... when any
>>>>>>>>>> + }
>>>>>
>>>>> This flags functions that have more than one declaration along any
>>>>> control flow path.  It doesn't flag this one:
>>>>>
>>>>>        void gnat(bool b, Error **errp)
>>>>>        {
>>>>>            if (b) {
>>>>>                Error *local_err = NULL;
>>>>>                foo(arg, &local_err);
>>>>>                error_propagate(errp, local_err);
>>>>>            } else {
>>>>>                Error *local_err = NULL;
>>>>>                bar(arg, &local_err);
>>>>>                error_propagate(errp, local_err);
>>>>>            }
>>>>>        }
>>>>>
>>>>> The Coccinelle script does the right thing for this one regardless.
>>>>>
>>>>> I'd prefer to have such functions flagged, too.  But spending time on
>>>>> convincing Coccinelle to do it for me is not worthwhile; I can simply
>>>>> search the diff produced by Coccinelle for deletions of declarations
>>>>> that are not indented exactly four spaces.
>>>>>
>>>>> But if we keep this rule, we should adjust its comment
>>>>>
>>>>>        // Warn several Error * definitions.
>>>>>
>>>>> because it sure suggests it also catches functions like the one I gave
>>>>> above.
>>>>
>>>> Hmm, yes.. We can write "Warn several Error * definitions in _one_
>>>> control flow (it's not so trivial to match _any_ case with several
>>>> definitions with coccinelle)" or something like this.
>>>
>>> Ha, "trivial" reminds me of a story.  The math professor, after having
>>> spent a good chunk of his lecture developing a proof on the blackboad
>>> turns to the audience to explain why this little part doesn't require
>>> proof with the words familiar to any math student "and this is trivial."
>>> Pause, puzzled look...  "Is it trivial?"  Pause, storms out of the
>>> lecture hall.  A minute or three pass.  Professor comes back beaming,
>>> "it is trivial!", and proceeds with the proof.
>>>
>>> My point is: it might be trivial with Coccinelle once you know how to do
>>> it.  We don't.
>>>
>>> Suggest "(can't figure out how to match several definitions regardless
>>> of control flow)".
>>
>> Wrong too, because I can:) for example, chaining two rules, catching the
>> positions of definition and check that they are different.. Or, some
>> cheating with python script.. That's why I wrote "not trivial",
>>
>> So, most correct would be "(can't figure out how to simply match several definitions regardless
>>> of control flow)".
> 
> Works for me.
> 
>> But again, coccinelle is for matching control flows, so its probably impossible to match such thing..
> [...]
>>>> OK, I almost OK with it, the only thing I doubt a bit is the following:
>>>>
>>>> We want to keep rule1.local_err inheritance to keep connection with
>>>> local_err definition.
>>>
>>> Yes.
>>>
>>>> Interesting, when we have both rule1.fn and rule1.local_err inherited,
>>>> do we inherit them in separate (i.e. all possible combinations of fn
>>>> and local_err symbols from rule1) or do we inherit a pair, i.e. only
>>>> fn/local_err pairs, found by rule1? If the latter is correct, that
>>>> with your script we loss this pair inheritance, and go to all possible
>>>> combinations of fn and local_err from rule1, possibly adding some wrong
>>>> conversion (OK, you've checked that no such cases in current code tree).
>>>
>>> The chaining "identifier rule1.FOO" is by name.  It's reliable only as
>>> long as there is exactly one instance of the name.
>>>
>>> We already discussed the case of the function name: if there are two
>>> instances of foo(), and rule1 matches only one of them, then we
>>> nevertheless apply the rules chained to rule1 to both.  Because that can
>>> be wrong, you came up with the ___ trick, which chains reliably.
>>>
>>> The same issue exists with the variable name: if there are two instances
>>> of @local_err, and rule1 matches only one of them, then we nevertheless
>>> apply the rules chained to rule1 to both.  Can also be wrong.
>>>
>>> What are the conditions for "wrong"?
>>>
>>> Because the ___ chaining is reliable, we know rule1 matched the
>>> function, i.e. it has a parameter Error **errp, and it has a automatic
>>> variable Error *local_err = NULL.
>>>
>>> We're good as long as *all* identifiers @local_err in this function are
>>> declared that way.  This seems quite likely.  It's not certain, though.
>>>
>>> Since nested declarations of Error ** variables are rare, we can rely on
>>> review to ensure we transform these functions correctly.
>>>
>>>> So, dropping inheritance in check-rules makes sence, as it may match
>>>> (and warn) more interesting cases.
>>>>
>>>> But for other rules, I'd prefere to be safer, and explictly inherit all
>>>> actually inherited identifiers..
>>>
>>> I still can't see what chaining by function name in addition to the ___
>>> chaining buys us.
>>
>> I'll check this thing soon. And resend today.

Checked.

Yes, it inherits pair of fn and local_err, and it definitely makes sense. It more stable.

Consider the following example:

# cat a.c
int f1(Error **errp)
{
     Error *err1 = NULL;
     int err2 = 0;

     error_propagate(errp, err1);

     return err2;
}

int f2(Error **errp)
{
     Error *err2 = NULL;
     int err1 = 0;

     error_propagate(errp, err2);

     return err1;
}


My script works correct and produces this change:
--- a.c
+++ /tmp/cocci-output-1753-10842a-a.c
@@ -1,19 +1,15 @@
  int f1(Error **errp)
  {
-    Error *err1 = NULL;
+    ERRP_AUTO_PROPAGATE();
      int err2 = 0;

-    error_propagate(errp, err1);
-
      return err2;
  }

  int f2(Error **errp)
  {
-    Error *err2 = NULL;
+    ERRP_AUTO_PROPAGATE();
      int err1 = 0;

-    error_propagate(errp, err2);
-
      return err1;
  }


But yours script is caught:
--- a.c
+++ /tmp/cocci-output-1814-b9b681-a.c
@@ -1,19 +1,15 @@
  int f1(Error **errp)
  {
-    Error *err1 = NULL;
+    ERRP_AUTO_PROPAGATE();
      int err2 = 0;

-    error_propagate(errp, err1);
-
-    return err2;
+    return *errp;
  }

  int f2(Error **errp)
  {
-    Error *err2 = NULL;
+    ERRP_AUTO_PROPAGATE();
      int err1 = 0;

-    error_propagate(errp, err2);
-
-    return err1;
+    return *errp;
  }


- see, it touches err1, which is unrelated to Error in f2. Hmm, interesting that it doesn't want to convert err1 declaration:)

- this is because relation between local_err and fn is lost.

So, understanding that there no such cases in the whole tree, and even if your patch works faster on the whole tree, I still don't want to drop inheritance, because it's just a correct thing to do. Yes, we've added ____ helper. It helps to avoid some problems. Pair-inheritance helps to avoid another problems. I understand, that there still may other, not-covered problems, but better to be as safe as possible. And inheritance here is native and correct thing to do, even with our ____ additional helper. What do you think?

>>
>>>
>>>>                                    Still, I feel, we'll never be
>>>> absolutely safe with coccinelle :)
>>>
>>> Right, although this particular problem is not really Coccinelle's
>>> fault.  Blindly treating all instances of a certain identifier in a
>>> certain area the same regardless of how they are bound to declarations
>>> is fundamentally unreliable, regardless of your actual tooling.
>>>
>>
>> Yes, still interesting, can coccinelle do more smart inheritance to match
>> exactly same object... I think, I need to CC coccinelle mailing list
>> to the next version
> 
> I'love to get taught how to chain reliably.
>
Vladimir Sementsov-Ogievskiy March 17, 2020, 1:54 p.m. UTC | #18
14.03.2020 0:54, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> 13.03.2020 18:42, Markus Armbruster wrote:
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>
>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>> out now as is.
>>>>>
>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>
>>>>>> Script adds ERRP_AUTO_PROPAGATE macro invocation where appropriate and
>>>>>> does corresponding changes in code (look for details in
>>>>>> include/qapi/error.h)
>>>>>>
>>>>>> Usage example:
>>>>>> spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>>     --macro-file scripts/cocci-macro-file.h --in-place --no-show-diff \
>>>>>>     --max-width 80 FILES...
>>>>>>
>>>>>> Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
>>>>>> ---
>>>>>>
>>>>>> Cc: Eric Blake <eblake@redhat.com>
>>>>>> Cc: Kevin Wolf <kwolf@redhat.com>
>>>>>> Cc: Max Reitz <mreitz@redhat.com>
>>>>>> Cc: Greg Kurz <groug@kaod.org>
>>>>>> Cc: Christian Schoenebeck <qemu_oss@crudebyte.com>
>>>>>> Cc: Stefano Stabellini <sstabellini@kernel.org>
>>>>>> Cc: Anthony Perard <anthony.perard@citrix.com>
>>>>>> Cc: Paul Durrant <paul@xen.org>
>>>>>> Cc: Stefan Hajnoczi <stefanha@redhat.com>
>>>>>> Cc: "Philippe Mathieu-Daudé" <philmd@redhat.com>
>>>>>> Cc: Laszlo Ersek <lersek@redhat.com>
>>>>>> Cc: Gerd Hoffmann <kraxel@redhat.com>
>>>>>> Cc: Stefan Berger <stefanb@linux.ibm.com>
>>>>>> Cc: Markus Armbruster <armbru@redhat.com>
>>>>>> Cc: Michael Roth <mdroth@linux.vnet.ibm.com>
>>>>>> Cc: qemu-devel@nongnu.org
>>>>>> Cc: qemu-block@nongnu.org
>>>>>> Cc: xen-devel@lists.xenproject.org
>>>>>>
>>>>>>     scripts/coccinelle/auto-propagated-errp.cocci | 327 ++++++++++++++++++
>>>>>>     include/qapi/error.h                          |   3 +
>>>>>>     MAINTAINERS                                   |   1 +
>>>>>>     3 files changed, 331 insertions(+)
>>>>>>     create mode 100644 scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>
>>>>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>> new file mode 100644
>>>>>> index 0000000000..7dac2dcfa4
>>>>>> --- /dev/null
>>>>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>>>>> @@ -0,0 +1,327 @@
>>>>>> +// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
>>>>>> +//
>>>>>> +// Copyright (c) 2020 Virtuozzo International GmbH.
>>>>>> +//
>>>>>> +// This program is free software; you can redistribute it and/or
>>>>>> +// modify it under the terms of the GNU General Public License as
>>>>>> +// published by the Free Software Foundation; either version 2 of the
>>>>>> +// License, or (at your option) any later version.
>>>>>> +//
>>>>>> +// This program is distributed in the hope that it will be useful,
>>>>>> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
>>>>>> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>>>>>> +// GNU General Public License for more details.
>>>>>> +//
>>>>>> +// You should have received a copy of the GNU General Public License
>>>>>> +// along with this program.  If not, see
>>>>>> +// <http://www.gnu.org/licenses/>.
>>>>>> +//
>>>>>> +// Usage example:
>>>>>> +// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
>>>>>> +//  --macro-file scripts/cocci-macro-file.h --in-place \
>>>>>> +//  --no-show-diff --max-width 80 FILES...
>>>>>> +//
>>>>>> +// Note: --max-width 80 is needed because coccinelle default is less
>>>>>> +// than 80, and without this parameter coccinelle may reindent some
>>>>>> +// lines which fit into 80 characters but not to coccinelle default,
>>>>>> +// which in turn produces extra patch hunks for no reason.
>>>>>
>>>>> This is about unwanted reformatting of parameter lists due to the ___
>>>>> chaining hack.  --max-width 80 makes that less likely, but not
>>>>> impossible.
>>>>>
>>>>> We can search for unwanted reformatting of parameter lists.  I think
>>>>> grepping diffs for '^\+.*Error \*\*' should do the trick.  For the whole
>>>>> tree, I get one false positive (not a parameter list), and one hit:
>>>>>
>>>>>        @@ -388,8 +388,10 @@ static void object_post_init_with_type(O
>>>>>             }
>>>>>         }
>>>>>
>>>>>        -void object_apply_global_props(Object *obj, const GPtrArray *props, Error **errp)
>>>>>        +void object_apply_global_props(Object *obj, const GPtrArray *props,
>>>>>        +                               Error **errp)
>>>>>         {
>>>>>        +    ERRP_AUTO_PROPAGATE();
>>>>>             int i;
>>>>>
>>>>>             if (!props) {
>>>>>
>>>>> Reformatting, but not unwanted.
>>>>
>>>> Yes, I saw it. This line is 81 character length, so it's OK to fix it in one hunk with
>>>> ERRP_AUTO_PROPAGATE addition even for non-automatic patch.
>>>
>>> Agree.
>>>
>>>>>
>>>>> The --max-width 80 hack is good enough for me.
>>>>>
>>>>> It does result in slightly long transformed lines, e.g. this one in
>>>>> replication.c:
>>>>>
>>>>>        @@ -113,7 +113,7 @@ static int replication_open(BlockDriverS
>>>>>                 s->mode = REPLICATION_MODE_PRIMARY;
>>>>>                 top_id = qemu_opt_get(opts, REPLICATION_TOP_ID);
>>>>>                 if (top_id) {
>>>>>        -            error_setg(&local_err, "The primary side does not support option top-id");
>>>>>        +            error_setg(errp, "The primary side does not support option top-id");
>>>>>                     goto fail;
>>>>>                 }
>>>>>             } else if (!strcmp(mode, "secondary")) {
>>>>>
>>>>> v8 did break this line (that's how I found it).  However, v9 still
>>>>> shortens the line, just not below the target.  All your + lines look
>>>>> quite unlikely to lengthen lines.  Let's not worry about this.
>>>>>
>>>>>> +// Switch unusual Error ** parameter names to errp
>>>>>> +// (this is necessary to use ERRP_AUTO_PROPAGATE).
>>>>>> +//
>>>>>> +// Disable optional_qualifier to skip functions with
>>>>>> +// "Error *const *errp" parameter.
>>>>>> +//
>>>>>> +// Skip functions with "assert(_errp && *_errp)" statement, because
>>>>>> +// that signals unusual semantics, and the parameter name may well
>>>>>> +// serve a purpose. (like nbd_iter_channel_error()).
>>>>>> +//
>>>>>> +// Skip util/error.c to not touch, for example, error_propagate() and
>>>>>> +// error_propagate_prepend().
>>>>>> +@ depends on !(file in "util/error.c") disable optional_qualifier@
>>>>>> +identifier fn;
>>>>>> +identifier _errp != errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(...,
>>>>>> +-   Error **_errp
>>>>>> ++   Error **errp
>>>>>> +    ,...)
>>>>>> + {
>>>>>> +(
>>>>>> +     ... when != assert(_errp && *_errp)
>>>>>> +&
>>>>>> +     <...
>>>>>> +-    _errp
>>>>>> ++    errp
>>>>>> +     ...>
>>>>>> +)
>>>>>> + }
>>>>>> +
>>>>>> +// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
>>>>>> +// necessary
>>>>>> +//
>>>>>> +// Note, that without "when any" the final "..." does not mach
>>>>>> +// something matched by previous pattern, i.e. the rule will not match
>>>>>> +// double error_prepend in control flow like in
>>>>>> +// vfio_set_irq_signaling().
>>>>>> +//
>>>>>> +// Note, "exists" says that we want apply rule even if it matches not
>>>>>> +// on all possible control flows (otherwise, it will not match
>>>>>> +// standard pattern when error_propagate() call is in if branch).
>>>>>> +@ disable optional_qualifier exists@
>>>>>> +identifier fn, local_err;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error **errp, ...)
>>>>>> + {
>>>>>> ++   ERRP_AUTO_PROPAGATE();
>>>>>> +    ...  when != ERRP_AUTO_PROPAGATE();
>>>>>> +(
>>>>>> +(
>>>>>> +    error_append_hint(errp, ...);
>>>>>> +|
>>>>>> +    error_prepend(errp, ...);
>>>>>> +|
>>>>>> +    error_vprepend(errp, ...);
>>>>>> +)
>>>>>> +    ... when any
>>>>>> +|
>>>>>> +    Error *local_err = NULL;
>>>>>> +    ...
>>>>>> +(
>>>>>> +    error_propagate_prepend(errp, local_err, ...);
>>>>>> +|
>>>>>> +    error_propagate(errp, local_err);
>>>>>> +)
>>>>>> +    ...
>>>>>> +)
>>>>>> + }
>>>>>> +
>>>>>> +
>>>>>> +// Match functions with propagation of local error to errp.
>>>>>> +// We want to refer these functions in several following rules, but I
>>>>>> +// don't know a proper way to inherit a function, not just its name
>>>>>> +// (to not match another functions with same name in following rules).
>>>>>> +// Not-proper way is as follows: rename errp parameter in functions
>>>>>> +// header and match it in following rules. Rename it back after all
>>>>>> +// transformations.
>>>>>> +//
>>>>>> +// The simplest case of propagation scheme is single definition of
>>>>>> +// local_err with at most one error_propagate_prepend or
>>>>>> +// error_propagate on each control-flow. Still, we want to match more
>>>>>> +// complex schemes too. We'll warn them with help of further rules.
>>>>>
>>>>> I think what we actually want is to examine instances of this pattern to
>>>>> figure out whether and how we want to transform them.  Perhaps:
>>>>>
>>>>>        // The common case is a single definition of local_err with at most one
>>>>>        // error_propagate_prepend() or error_propagate() on each control-flow
>>>>>        // path. Instances of this case we convert with this script. Functions
>>>>
>>>> For me, sounds a bit like "other things we don't convert".
>>>> Actually we convert other things too.
>>>
>>> What other patterns of error propagation do we convert?
>>
>> Something like in xen_block_device_destroy, why not? Otherwise, it's better to avoid
>> matching things like xen_block_device_destroy, not just warn them.
>> But I'd prefer to proceed now as is to fit into 5.0.. Too much time already
>> spent on this. So, I'm OK with your wording too.
> 
> Let's scratch "Instances of this case we convert with this script."
> 
>>>>>        // with multiple definitions or propagates we want to examine
>>>>>        // manually. Later rules emit warnings to guide us to them.
>>>>>
>>>>>> +@rule1 disable optional_qualifier exists@
>>>>>> +identifier fn, local_err;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error **
>>>>>> +-    errp
>>>>>> ++    ____
>>>>>> +    , ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> +     Error *local_err = NULL;
>>>>>> +     ...
>>>>>> +(
>>>>>> +     error_propagate_prepend(errp, local_err, ...);
>>>>>> +|
>>>>>> +     error_propagate(errp, local_err);
>>>>>> +)
>>>>>> +     ...
>>>>>> + }
>>>>>> +
>>>>>> +
>>>>>> +// Warn several Error * definitions.
>>>>>> +@check1 disable optional_qualifier exists@
>>>>>> +identifier fn = rule1.fn, local_err, local_err2;
>>>>>
>>>>> Elsewhere, you use just rule.fn instead of fn = rule1.fn.  Any
>>>>> particular reason for the difference?
>>>>
>>>> I didn't find other way to ref check1.fn in next python rule. It just don't
>>>> work if I write here just rule1.fn.
>>>>
>>>>>
>>>>> With the ___ chaining hack, I doubt we still need "= rule1.fn" or
>>>>> "rule1.fn".  If I replace "fn = rule1.fn" and "rule.fn" by just "fn"
>>>>> everywhere, then apply the script to the complete tree, I get the same
>>>>> result.
>>>>
>>>> I think, it's more efficient to reuse names from previous rules. I think it should
>>>> work faster (more information, less extra matching).
>>>
>>> Nope.  With my hacked up script (patch appended) Coccinelle is actually
>>> *faster* for the .[ch] touched by this series: with your unmodified
>>> script, it takes a bit over 12s on my box, with mine around 7s.  Output
>>> is identical.
>>>
>>> Never guess performance, always measure it :)
>>
>> Hmm, whole tree results would be better proof
>>
>>>
>>> Two notes on my script:
>>>
>>> * Unlike yours, it recognizes double-propagation in my test case.
>>>     Discussed below.
>>>
>>> * Its "several definitions of" warning includes positions.  That turned
>>>     out to be useless, but I've been too lazy to take that out again.
>>>
>>>>>
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> +     Error *local_err = NULL;
>>>>>> +     ... when any
>>>>>> +     Error *local_err2 = NULL;
>>>>>> +     ... when any
>>>>>> + }
> 
> This flags functions that have more than one declaration along any
> control flow path.  It doesn't flag this one:
> 
>      void gnat(bool b, Error **errp)
>      {
>          if (b) {
>              Error *local_err = NULL;
>              foo(arg, &local_err);
>              error_propagate(errp, local_err);
>          } else {
>              Error *local_err = NULL;
>              bar(arg, &local_err);
>              error_propagate(errp, local_err);
>          }
>      }
> 
> The Coccinelle script does the right thing for this one regardless.
> 
> I'd prefer to have such functions flagged, too.  But spending time on
> convincing Coccinelle to do it for me is not worthwhile; I can simply
> search the diff produced by Coccinelle for deletions of declarations
> that are not indented exactly four spaces.
> 
> But if we keep this rule, we should adjust its comment
> 
>      // Warn several Error * definitions.
> 
> because it sure suggests it also catches functions like the one I gave
> above.
> 
>>>>>> +
>>>>>> +@ script:python @
>>>>>> +fn << check1.fn;
>>>>>> +@@
>>>>>> +
>>>>>> +print('Warning: function {} has several definitions of '
>>>>>> +      'Error * local variable'.format(fn))
>>>>>> +
>>>>>> +// Warn several propagations in control flow.
>>>>>> +@check2 disable optional_qualifier exists@
>>>>>> +identifier fn = rule1.fn;
>>>>>> +symbol errp;
>>>>>> +position p1, p2;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> +(
>>>>>> +     error_propagate_prepend(errp, ...);@p1
>>>>>> +|
>>>>>> +     error_propagate(errp, ...);@p1
>>>>>> +)
>>>>>> +     ...
>>>>>> +(
>>>>>> +     error_propagate_prepend(errp, ...);@p2
>>>>>> +|
>>>>>> +     error_propagate(errp, ...);@p2
>>>>>> +)
>>>>>> +     ... when any
>>>>>> + }
>>>>>> +
>>>>>
>>>>> Hmm, we don't catch the example I used in review of v8:
>>>>>
>>>>>        extern foo(int, Error **);
>>>>>        extern bar(int, Error **);
>>>>>
>>>>>        void frob(Error **errp)
>>>>>        {
>>>>>            Error *local_err = NULL;
>>>>>            int arg;
>>>>>
>>>>>            foo(arg, errp);
>>>>>            bar(arg, &local_err);
>>>>>            error_propagate(errp, local_err);
>>>>>            bar(arg + 1, &local_err);
>>>>>            error_propagate(errp, local_err);
>>>>>        }
>>>>>
>>>>> I believe this is because rule1 does not match here.
>>>>
>>>> Yes, rule1 wants at least one code flow with non-doubled propagation.
>>>>
>>>>>
>>>>> If I change the rule as follows, it catches the example:
>>>>>
>>>>>        @@ -157,24 +157,23 @@ print('Warning: function {} has several definitions of '
>>>>>
>>>>>         // Warn several propagations in control flow.
>>>>>         @check2 disable optional_qualifier exists@
>>>>>        -identifier fn = rule1.fn;
>>>>>        -symbol errp;
>>>>>        +identifier fn, _errp;
>>>>>         position p1, p2;
>>>>>         @@
>>>>>
>>>>>        - fn(..., Error ** ____, ...)
>>>>>        + fn(..., Error **_errp, ...)
>>>>>          {
>>>>>              ...
>>>>>         (
>>>>>        -     error_propagate_prepend(errp, ...);@p1
>>>>>        +     error_propagate_prepend(_errp, ...);@p1
>>>>>         |
>>>>>        -     error_propagate(errp, ...);@p1
>>>>>        +     error_propagate(_errp, ...);@p1
>>>>>         )
>>>>>              ...
>>>>>         (
>>>>>        -     error_propagate_prepend(errp, ...);@p2
>>>>>        +     error_propagate_prepend(_errp, ...);@p2
>>>>>         |
>>>>>        -     error_propagate(errp, ...);@p2
>>>>>        +     error_propagate(_errp, ...);@p2
>>>>>         )
>>>>>              ... when any
>>>>>          }
>>>>>
>>>>> To my mild surprise, it still doesn't find anything in our tree.
>>>>>
>>>>> Should we decouple the previous rule from rule1, too?  I tested the
>>>>> following on the whole tree:
>>>>
>>>> I don't think so. Why to check what we are not going to convert? If we want
>>>> to check side things, it's better to do it in other coccinelle script..
>>>
>>> Misunderstanding?  The rules are still chained together via the ___
>>> hack, just not via function name, because that's unreliable and
>>> redundant.
>>
>> Strange.. Then, how can it match something not matched by rule1?
> 
> I think I got confused when I wrote the "Misunderstanding?" paragraph.
> 
> Let me try again.
> 
> First rule check2.
> 
> The common case is a at most one propagation to @errp along any control
> flow path.  We trust your Coccinelle script to convert that alright.
> 
> Any other propagation to @errp I want to review.  Whether the script
> attempts a conversion or not is unimportant, as long as it points me to
> the function to review.
> 
> Rule rule1 matches functions that propagate to @errp once along at least
> one control flow path.
> 
> Unchained from rule rule1, rule check2 flags any function that
> propagates to @errp multiple times along any control flow path.
> 
> Chained to rule1, it flags only functions that also have a path with
> single propagation.
> 
> In other words, the unchained rule flags *all* multi-propagations to
> @errp, while the chained rule flags only the ones the script attempts to
> convert.  The former is much more useful to me.
> 
> Now rule check1.  It flags functions with multiple declarations along
> any control flow path.  Again, chaining it to rule1 restricts it to the
> functions we attempt to convert.  Makes it less useful to me.  However,
> because my desire to review multiple declarations in function we don't
> attempt to convert is lower than my desire to review multiple
> propagations to @errp in such functions, chaining check1 is tolerable
> for me.  But why chain check1 if we don't chain check2?
> 
>>
>>>
>>>>>
>>>>>        @@ -136,10 +136,10 @@ symbol errp;
>>>>>
>>>>>         // Warn several Error * definitions.
>>>>>         @check1 disable optional_qualifier exists@
>>>>>        -identifier fn = rule1.fn, local_err, local_err2;
>>>>>        +identifier fn, _errp, local_err, local_err2;
>>>>>         @@
>>>>>
>>>>>        - fn(..., Error ** ____, ...)
>>>>>        + fn(..., Error **_errp, ...)
>>>>>          {
>>>>>              ...
>>>>>              Error *local_err = NULL;
>>>>>
>>>>> Warnings remain unchanged.
>>>>>
>>>>>> +@ script:python @
>>>>>> +fn << check2.fn;
>>>>>> +p1 << check2.p1;
>>>>>> +p2 << check2.p2;
>>>>>> +@@
>>>>>> +
>>>>>> +print('Warning: function {} propagates to errp several times in '
>>>>>> +      'one control flow: at {}:{} and then at {}:{}'.format(
>>>>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>>>> +
>>>>>> +// Convert special case with goto separately.
>>>>>> +// I tried merging this into the following rule the obvious way, but
>>>>>> +// it made Coccinelle hang on block.c
>>>>>> +//
>>>>>> +// Note interesting thing: if we don't do it here, and try to fixup
>>>>>> +// "out: }" things later after all transformations (the rule will be
>>>>>> +// the same, just without error_propagate() call), coccinelle fails to
>>>>>> +// match this "out: }".
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn, rule1.local_err, out;
>>>>>
>>>>> As explained above, I doubt the need for rule1.fn.  We do need
>>>>> rule1.local_err to avoid unwanted transformations.  More of the same
>>>>> below.
>>>>
>>>> Logically, I want to inherit from rule1. So why not to stress it by inheriting
>>>> fn variable? It's just a correct thing to do.
>>>> And I hope it helps coccinelle to work more efficiently.
>>>>
>>>>>
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +-    goto out;
>>>>>> ++    return;
>>>>>> +     ...>
>>>>>> +- out:
>>>>>> +-    error_propagate(errp, local_err);
>>>>>> + }
>>>>>> +
>>>>>> +// Convert most of local_err related stuff.
>>>>>> +//
>>>>>> +// Note, that we update everything related to matched by rule1
>>>>>> +// function name and local_err name. We may match something not
>>>>>> +// related to the pattern matched by rule1. For example, local_err may
>>>>>> +// be defined with the same name in different blocks inside one
>>>>>> +// function, and in one block follow the propagation pattern and in
>>>>>> +// other block doesn't. Or we may have several functions with the same
>>>>>> +// name (for different configurations).
>>>>>> +//
>>>>>> +// Note also that errp-cleaning functions
>>>>>> +//   error_free_errp
>>>>>> +//   error_report_errp
>>>>>> +//   error_reportf_errp
>>>>>> +//   warn_report_errp
>>>>>> +//   warn_reportf_errp
>>>>>> +// are not yet implemented. They must call corresponding Error* -
>>>>>> +// freeing function and then set *errp to NULL, to avoid further
>>>>>> +// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
>>>>>> +// For example, error_free_errp may look like this:
>>>>>> +//
>>>>>> +//    void error_free_errp(Error **errp)
>>>>>> +//    {
>>>>>> +//        error_free(*errp);
>>>>>> +//        *errp = NULL;
>>>>>> +//    }
>>>>>> +@ disable optional_qualifier exists@
>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>> +expression list args;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +(
>>>>>> +-    Error *local_err = NULL;
>>>>>> +|
>>>>>> +
>>>>>> +// Convert error clearing functions
>>>>>> +(
>>>>>> +-    error_free(local_err);
>>>>>> ++    error_free_errp(errp);
>>>>>> +|
>>>>>> +-    error_report_err(local_err);
>>>>>> ++    error_report_errp(errp);
>>>>>> +|
>>>>>> +-    error_reportf_err(local_err, args);
>>>>>> ++    error_reportf_errp(errp, args);
>>>>>> +|
>>>>>> +-    warn_report_err(local_err);
>>>>>> ++    warn_report_errp(errp);
>>>>>> +|
>>>>>> +-    warn_reportf_err(local_err, args);
>>>>>> ++    warn_reportf_errp(errp, args);
>>>>>> +)
>>>>>> +?-    local_err = NULL;
>>>>>> +
>>>>>> +|
>>>>>> +-    error_propagate_prepend(errp, local_err, args);
>>>>>> ++    error_prepend(errp, args);
>>>>>> +|
>>>>>> +-    error_propagate(errp, local_err);
>>>>>> +|
>>>>>> +-    &local_err
>>>>>> ++    errp
>>>>>> +)
>>>>>> +     ...>
>>>>>> + }
>>>>>> +
>>>>>> +// Convert remaining local_err usage. For example, different kinds of
>>>>>> +// error checking in if conditionals. We can't merge this into
>>>>>> +// previous hunk, as this conflicts with other substitutions in it (at
>>>>>> +// least with "- local_err = NULL").
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn, rule1.local_err;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +-    local_err
>>>>>> ++    *errp
>>>>>> +     ...>
>>>>>> + }
>>>>>> +
>>>>>> +// Always use the same pattern for checking error
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn;
>>>>>> +symbol errp;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error ** ____, ...)
>>>>>> + {
>>>>>> +     <...
>>>>>> +-    *errp != NULL
>>>>>> ++    *errp
>>>>>> +     ...>
>>>>>> + }
>>>>>> +
>>>>>> +// Revert temporary ___ identifier.
>>>>>> +@ disable optional_qualifier@
>>>>>> +identifier rule1.fn;
>>>>>> +@@
>>>>>> +
>>>>>> + fn(..., Error **
>>>>>> +-   ____
>>>>>> ++   errp
>>>>>> +    , ...)
>>>>>> + {
>>>>>> +     ...
>>>>>> + }
>>>>>> diff --git a/include/qapi/error.h b/include/qapi/error.h
>>>>>> index 30140d9bfe..56c133520d 100644
>>>>>> --- a/include/qapi/error.h
>>>>>> +++ b/include/qapi/error.h
>>>>>> @@ -214,6 +214,9 @@
>>>>>>      *         }
>>>>>>      *         ...
>>>>>>      *     }
>>>>>> + *
>>>>>> + * For mass-conversion use script
>>>>>> + *   scripts/coccinelle/auto-propagated-errp.cocci
>>>>>>      */
>>>>>>       #ifndef ERROR_H
>>>>>> diff --git a/MAINTAINERS b/MAINTAINERS
>>>>>> index 857f969aa1..047f1b9714 100644
>>>>>> --- a/MAINTAINERS
>>>>>> +++ b/MAINTAINERS
>>>>>> @@ -1998,6 +1998,7 @@ F: include/qemu/error-report.h
>>>>>>     F: qapi/error.json
>>>>>>     F: util/error.c
>>>>>>     F: util/qemu-error.c
>>>>>> +F: scripts/coccinelle/*err*.cocci
>>>>>>       GDB stub
>>>>>>     M: Alex Bennée <alex.bennee@linaro.org>
>>>>>
>>>
>>>
>>>   From 42a08c529024337d1b859839c9ce7f797f784555 Mon Sep 17 00:00:00 2001
>>> From: Markus Armbruster <armbru@redhat.com>
>>> Date: Fri, 13 Mar 2020 14:27:57 +0100
>>> Subject: [PATCH] fixup! scripts: Coccinelle script to use
>>>    ERRP_AUTO_PROPAGATE()
>>>
>>> ---
>>>    scripts/coccinelle/auto-propagated-errp.cocci | 37 ++++++++++---------
>>>    1 file changed, 20 insertions(+), 17 deletions(-)
>>>
>>> diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
>>> index 7dac2dcfa4..43b0b0e63b 100644
>>> --- a/scripts/coccinelle/auto-propagated-errp.cocci
>>> +++ b/scripts/coccinelle/auto-propagated-errp.cocci
>>> @@ -136,45 +136,48 @@ symbol errp;
>>>      // Warn several Error * definitions.
>>>    @check1 disable optional_qualifier exists@
>>> -identifier fn = rule1.fn, local_err, local_err2;
>>> +identifier fn, _errp, local_err, local_err2;
>>> +position p1, p2;
>>
>>
>> Hmm, seems like I forget to define ____ as symbol in my patch
> 
> Coccinelle defaults to symbol.
> 
>>>    @@
>>>    - fn(..., Error ** ____, ...)
>>> + fn(..., Error **_errp, ...)
>>
>> Ahmm.. it will break compilation?
>>
>> Or, how will it work when _errp defined as meta variable is only in "+..." line? Should it be symbol instead, or just not defined?
> 
> Misunderstanding?  It's a diff between your .cocci and mine.  My version
> is
> 
>      // Warn several Error * definitions.
>      @check1 disable optional_qualifier exists@
>      identifier fn, _errp, local_err, local_err2;
>      position p1, p2;
>      @@
> 
>       fn(..., Error **_errp, ...)
>       {
>           ...
>           Error *local_err = NULL;@p1
>           ... when any
>           Error *local_err2 = NULL;@p2
>           ... when any
>       }
> 
>      @ script:python @
>      fn << check1.fn;
>      p1 << check1.p1;
>      p2 << check1.p2;
>      @@
> 
>>>     {
>>>         ...
>>> -     Error *local_err = NULL;
>>> +     Error *local_err = NULL;@p1
>>
>> Why to do -/+ here? Nothing changed..
>>
>>>         ... when any
>>> -     Error *local_err2 = NULL;
>>> +     Error *local_err2 = NULL;@p2
>>>         ... when any
>>>     }
>>>      @ script:python @
>>>    fn << check1.fn;
>>> +p1 << check1.p1;
>>> +p2 << check1.p2;
>>>    @@
>>>      print('Warning: function {} has several definitions of '
>>> -      'Error * local variable'.format(fn))
>>> +      'Error * local variable: at {}:{} and then at {}:{}'.format(
>>> +          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>>      // Warn several propagations in control flow.
>>>    @check2 disable optional_qualifier exists@
>>> -identifier fn = rule1.fn;
>>> -symbol errp;
>>> +identifier fn, _errp;
>>>    position p1, p2;
>>>    @@
>>>    - fn(..., Error ** ____, ...)
>>> + fn(..., Error **_errp, ...)
>>>     {
>>>         ...
>>>    (
>>> -     error_propagate_prepend(errp, ...);@p1
>>> +     error_propagate_prepend(_errp, ...);@p1
>>>    |
>>> -     error_propagate(errp, ...);@p1
>>> +     error_propagate(_errp, ...);@p1
>>>    )
>>>         ...
>>>    (
>>> -     error_propagate_prepend(errp, ...);@p2
>>> +     error_propagate_prepend(_errp, ...);@p2
>>>    |
>>> -     error_propagate(errp, ...);@p2
>>> +     error_propagate(_errp, ...);@p2
>>>    )
>>
>> You change some occurrences of errp to _errp, but not all. It breaks compilation.
>>
>>>         ... when any
>>>     }
>>> @@ -198,7 +201,7 @@ print('Warning: function {} propagates to errp several times in '
>>>    // the same, just without error_propagate() call), coccinelle fails to
>>>    // match this "out: }".
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn, rule1.local_err, out;
>>> +identifier fn, rule1.local_err, out;
>>
>> Hmm. If it improves performance it is strange.. But I can live with this change.
>>
>>>    symbol errp;
>>>    @@
>>>    @@ -239,7 +242,7 @@ symbol errp;
>>>    //        *errp = NULL;
>>>    //    }
>>>    @ disable optional_qualifier exists@
>>> -identifier rule1.fn, rule1.local_err;
>>> +identifier fn, rule1.local_err;
>>>    expression list args;
>>>    symbol errp;
>>>    @@
>>> @@ -287,7 +290,7 @@ symbol errp;
>>>    // previous hunk, as this conflicts with other substitutions in it (at
>>>    // least with "- local_err = NULL").
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn, rule1.local_err;
>>> +identifier fn, rule1.local_err;
>>>    symbol errp;
>>>    @@
>>>    @@ -301,7 +304,7 @@ symbol errp;
>>>      // Always use the same pattern for checking error
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn;
>>> +identifier fn;
>>>    symbol errp;
>>>    @@
>>>    @@ -315,7 +318,7 @@ symbol errp;
>>>      // Revert temporary ___ identifier.
>>>    @ disable optional_qualifier@
>>> -identifier rule1.fn;
>>> +identifier fn;
>>>    @@
>>>       fn(..., Error **
>>>
> 
> I append my hacked up version of auto-propagated-errp.cocci.  It
> produces the same patch as yours for the complete tree.
> 
> 
> 
> // Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
> //
> // Copyright (c) 2020 Virtuozzo International GmbH.
> //
> // This program is free software; you can redistribute it and/or
> // modify it under the terms of the GNU General Public License as
> // published by the Free Software Foundation; either version 2 of the
> // License, or (at your option) any later version.
> //
> // This program is distributed in the hope that it will be useful,
> // but WITHOUT ANY WARRANTY; without even the implied warranty of
> // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> // GNU General Public License for more details.
> //
> // You should have received a copy of the GNU General Public License
> // along with this program.  If not, see
> // <http://www.gnu.org/licenses/>.
> //
> // Usage example:
> // spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
> //  --macro-file scripts/cocci-macro-file.h --in-place \
> //  --no-show-diff --max-width 80 FILES...
> //
> // Note: --max-width 80 is needed because coccinelle default is less
> // than 80, and without this parameter coccinelle may reindent some
> // lines which fit into 80 characters but not to coccinelle default,
> // which in turn produces extra patch hunks for no reason.
> 
> // Switch unusual Error ** parameter names to errp
> // (this is necessary to use ERRP_AUTO_PROPAGATE).
> //
> // Disable optional_qualifier to skip functions with
> // "Error *const *errp" parameter.
> //
> // Skip functions with "assert(_errp && *_errp)" statement, because
> // that signals unusual semantics, and the parameter name may well
> // serve a purpose. (like nbd_iter_channel_error()).
> //
> // Skip util/error.c to not touch, for example, error_propagate() and
> // error_propagate_prepend().
> @ depends on !(file in "util/error.c") disable optional_qualifier@
> identifier fn;
> identifier _errp != errp;
> @@
> 
>   fn(...,
> -   Error **_errp
> +   Error **errp
>      ,...)
>   {
> (
>       ... when != assert(_errp && *_errp)
> &
>       <...
> -    _errp
> +    errp
>       ...>
> )
>   }
> 
> // Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
> // necessary
> //
> // Note, that without "when any" the final "..." does not mach
> // something matched by previous pattern, i.e. the rule will not match
> // double error_prepend in control flow like in
> // vfio_set_irq_signaling().
> //
> // Note, "exists" says that we want apply rule even if it matches not
> // on all possible control flows (otherwise, it will not match
> // standard pattern when error_propagate() call is in if branch).
> @ disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
> 
>   fn(..., Error **errp, ...)
>   {
> +   ERRP_AUTO_PROPAGATE();
>      ...  when != ERRP_AUTO_PROPAGATE();
> (
> (
>      error_append_hint(errp, ...);
> |
>      error_prepend(errp, ...);
> |
>      error_vprepend(errp, ...);
> )
>      ... when any
> |
>      Error *local_err = NULL;
>      ...
> (
>      error_propagate_prepend(errp, local_err, ...);
> |
>      error_propagate(errp, local_err);
> )
>      ...
> )
>   }
> 
> 
> // Match functions with propagation of local error to errp.
> // We want to refer these functions in several following rules, but I
> // don't know a proper way to inherit a function, not just its name
> // (to not match another functions with same name in following rules).
> // Not-proper way is as follows: rename errp parameter in functions
> // header and match it in following rules. Rename it back after all
> // transformations.
> //
> // The simplest case of propagation scheme is single definition of
> // local_err with at most one error_propagate_prepend or
> // error_propagate on each control-flow. Still, we want to match more
> // complex schemes too. We'll warn them with help of further rules.
> @rule1 disable optional_qualifier exists@
> identifier fn, local_err;
> symbol errp;
> @@
> 
>   fn(..., Error **
> -    errp
> +    ____
>      , ...)
>   {
>       ...
>       Error *local_err = NULL;
>       ...
> (
>       error_propagate_prepend(errp, local_err, ...);
> |
>       error_propagate(errp, local_err);
> )
>       ...
>   }
> 
> 
> // Warn several Error * definitions.
> @check1 disable optional_qualifier exists@
> identifier fn, _errp, local_err, local_err2;
> position p1, p2;
> @@
> 
>   fn(..., Error **_errp, ...)
>   {
>       ...
>       Error *local_err = NULL;@p1
>       ... when any
>       Error *local_err2 = NULL;@p2
>       ... when any
>   }
> 
> @ script:python @
> fn << check1.fn;
> p1 << check1.p1;
> p2 << check1.p2;
> @@
> 
> print('Warning: function {} has several definitions of '
>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> 
> // Warn several propagations in control flow.
> @check2 disable optional_qualifier exists@
> identifier fn, _errp;
> position p1, p2;
> @@
> 
>   fn(..., Error **_errp, ...)

Hmm, for this to work, we should move the rule above rule1, because now paramter
definition is different from it usage in the function body.

>   {
>       ...
> (
>       error_propagate_prepend(_errp, ...);@p1
> |
>       error_propagate(_errp, ...);@p1
> )
>       ...
> (
>       error_propagate_prepend(_errp, ...);@p2
> |
>       error_propagate(_errp, ...);@p2
> )
>       ... when any
>   }
> 
> @ script:python @
> fn << check2.fn;
> p1 << check2.p1;
> p2 << check2.p2;
> @@
> 
> print('Warning: function {} propagates to errp several times in '
>        'one control flow: at {}:{} and then at {}:{}'.format(
>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
> 
> // Convert special case with goto separately.
> // I tried merging this into the following rule the obvious way, but
> // it made Coccinelle hang on block.c
> //
> // Note interesting thing: if we don't do it here, and try to fixup
> // "out: }" things later after all transformations (the rule will be
> // the same, just without error_propagate() call), coccinelle fails to
> // match this "out: }".
> @ disable optional_qualifier@
> identifier fn, rule1.local_err, out;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    goto out;
> +    return;
>       ...>
> - out:
> -    error_propagate(errp, local_err);
>   }
> 
> // Convert most of local_err related stuff.
> //
> // Note, that we update everything related to matched by rule1
> // function name and local_err name. We may match something not
> // related to the pattern matched by rule1. For example, local_err may
> // be defined with the same name in different blocks inside one
> // function, and in one block follow the propagation pattern and in
> // other block doesn't. Or we may have several functions with the same
> // name (for different configurations).
> //
> // Note also that errp-cleaning functions
> //   error_free_errp
> //   error_report_errp
> //   error_reportf_errp
> //   warn_report_errp
> //   warn_reportf_errp
> // are not yet implemented. They must call corresponding Error* -
> // freeing function and then set *errp to NULL, to avoid further
> // propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
> // For example, error_free_errp may look like this:
> //
> //    void error_free_errp(Error **errp)
> //    {
> //        error_free(*errp);
> //        *errp = NULL;
> //    }
> @ disable optional_qualifier exists@
> identifier fn, rule1.local_err;
> expression list args;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> (
> -    Error *local_err = NULL;
> |
> 
> // Convert error clearing functions
> (
> -    error_free(local_err);
> +    error_free_errp(errp);
> |
> -    error_report_err(local_err);
> +    error_report_errp(errp);
> |
> -    error_reportf_err(local_err, args);
> +    error_reportf_errp(errp, args);
> |
> -    warn_report_err(local_err);
> +    warn_report_errp(errp);
> |
> -    warn_reportf_err(local_err, args);
> +    warn_reportf_errp(errp, args);
> )
> ?-    local_err = NULL;
> 
> |
> -    error_propagate_prepend(errp, local_err, args);
> +    error_prepend(errp, args);
> |
> -    error_propagate(errp, local_err);
> |
> -    &local_err
> +    errp
> )
>       ...>
>   }
> 
> // Convert remaining local_err usage. For example, different kinds of
> // error checking in if conditionals. We can't merge this into
> // previous hunk, as this conflicts with other substitutions in it (at
> // least with "- local_err = NULL").
> @ disable optional_qualifier@
> identifier fn, rule1.local_err;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    local_err
> +    *errp
>       ...>
>   }
> 
> // Always use the same pattern for checking error
> @ disable optional_qualifier@
> identifier fn;
> symbol errp;
> @@
> 
>   fn(..., Error ** ____, ...)
>   {
>       <...
> -    *errp != NULL
> +    *errp
>       ...>
>   }
> 
> // Revert temporary ___ identifier.
> @ disable optional_qualifier@
> identifier fn;
> @@
> 
>   fn(..., Error **
> -   ____
> +   errp
>      , ...)
>   {
>       ...
>   }
>
Markus Armbruster March 19, 2020, 8:31 a.m. UTC | #19
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 14.03.2020 0:54, Markus Armbruster wrote:
[...]
>> // Match functions with propagation of local error to errp.
>> // We want to refer these functions in several following rules, but I
>> // don't know a proper way to inherit a function, not just its name
>> // (to not match another functions with same name in following rules).
>> // Not-proper way is as follows: rename errp parameter in functions
>> // header and match it in following rules. Rename it back after all
>> // transformations.
>> //
>> // The simplest case of propagation scheme is single definition of
>> // local_err with at most one error_propagate_prepend or
>> // error_propagate on each control-flow. Still, we want to match more
>> // complex schemes too. We'll warn them with help of further rules.
>> @rule1 disable optional_qualifier exists@
>> identifier fn, local_err;
>> symbol errp;
>> @@
>>
>>   fn(..., Error **
>> -    errp
>> +    ____
>>      , ...)
>>   {
>>       ...
>>       Error *local_err = NULL;
>>       ...
>> (
>>       error_propagate_prepend(errp, local_err, ...);
>> |
>>       error_propagate(errp, local_err);
>> )
>>       ...
>>   }
>>
>>
>> // Warn several Error * definitions.
>> @check1 disable optional_qualifier exists@
>> identifier fn, _errp, local_err, local_err2;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>>   {
>>       ...
>>       Error *local_err = NULL;@p1
>>       ... when any
>>       Error *local_err2 = NULL;@p2
>>       ... when any
>>   }
>>
>> @ script:python @
>> fn << check1.fn;
>> p1 << check1.p1;
>> p2 << check1.p2;
>> @@
>>
>> print('Warning: function {} has several definitions of '
>>        'Error * local variable: at {}:{} and then at {}:{}'.format(
>>            fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
>>
>> // Warn several propagations in control flow.
>> @check2 disable optional_qualifier exists@
>> identifier fn, _errp;
>> position p1, p2;
>> @@
>>
>>   fn(..., Error **_errp, ...)
>
> Hmm, for this to work, we should move the rule above rule1, because now paramter
> definition is different from it usage in the function body.

I think you're right.

[...]
Markus Armbruster March 19, 2020, 10:45 a.m. UTC | #20
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 17.03.2020 13:39, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>
>>> 16.03.2020 11:21, Markus Armbruster wrote:
>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>
>>>>> On 14.03.2020 00:54, Markus Armbruster wrote:
>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>
>>>>>>> 13.03.2020 18:42, Markus Armbruster wrote:
>>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>>>
>>>>>>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>>>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>>>>>>> out now as is.
>>>>>>>>>>
>>>>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>> [...]
>>>>>>>>>>> +@@
>>>>>>>>>>> +
>>>>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>>>>> + {
>>>>>>>>>>> +     ...
>>>>>>>>>>> +     Error *local_err = NULL;
>>>>>>>>>>> +     ... when any
>>>>>>>>>>> +     Error *local_err2 = NULL;
>>>>>>>>>>> +     ... when any
>>>>>>>>>>> + }
>>>>>>
>>>>>> This flags functions that have more than one declaration along any
>>>>>> control flow path.  It doesn't flag this one:
>>>>>>
>>>>>>        void gnat(bool b, Error **errp)
>>>>>>        {
>>>>>>            if (b) {
>>>>>>                Error *local_err = NULL;
>>>>>>                foo(arg, &local_err);
>>>>>>                error_propagate(errp, local_err);
>>>>>>            } else {
>>>>>>                Error *local_err = NULL;
>>>>>>                bar(arg, &local_err);
>>>>>>                error_propagate(errp, local_err);
>>>>>>            }
>>>>>>        }
>>>>>>
>>>>>> The Coccinelle script does the right thing for this one regardless.
>>>>>>
>>>>>> I'd prefer to have such functions flagged, too.  But spending time on
>>>>>> convincing Coccinelle to do it for me is not worthwhile; I can simply
>>>>>> search the diff produced by Coccinelle for deletions of declarations
>>>>>> that are not indented exactly four spaces.
>>>>>>
>>>>>> But if we keep this rule, we should adjust its comment
>>>>>>
>>>>>>        // Warn several Error * definitions.
>>>>>>
>>>>>> because it sure suggests it also catches functions like the one I gave
>>>>>> above.
>>>>>
>>>>> Hmm, yes.. We can write "Warn several Error * definitions in _one_
>>>>> control flow (it's not so trivial to match _any_ case with several
>>>>> definitions with coccinelle)" or something like this.
>>>>
>>>> Ha, "trivial" reminds me of a story.  The math professor, after having
>>>> spent a good chunk of his lecture developing a proof on the blackboad
>>>> turns to the audience to explain why this little part doesn't require
>>>> proof with the words familiar to any math student "and this is trivial."
>>>> Pause, puzzled look...  "Is it trivial?"  Pause, storms out of the
>>>> lecture hall.  A minute or three pass.  Professor comes back beaming,
>>>> "it is trivial!", and proceeds with the proof.
>>>>
>>>> My point is: it might be trivial with Coccinelle once you know how to do
>>>> it.  We don't.
>>>>
>>>> Suggest "(can't figure out how to match several definitions regardless
>>>> of control flow)".
>>>
>>> Wrong too, because I can:) for example, chaining two rules, catching the
>>> positions of definition and check that they are different.. Or, some
>>> cheating with python script.. That's why I wrote "not trivial",
>>>
>>> So, most correct would be "(can't figure out how to simply match several definitions regardless
>>>> of control flow)".
>>
>> Works for me.
>>
>>> But again, coccinelle is for matching control flows, so its probably impossible to match such thing..
>> [...]
>>>>> OK, I almost OK with it, the only thing I doubt a bit is the following:
>>>>>
>>>>> We want to keep rule1.local_err inheritance to keep connection with
>>>>> local_err definition.
>>>>
>>>> Yes.
>>>>
>>>>> Interesting, when we have both rule1.fn and rule1.local_err inherited,
>>>>> do we inherit them in separate (i.e. all possible combinations of fn
>>>>> and local_err symbols from rule1) or do we inherit a pair, i.e. only
>>>>> fn/local_err pairs, found by rule1? If the latter is correct, that
>>>>> with your script we loss this pair inheritance, and go to all possible
>>>>> combinations of fn and local_err from rule1, possibly adding some wrong
>>>>> conversion (OK, you've checked that no such cases in current code tree).
>>>>
>>>> The chaining "identifier rule1.FOO" is by name.  It's reliable only as
>>>> long as there is exactly one instance of the name.
>>>>
>>>> We already discussed the case of the function name: if there are two
>>>> instances of foo(), and rule1 matches only one of them, then we
>>>> nevertheless apply the rules chained to rule1 to both.  Because that can
>>>> be wrong, you came up with the ___ trick, which chains reliably.
>>>>
>>>> The same issue exists with the variable name: if there are two instances
>>>> of @local_err, and rule1 matches only one of them, then we nevertheless
>>>> apply the rules chained to rule1 to both.  Can also be wrong.
>>>>
>>>> What are the conditions for "wrong"?
>>>>
>>>> Because the ___ chaining is reliable, we know rule1 matched the
>>>> function, i.e. it has a parameter Error **errp, and it has a automatic
>>>> variable Error *local_err = NULL.
>>>>
>>>> We're good as long as *all* identifiers @local_err in this function are
>>>> declared that way.  This seems quite likely.  It's not certain, though.
>>>>
>>>> Since nested declarations of Error ** variables are rare, we can rely on
>>>> review to ensure we transform these functions correctly.
>>>>
>>>>> So, dropping inheritance in check-rules makes sence, as it may match
>>>>> (and warn) more interesting cases.
>>>>>
>>>>> But for other rules, I'd prefere to be safer, and explictly inherit all
>>>>> actually inherited identifiers..
>>>>
>>>> I still can't see what chaining by function name in addition to the ___
>>>> chaining buys us.
>>>
>>> I'll check this thing soon. And resend today.
>
> Checked.
>
> Yes, it inherits pair of fn and local_err, and it definitely makes sense. It more stable.
>
> Consider the following example:
>
> # cat a.c
> int f1(Error **errp)
> {
>     Error *err1 = NULL;
>     int err2 = 0;
>
>     error_propagate(errp, err1);
>
>     return err2;
> }
>
> int f2(Error **errp)
> {
>     Error *err2 = NULL;
>     int err1 = 0;
>
>     error_propagate(errp, err2);
>
>     return err1;
> }
>
>
> My script works correct and produces this change:
> --- a.c
> +++ /tmp/cocci-output-1753-10842a-a.c
> @@ -1,19 +1,15 @@
>  int f1(Error **errp)
>  {
> -    Error *err1 = NULL;
> +    ERRP_AUTO_PROPAGATE();
>      int err2 = 0;
>
> -    error_propagate(errp, err1);
> -
>      return err2;
>  }
>
>  int f2(Error **errp)
>  {
> -    Error *err2 = NULL;
> +    ERRP_AUTO_PROPAGATE();
>      int err1 = 0;
>
> -    error_propagate(errp, err2);
> -
>      return err1;
>  }
>
>
> But yours script is caught:
> --- a.c
> +++ /tmp/cocci-output-1814-b9b681-a.c
> @@ -1,19 +1,15 @@
>  int f1(Error **errp)
>  {
> -    Error *err1 = NULL;
> +    ERRP_AUTO_PROPAGATE();
>      int err2 = 0;
>
> -    error_propagate(errp, err1);
> -
> -    return err2;
> +    return *errp;
>  }
>
>  int f2(Error **errp)
>  {
> -    Error *err2 = NULL;
> +    ERRP_AUTO_PROPAGATE();
>      int err1 = 0;
>
> -    error_propagate(errp, err2);
> -
> -    return err1;
> +    return *errp;
>  }
>
>
> - see, it touches err1, which is unrelated to Error in f2. Hmm,
> interesting that it doesn't want to convert err1 declaration:)
>
> - this is because relation between local_err and fn is lost.

Let me try to think this through.

rule1 matches functions that propagate from a local variable @local_err
to parameter @errp.  It uses the ___ hack to reliably tag the function.
Later rules that should only apply to these functions can match ___.

These later rules each provide a part of the total error propagation
transformation.  They must transform exactly the @local_err and @errp
matched by rule1 in each function.

Your solution is to constrain the identifiers, i.e.

    identifier rule1.fn, rule1.local_err;

If rule1 matches only one function named foo(), and within that foo()
the local variable @local_err rule1 matches actually binds all
occurences of the identifier @local_err, the constraint is reliable.

Else, the constraint may still accept occurences of @local_err not bound
to the variable matched by rule1.

Example 1:

    int bar(Error **errp)
    {
        if (pred()) {
            Error *local_err = NULL;

            error_setg(&local_err, "zzzt");
            error_propagate(errp, local_err);
        } else {
            int local_err = 0;
            return local_err;
        }
        return 0;
    }

rule1 matches the first @local_err variable, and not the second one.  We
must transform occurences of the first one, and not occurences of the
second one.  We do transform all:

     int bar(Error **errp)
     {
    +    ERRP_AUTO_PROPAGATE();
         if (pred()) {
    -        Error *local_err = NULL;
    -
    -        error_setg(&local_err, "zzzt");
    -        error_propagate(errp, local_err);
    +        error_setg(errp, "zzzt");
         } else {
             int local_err = 0;
    -        return local_err;
    +        return *errp;
         }
         return 0;
     }

Example 2:

    int foo(Error **errp)
    {
        Error *local_err = NULL;

        error_setg(&local_err, "zzzt");
        error_propagate(errp, local_err);
        return 0;
    }

    int foo(Error **errp)
    {
        Error *err = NULL;
        int local_err = 0;

        error_setg(&local_err, "zzzt");
        error_propagate(errp, err);
        return local_err;
    }

rule1 matches @local_err in the first foo(), and @err in the second one.
We must transform @local_err in the first one(), and @err in the second
one.  We do transform both in both:

     int foo(Error **errp)
     {
    -    Error *local_err = NULL;
    +    ERRP_AUTO_PROPAGATE();

    -    error_setg(&local_err, "zzzt");
    -    error_propagate(errp, local_err);
    +    error_setg(errp, "zzzt");
         return 0;
     }

     int foo(Error **errp)
     {
    -    Error *err = NULL;
    +    ERRP_AUTO_PROPAGATE();
         int local_err = 0;

    -    error_setg(&local_err, "zzzt");
    -    error_propagate(errp, err);
    -    return local_err;
    +    error_setg(errp, "zzzt");
    +    return *errp;
     }

Constraining only the variable identifier like I proposed is even less
reliable, as you demonstrated: then the issue in example 2 exists even
for differently named functions.

For a reliable solution, we could use perhaps use the ___ hack again:
have rule1 rename @local_err it actually matches.  But to be honest, my
appetite for another round of wrestling with Coccinelle isn't what it
used to be.

I think we can do without as long as we're well aware of the script's
limitations, and we're confident we can detect problematic cases.

Detecting transformation of multiple functions with the same name should
be easy.

Detecting occurences of identifiers not bound by a certain variable
should be feasible: we find and review every transformed function that
doesn't declare the variable in its outermost scope.

Since "well aware" is going to erode with time, we may want to delete
the script when we're done converting.

> So, understanding that there no such cases in the whole tree, and even
> if your patch works faster on the whole tree, I still don't want to
> drop inheritance, because it's just a correct thing to do. Yes, we've
> added ____ helper. It helps to avoid some problems. Pair-inheritance
> helps to avoid another problems. I understand, that there still may
> other, not-covered problems, but better to be as safe as possible. And
> inheritance here is native and correct thing to do, even with our ____
> additional helper. What do you think?

I wouldn't call it correct.  It's still unreliable, but less so than
without the function name constraint.  That makes it less wrong.

100% reliable would be nice, but not at any cost.  Something we're
reasonably confident to get right should be good enough.

To be confident, we need to understand the script's limitations, and how
to compensate for them.  I figure we do now.  You too?

[...]
Vladimir Sementsov-Ogievskiy March 19, 2020, 12:12 p.m. UTC | #21
19.03.2020 13:45, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> 17.03.2020 13:39, Markus Armbruster wrote:
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>
>>>> 16.03.2020 11:21, Markus Armbruster wrote:
>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>
>>>>>> On 14.03.2020 00:54, Markus Armbruster wrote:
>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>>
>>>>>>>> 13.03.2020 18:42, Markus Armbruster wrote:
>>>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>>>>>>>>
>>>>>>>>>> 12.03.2020 19:36, Markus Armbruster wrote:
>>>>>>>>>>> I may have a second look tomorrow with fresher eyes, but let's get this
>>>>>>>>>>> out now as is.
>>>>>>>>>>>
>>>>>>>>>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
>>> [...]
>>>>>>>>>>>> +@@
>>>>>>>>>>>> +
>>>>>>>>>>>> + fn(..., Error ** ____, ...)
>>>>>>>>>>>> + {
>>>>>>>>>>>> +     ...
>>>>>>>>>>>> +     Error *local_err = NULL;
>>>>>>>>>>>> +     ... when any
>>>>>>>>>>>> +     Error *local_err2 = NULL;
>>>>>>>>>>>> +     ... when any
>>>>>>>>>>>> + }
>>>>>>>
>>>>>>> This flags functions that have more than one declaration along any
>>>>>>> control flow path.  It doesn't flag this one:
>>>>>>>
>>>>>>>         void gnat(bool b, Error **errp)
>>>>>>>         {
>>>>>>>             if (b) {
>>>>>>>                 Error *local_err = NULL;
>>>>>>>                 foo(arg, &local_err);
>>>>>>>                 error_propagate(errp, local_err);
>>>>>>>             } else {
>>>>>>>                 Error *local_err = NULL;
>>>>>>>                 bar(arg, &local_err);
>>>>>>>                 error_propagate(errp, local_err);
>>>>>>>             }
>>>>>>>         }
>>>>>>>
>>>>>>> The Coccinelle script does the right thing for this one regardless.
>>>>>>>
>>>>>>> I'd prefer to have such functions flagged, too.  But spending time on
>>>>>>> convincing Coccinelle to do it for me is not worthwhile; I can simply
>>>>>>> search the diff produced by Coccinelle for deletions of declarations
>>>>>>> that are not indented exactly four spaces.
>>>>>>>
>>>>>>> But if we keep this rule, we should adjust its comment
>>>>>>>
>>>>>>>         // Warn several Error * definitions.
>>>>>>>
>>>>>>> because it sure suggests it also catches functions like the one I gave
>>>>>>> above.
>>>>>>
>>>>>> Hmm, yes.. We can write "Warn several Error * definitions in _one_
>>>>>> control flow (it's not so trivial to match _any_ case with several
>>>>>> definitions with coccinelle)" or something like this.
>>>>>
>>>>> Ha, "trivial" reminds me of a story.  The math professor, after having
>>>>> spent a good chunk of his lecture developing a proof on the blackboad
>>>>> turns to the audience to explain why this little part doesn't require
>>>>> proof with the words familiar to any math student "and this is trivial."
>>>>> Pause, puzzled look...  "Is it trivial?"  Pause, storms out of the
>>>>> lecture hall.  A minute or three pass.  Professor comes back beaming,
>>>>> "it is trivial!", and proceeds with the proof.
>>>>>
>>>>> My point is: it might be trivial with Coccinelle once you know how to do
>>>>> it.  We don't.
>>>>>
>>>>> Suggest "(can't figure out how to match several definitions regardless
>>>>> of control flow)".
>>>>
>>>> Wrong too, because I can:) for example, chaining two rules, catching the
>>>> positions of definition and check that they are different.. Or, some
>>>> cheating with python script.. That's why I wrote "not trivial",
>>>>
>>>> So, most correct would be "(can't figure out how to simply match several definitions regardless
>>>>> of control flow)".
>>>
>>> Works for me.
>>>
>>>> But again, coccinelle is for matching control flows, so its probably impossible to match such thing..
>>> [...]
>>>>>> OK, I almost OK with it, the only thing I doubt a bit is the following:
>>>>>>
>>>>>> We want to keep rule1.local_err inheritance to keep connection with
>>>>>> local_err definition.
>>>>>
>>>>> Yes.
>>>>>
>>>>>> Interesting, when we have both rule1.fn and rule1.local_err inherited,
>>>>>> do we inherit them in separate (i.e. all possible combinations of fn
>>>>>> and local_err symbols from rule1) or do we inherit a pair, i.e. only
>>>>>> fn/local_err pairs, found by rule1? If the latter is correct, that
>>>>>> with your script we loss this pair inheritance, and go to all possible
>>>>>> combinations of fn and local_err from rule1, possibly adding some wrong
>>>>>> conversion (OK, you've checked that no such cases in current code tree).
>>>>>
>>>>> The chaining "identifier rule1.FOO" is by name.  It's reliable only as
>>>>> long as there is exactly one instance of the name.
>>>>>
>>>>> We already discussed the case of the function name: if there are two
>>>>> instances of foo(), and rule1 matches only one of them, then we
>>>>> nevertheless apply the rules chained to rule1 to both.  Because that can
>>>>> be wrong, you came up with the ___ trick, which chains reliably.
>>>>>
>>>>> The same issue exists with the variable name: if there are two instances
>>>>> of @local_err, and rule1 matches only one of them, then we nevertheless
>>>>> apply the rules chained to rule1 to both.  Can also be wrong.
>>>>>
>>>>> What are the conditions for "wrong"?
>>>>>
>>>>> Because the ___ chaining is reliable, we know rule1 matched the
>>>>> function, i.e. it has a parameter Error **errp, and it has a automatic
>>>>> variable Error *local_err = NULL.
>>>>>
>>>>> We're good as long as *all* identifiers @local_err in this function are
>>>>> declared that way.  This seems quite likely.  It's not certain, though.
>>>>>
>>>>> Since nested declarations of Error ** variables are rare, we can rely on
>>>>> review to ensure we transform these functions correctly.
>>>>>
>>>>>> So, dropping inheritance in check-rules makes sence, as it may match
>>>>>> (and warn) more interesting cases.
>>>>>>
>>>>>> But for other rules, I'd prefere to be safer, and explictly inherit all
>>>>>> actually inherited identifiers..
>>>>>
>>>>> I still can't see what chaining by function name in addition to the ___
>>>>> chaining buys us.
>>>>
>>>> I'll check this thing soon. And resend today.
>>
>> Checked.
>>
>> Yes, it inherits pair of fn and local_err, and it definitely makes sense. It more stable.
>>
>> Consider the following example:
>>
>> # cat a.c
>> int f1(Error **errp)
>> {
>>      Error *err1 = NULL;
>>      int err2 = 0;
>>
>>      error_propagate(errp, err1);
>>
>>      return err2;
>> }
>>
>> int f2(Error **errp)
>> {
>>      Error *err2 = NULL;
>>      int err1 = 0;
>>
>>      error_propagate(errp, err2);
>>
>>      return err1;
>> }
>>
>>
>> My script works correct and produces this change:
>> --- a.c
>> +++ /tmp/cocci-output-1753-10842a-a.c
>> @@ -1,19 +1,15 @@
>>   int f1(Error **errp)
>>   {
>> -    Error *err1 = NULL;
>> +    ERRP_AUTO_PROPAGATE();
>>       int err2 = 0;
>>
>> -    error_propagate(errp, err1);
>> -
>>       return err2;
>>   }
>>
>>   int f2(Error **errp)
>>   {
>> -    Error *err2 = NULL;
>> +    ERRP_AUTO_PROPAGATE();
>>       int err1 = 0;
>>
>> -    error_propagate(errp, err2);
>> -
>>       return err1;
>>   }
>>
>>
>> But yours script is caught:
>> --- a.c
>> +++ /tmp/cocci-output-1814-b9b681-a.c
>> @@ -1,19 +1,15 @@
>>   int f1(Error **errp)
>>   {
>> -    Error *err1 = NULL;
>> +    ERRP_AUTO_PROPAGATE();
>>       int err2 = 0;
>>
>> -    error_propagate(errp, err1);
>> -
>> -    return err2;
>> +    return *errp;
>>   }
>>
>>   int f2(Error **errp)
>>   {
>> -    Error *err2 = NULL;
>> +    ERRP_AUTO_PROPAGATE();
>>       int err1 = 0;
>>
>> -    error_propagate(errp, err2);
>> -
>> -    return err1;
>> +    return *errp;
>>   }
>>
>>
>> - see, it touches err1, which is unrelated to Error in f2. Hmm,
>> interesting that it doesn't want to convert err1 declaration:)
>>
>> - this is because relation between local_err and fn is lost.
> 
> Let me try to think this through.
> 
> rule1 matches functions that propagate from a local variable @local_err
> to parameter @errp.  It uses the ___ hack to reliably tag the function.
> Later rules that should only apply to these functions can match ___.
> 
> These later rules each provide a part of the total error propagation
> transformation.  They must transform exactly the @local_err and @errp
> matched by rule1 in each function.
> 
> Your solution is to constrain the identifiers, i.e.
> 
>      identifier rule1.fn, rule1.local_err;
> 
> If rule1 matches only one function named foo(), and within that foo()
> the local variable @local_err rule1 matches actually binds all
> occurences of the identifier @local_err, the constraint is reliable.
> 
> Else, the constraint may still accept occurences of @local_err not bound
> to the variable matched by rule1.
> 
> Example 1:
> 
>      int bar(Error **errp)
>      {
>          if (pred()) {
>              Error *local_err = NULL;
> 
>              error_setg(&local_err, "zzzt");
>              error_propagate(errp, local_err);
>          } else {
>              int local_err = 0;
>              return local_err;
>          }
>          return 0;
>      }
> 
> rule1 matches the first @local_err variable, and not the second one.  We
> must transform occurences of the first one, and not occurences of the
> second one.  We do transform all:
> 
>       int bar(Error **errp)
>       {
>      +    ERRP_AUTO_PROPAGATE();
>           if (pred()) {
>      -        Error *local_err = NULL;
>      -
>      -        error_setg(&local_err, "zzzt");
>      -        error_propagate(errp, local_err);
>      +        error_setg(errp, "zzzt");
>           } else {
>               int local_err = 0;
>      -        return local_err;
>      +        return *errp;
>           }
>           return 0;
>       }
> 

Aha, good example. And we even do not warn it.

> Example 2:
> 
>      int foo(Error **errp)
>      {
>          Error *local_err = NULL;
> 
>          error_setg(&local_err, "zzzt");
>          error_propagate(errp, local_err);
>          return 0;
>      }
> 
>      int foo(Error **errp)
>      {
>          Error *err = NULL;
>          int local_err = 0;
> 
>          error_setg(&local_err, "zzzt");
>          error_propagate(errp, err);
>          return local_err;
>      }
> 
> rule1 matches @local_err in the first foo(), and @err in the second one.
> We must transform @local_err in the first one(), and @err in the second
> one.  We do transform both in both:
> 
>       int foo(Error **errp)
>       {
>      -    Error *local_err = NULL;
>      +    ERRP_AUTO_PROPAGATE();
> 
>      -    error_setg(&local_err, "zzzt");
>      -    error_propagate(errp, local_err);
>      +    error_setg(errp, "zzzt");
>           return 0;
>       }
> 
>       int foo(Error **errp)
>       {
>      -    Error *err = NULL;
>      +    ERRP_AUTO_PROPAGATE();
>           int local_err = 0;
> 
>      -    error_setg(&local_err, "zzzt");
>      -    error_propagate(errp, err);
>      -    return local_err;
>      +    error_setg(errp, "zzzt");
>      +    return *errp;
>       }
> 
> Constraining only the variable identifier like I proposed is even less
> reliable, as you demonstrated: then the issue in example 2 exists even
> for differently named functions.
> 
> For a reliable solution, we could use perhaps use the ___ hack again:
> have rule1 rename @local_err it actually matches. But to be honest, my
> appetite for another round of wrestling with Coccinelle isn't what it
> used to be. >
> I think we can do without as long as we're well aware of the script's
> limitations, and we're confident we can detect problematic cases.
> 
> Detecting transformation of multiple functions with the same name should
> be easy.
> 
> Detecting occurences of identifiers not bound by a certain variable
> should be feasible: we find and review every transformed function that
> doesn't declare the variable in its outermost scope.
> 
> Since "well aware" is going to erode with time, we may want to delete
> the script when we're done converting.
> 
>> So, understanding that there no such cases in the whole tree, and even
>> if your patch works faster on the whole tree, I still don't want to
>> drop inheritance, because it's just a correct thing to do. Yes, we've
>> added ____ helper. It helps to avoid some problems. Pair-inheritance
>> helps to avoid another problems. I understand, that there still may
>> other, not-covered problems, but better to be as safe as possible. And
>> inheritance here is native and correct thing to do, even with our ____
>> additional helper. What do you think?
> 
> I wouldn't call it correct.  It's still unreliable, but less so than
> without the function name constraint.  That makes it less wrong.

Agree.

> 
> 100% reliable would be nice, but not at any cost.  Something we're
> reasonably confident to get right should be good enough.
> 
> To be confident, we need to understand the script's limitations, and how
> to compensate for them.  I figure we do now.  You too?
> 

I will not be surprised, if we missed some more interesting cases :)
But we should proceed. What is our plan? Will you queue v10 for 5.1?
Markus Armbruster March 20, 2020, 1:58 p.m. UTC | #22
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 19.03.2020 13:45, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
[...]
>>> So, understanding that there no such cases in the whole tree, and even
>>> if your patch works faster on the whole tree, I still don't want to
>>> drop inheritance, because it's just a correct thing to do. Yes, we've
>>> added ____ helper. It helps to avoid some problems. Pair-inheritance
>>> helps to avoid another problems. I understand, that there still may
>>> other, not-covered problems, but better to be as safe as possible. And
>>> inheritance here is native and correct thing to do, even with our ____
>>> additional helper. What do you think?
>>
>> I wouldn't call it correct.  It's still unreliable, but less so than
>> without the function name constraint.  That makes it less wrong.
>
> Agree.
>
>>
>> 100% reliable would be nice, but not at any cost.  Something we're
>> reasonably confident to get right should be good enough.
>>
>> To be confident, we need to understand the script's limitations, and how
>> to compensate for them.  I figure we do now.  You too?
>>
>
> I will not be surprised, if we missed some more interesting cases :)
> But we should proceed. What is our plan? Will you queue v10 for 5.1?

v10's PATCH 1+2 look ready.  The error.h comment update could perhaps
use some polish; I've focused my attention elsewhere.

PATCH 8-9 are generated.  They should never be rebased, always be
regenerated.  We compare regenerated patches to posted ones to make sure
they are still sane, and the R-bys are still valid.  I can take care of
the comparing.

I'd like to have a pull request ready when the tree reopens for general
development.  Let's use the time until then to get more generated
patches out for review.

If I queue up patches in my tree, we shift the responsibility for
regenerating patches from you to me, and create a coordination issue:
you'll want to base patch submissions on the branch I use to queue this
work, and that's going to be awkward when I rebase / regenerate that
branch.  I think it's simpler to queue up in your tree until we're ready
for a pull request.

When you post more patches, use

    Based-on: <20200317151625.20797-1-vsementsov@virtuozzo.com>

so that Patchew applies them on top of this series.  Hmm, probably won't
do, as PATCH 9 already conflicts.

You could instead repost PATCH 1+2 with each batch.  I hope that's not
too confusing.

I trust you'll keep providing a tag reviewers can pull.

I suggest to ask maintainers to leave merging these patches to me, in
cover letters.

Makes sense?
Vladimir Sementsov-Ogievskiy March 20, 2020, 2:36 p.m. UTC | #23
20.03.2020 16:58, Markus Armbruster wrote:
> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> 
>> 19.03.2020 13:45, Markus Armbruster wrote:
>>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
> [...]
>>>> So, understanding that there no such cases in the whole tree, and even
>>>> if your patch works faster on the whole tree, I still don't want to
>>>> drop inheritance, because it's just a correct thing to do. Yes, we've
>>>> added ____ helper. It helps to avoid some problems. Pair-inheritance
>>>> helps to avoid another problems. I understand, that there still may
>>>> other, not-covered problems, but better to be as safe as possible. And
>>>> inheritance here is native and correct thing to do, even with our ____
>>>> additional helper. What do you think?
>>>
>>> I wouldn't call it correct.  It's still unreliable, but less so than
>>> without the function name constraint.  That makes it less wrong.
>>
>> Agree.
>>
>>>
>>> 100% reliable would be nice, but not at any cost.  Something we're
>>> reasonably confident to get right should be good enough.
>>>
>>> To be confident, we need to understand the script's limitations, and how
>>> to compensate for them.  I figure we do now.  You too?
>>>
>>
>> I will not be surprised, if we missed some more interesting cases :)
>> But we should proceed. What is our plan? Will you queue v10 for 5.1?
> 
> v10's PATCH 1+2 look ready.  The error.h comment update could perhaps
> use some polish; I've focused my attention elsewhere.
> 
> PATCH 8-9 are generated.  They should never be rebased, always be
> regenerated.  We compare regenerated patches to posted ones to make sure
> they are still sane, and the R-bys are still valid.  I can take care of
> the comparing.
> 
> I'd like to have a pull request ready when the tree reopens for general
> development.  Let's use the time until then to get more generated
> patches out for review.
> 
> If I queue up patches in my tree, we shift the responsibility for
> regenerating patches from you to me, and create a coordination issue:
> you'll want to base patch submissions on the branch I use to queue this
> work, and that's going to be awkward when I rebase / regenerate that
> branch.  I think it's simpler to queue up in your tree until we're ready
> for a pull request.
> 
> When you post more patches, use
> 
>      Based-on: <20200317151625.20797-1-vsementsov@virtuozzo.com>
> 
> so that Patchew applies them on top of this series.  Hmm, probably won't
> do, as PATCH 9 already conflicts.
> 
> You could instead repost PATCH 1+2 with each batch.  I hope that's not
> too confusing.
> 
> I trust you'll keep providing a tag reviewers can pull.
> 
> I suggest to ask maintainers to leave merging these patches to me, in
> cover letters.
> 
> Makes sense?
> 

Hmm.

I remember what Kevin said about freeze period: maintainers will queue
a lot of patches in their "next" branches, and send pull requests at start
of next developing period. This highly possible will drop r-bs I can get now.
And reviewers will have to review twice.

And for the same reason, it's bad idea to queue in your branch a lot of patches
from different subsystems during freeze.

So, just postpone this all up to next development phase?
Markus Armbruster March 20, 2020, 4:23 p.m. UTC | #24
Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:

> 20.03.2020 16:58, Markus Armbruster wrote:
>> Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> writes:
[...]
>>> I will not be surprised, if we missed some more interesting cases :)
>>> But we should proceed. What is our plan? Will you queue v10 for 5.1?
>>
>> v10's PATCH 1+2 look ready.  The error.h comment update could perhaps
>> use some polish; I've focused my attention elsewhere.
>>
>> PATCH 8-9 are generated.  They should never be rebased, always be
>> regenerated.  We compare regenerated patches to posted ones to make sure
>> they are still sane, and the R-bys are still valid.  I can take care of
>> the comparing.
>>
>> I'd like to have a pull request ready when the tree reopens for general
>> development.  Let's use the time until then to get more generated
>> patches out for review.
>>
>> If I queue up patches in my tree, we shift the responsibility for
>> regenerating patches from you to me, and create a coordination issue:
>> you'll want to base patch submissions on the branch I use to queue this
>> work, and that's going to be awkward when I rebase / regenerate that
>> branch.  I think it's simpler to queue up in your tree until we're ready
>> for a pull request.
>>
>> When you post more patches, use
>>
>>      Based-on: <20200317151625.20797-1-vsementsov@virtuozzo.com>
>>
>> so that Patchew applies them on top of this series.  Hmm, probably won't
>> do, as PATCH 9 already conflicts.
>>
>> You could instead repost PATCH 1+2 with each batch.  I hope that's not
>> too confusing.
>>
>> I trust you'll keep providing a tag reviewers can pull.
>>
>> I suggest to ask maintainers to leave merging these patches to me, in
>> cover letters.
>>
>> Makes sense?
>>
>
> Hmm.
>
> I remember what Kevin said about freeze period: maintainers will queue
> a lot of patches in their "next" branches, and send pull requests at start
> of next developing period. This highly possible will drop r-bs I can get now.
> And reviewers will have to review twice.
>
> And for the same reason, it's bad idea to queue in your branch a lot of patches
> from different subsystems during freeze.
>
> So, just postpone this all up to next development phase?

Okay.  I hope we can process generated patches at a brisk pace then.
diff mbox series

Patch

diff --git a/scripts/coccinelle/auto-propagated-errp.cocci b/scripts/coccinelle/auto-propagated-errp.cocci
new file mode 100644
index 0000000000..7dac2dcfa4
--- /dev/null
+++ b/scripts/coccinelle/auto-propagated-errp.cocci
@@ -0,0 +1,327 @@ 
+// Use ERRP_AUTO_PROPAGATE (see include/qapi/error.h)
+//
+// Copyright (c) 2020 Virtuozzo International GmbH.
+//
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License as
+// published by the Free Software Foundation; either version 2 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program.  If not, see
+// <http://www.gnu.org/licenses/>.
+//
+// Usage example:
+// spatch --sp-file scripts/coccinelle/auto-propagated-errp.cocci \
+//  --macro-file scripts/cocci-macro-file.h --in-place \
+//  --no-show-diff --max-width 80 FILES...
+//
+// Note: --max-width 80 is needed because coccinelle default is less
+// than 80, and without this parameter coccinelle may reindent some
+// lines which fit into 80 characters but not to coccinelle default,
+// which in turn produces extra patch hunks for no reason.
+
+// Switch unusual Error ** parameter names to errp
+// (this is necessary to use ERRP_AUTO_PROPAGATE).
+//
+// Disable optional_qualifier to skip functions with
+// "Error *const *errp" parameter.
+//
+// Skip functions with "assert(_errp && *_errp)" statement, because
+// that signals unusual semantics, and the parameter name may well
+// serve a purpose. (like nbd_iter_channel_error()).
+//
+// Skip util/error.c to not touch, for example, error_propagate() and
+// error_propagate_prepend().
+@ depends on !(file in "util/error.c") disable optional_qualifier@
+identifier fn;
+identifier _errp != errp;
+@@
+
+ fn(...,
+-   Error **_errp
++   Error **errp
+    ,...)
+ {
+(
+     ... when != assert(_errp && *_errp)
+&
+     <...
+-    _errp
++    errp
+     ...>
+)
+ }
+
+// Add invocation of ERRP_AUTO_PROPAGATE to errp-functions where
+// necessary
+//
+// Note, that without "when any" the final "..." does not mach
+// something matched by previous pattern, i.e. the rule will not match
+// double error_prepend in control flow like in
+// vfio_set_irq_signaling().
+//
+// Note, "exists" says that we want apply rule even if it matches not
+// on all possible control flows (otherwise, it will not match
+// standard pattern when error_propagate() call is in if branch).
+@ disable optional_qualifier exists@
+identifier fn, local_err;
+symbol errp;
+@@
+
+ fn(..., Error **errp, ...)
+ {
++   ERRP_AUTO_PROPAGATE();
+    ...  when != ERRP_AUTO_PROPAGATE();
+(
+(
+    error_append_hint(errp, ...);
+|
+    error_prepend(errp, ...);
+|
+    error_vprepend(errp, ...);
+)
+    ... when any
+|
+    Error *local_err = NULL;
+    ...
+(
+    error_propagate_prepend(errp, local_err, ...);
+|
+    error_propagate(errp, local_err);
+)
+    ...
+)
+ }
+
+
+// Match functions with propagation of local error to errp.
+// We want to refer these functions in several following rules, but I
+// don't know a proper way to inherit a function, not just its name
+// (to not match another functions with same name in following rules).
+// Not-proper way is as follows: rename errp parameter in functions
+// header and match it in following rules. Rename it back after all
+// transformations.
+//
+// The simplest case of propagation scheme is single definition of
+// local_err with at most one error_propagate_prepend or
+// error_propagate on each control-flow. Still, we want to match more
+// complex schemes too. We'll warn them with help of further rules.
+@rule1 disable optional_qualifier exists@
+identifier fn, local_err;
+symbol errp;
+@@
+
+ fn(..., Error **
+-    errp
++    ____
+    , ...)
+ {
+     ...
+     Error *local_err = NULL;
+     ...
+(
+     error_propagate_prepend(errp, local_err, ...);
+|
+     error_propagate(errp, local_err);
+)
+     ...
+ }
+
+
+// Warn several Error * definitions.
+@check1 disable optional_qualifier exists@
+identifier fn = rule1.fn, local_err, local_err2;
+@@
+
+ fn(..., Error ** ____, ...)
+ {
+     ...
+     Error *local_err = NULL;
+     ... when any
+     Error *local_err2 = NULL;
+     ... when any
+ }
+
+@ script:python @
+fn << check1.fn;
+@@
+
+print('Warning: function {} has several definitions of '
+      'Error * local variable'.format(fn))
+
+// Warn several propagations in control flow.
+@check2 disable optional_qualifier exists@
+identifier fn = rule1.fn;
+symbol errp;
+position p1, p2;
+@@
+
+ fn(..., Error ** ____, ...)
+ {
+     ...
+(
+     error_propagate_prepend(errp, ...);@p1
+|
+     error_propagate(errp, ...);@p1
+)
+     ...
+(
+     error_propagate_prepend(errp, ...);@p2
+|
+     error_propagate(errp, ...);@p2
+)
+     ... when any
+ }
+
+@ script:python @
+fn << check2.fn;
+p1 << check2.p1;
+p2 << check2.p2;
+@@
+
+print('Warning: function {} propagates to errp several times in '
+      'one control flow: at {}:{} and then at {}:{}'.format(
+          fn, p1[0].file, p1[0].line, p2[0].file, p2[0].line))
+
+// Convert special case with goto separately.
+// I tried merging this into the following rule the obvious way, but
+// it made Coccinelle hang on block.c
+//
+// Note interesting thing: if we don't do it here, and try to fixup
+// "out: }" things later after all transformations (the rule will be
+// the same, just without error_propagate() call), coccinelle fails to
+// match this "out: }".
+@ disable optional_qualifier@
+identifier rule1.fn, rule1.local_err, out;
+symbol errp;
+@@
+
+ fn(..., Error ** ____, ...)
+ {
+     <...
+-    goto out;
++    return;
+     ...>
+- out:
+-    error_propagate(errp, local_err);
+ }
+
+// Convert most of local_err related stuff.
+//
+// Note, that we update everything related to matched by rule1
+// function name and local_err name. We may match something not
+// related to the pattern matched by rule1. For example, local_err may
+// be defined with the same name in different blocks inside one
+// function, and in one block follow the propagation pattern and in
+// other block doesn't. Or we may have several functions with the same
+// name (for different configurations).
+//
+// Note also that errp-cleaning functions
+//   error_free_errp
+//   error_report_errp
+//   error_reportf_errp
+//   warn_report_errp
+//   warn_reportf_errp
+// are not yet implemented. They must call corresponding Error* -
+// freeing function and then set *errp to NULL, to avoid further
+// propagation to original errp (consider ERRP_AUTO_PROPAGATE in use).
+// For example, error_free_errp may look like this:
+//
+//    void error_free_errp(Error **errp)
+//    {
+//        error_free(*errp);
+//        *errp = NULL;
+//    }
+@ disable optional_qualifier exists@
+identifier rule1.fn, rule1.local_err;
+expression list args;
+symbol errp;
+@@
+
+ fn(..., Error ** ____, ...)
+ {
+     <...
+(
+-    Error *local_err = NULL;
+|
+
+// Convert error clearing functions
+(
+-    error_free(local_err);
++    error_free_errp(errp);
+|
+-    error_report_err(local_err);
++    error_report_errp(errp);
+|
+-    error_reportf_err(local_err, args);
++    error_reportf_errp(errp, args);
+|
+-    warn_report_err(local_err);
++    warn_report_errp(errp);
+|
+-    warn_reportf_err(local_err, args);
++    warn_reportf_errp(errp, args);
+)
+?-    local_err = NULL;
+
+|
+-    error_propagate_prepend(errp, local_err, args);
++    error_prepend(errp, args);
+|
+-    error_propagate(errp, local_err);
+|
+-    &local_err
++    errp
+)
+     ...>
+ }
+
+// Convert remaining local_err usage. For example, different kinds of
+// error checking in if conditionals. We can't merge this into
+// previous hunk, as this conflicts with other substitutions in it (at
+// least with "- local_err = NULL").
+@ disable optional_qualifier@
+identifier rule1.fn, rule1.local_err;
+symbol errp;
+@@
+
+ fn(..., Error ** ____, ...)
+ {
+     <...
+-    local_err
++    *errp
+     ...>
+ }
+
+// Always use the same pattern for checking error
+@ disable optional_qualifier@
+identifier rule1.fn;
+symbol errp;
+@@
+
+ fn(..., Error ** ____, ...)
+ {
+     <...
+-    *errp != NULL
++    *errp
+     ...>
+ }
+
+// Revert temporary ___ identifier.
+@ disable optional_qualifier@
+identifier rule1.fn;
+@@
+
+ fn(..., Error **
+-   ____
++   errp
+    , ...)
+ {
+     ...
+ }
diff --git a/include/qapi/error.h b/include/qapi/error.h
index 30140d9bfe..56c133520d 100644
--- a/include/qapi/error.h
+++ b/include/qapi/error.h
@@ -214,6 +214,9 @@ 
  *         }
  *         ...
  *     }
+ *
+ * For mass-conversion use script
+ *   scripts/coccinelle/auto-propagated-errp.cocci
  */
 
 #ifndef ERROR_H
diff --git a/MAINTAINERS b/MAINTAINERS
index 857f969aa1..047f1b9714 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -1998,6 +1998,7 @@  F: include/qemu/error-report.h
 F: qapi/error.json
 F: util/error.c
 F: util/qemu-error.c
+F: scripts/coccinelle/*err*.cocci
 
 GDB stub
 M: Alex Bennée <alex.bennee@linaro.org>