Skip to contentSkip to conversation

Adding statement after declarations with zero-length match after

cocci Mats Kindahl 3 participants 10 messages Feb 15, 2025 – Feb 17, 2025

lore
Share & tools
lore
#0 lore raw

Hi again,

Here is one case again that is stumping me. Suppose that we want to write an SmPL to replace dynamic allocations inside a function where the allocated object is not visible outside the function. For example, consider this example:

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

   struct magic {
      int i_val;
      float f_val;
   };

   extern void magic_init(struct magic *);

   void foo_2(void) {
      struct magic more = malloc(sizeof(struct magic));
      more->i_val = 1;
      printf("%d", more->i_val);
      free(more);
   }

Here we want this to be rewritten to

   void foo_2(void) {
      struct magic more;
      magic_init(&more);
      more.i_val = 1;
      printf("%d", more.i_val);
   }

However, if we for some reason return the pointer, we do not want it to be rewritten.

   struct magic *foo_3(void) {
      struct magic *ptr = malloc(sizeof(struct magic));
      ptr->i_val = 1;
      printf("%d", ptr->i_val);
      return ptr;
   }

There are a few more cases, but this is the basics. In particular I ignore assigning to and from the variable as well as calling other functions, because this is not part of the problem right now. Note that I want the call to "magic_init()" to be after all the declarations.

Using the following semantic script, we want to capture these cases and replace it with a stack allocation. This requires rewriting internal references as well, so we have a piece at the end that updates the references. Here I use the pattern of catching the case with a base rule, and then using that in a dependent rule. This allows be to capture the malloc call to a local idexpression but find the identifier when it is being declared so that I can replace it.

   @base exists@
   type T;
   local idexpression T *var;
   position p1;
   @@
      var@p1 = malloc(sizeof(T))
      ... when forall
          when != return var;

@depends on patch exists@
type base.T;
position base.p1, p2;
identifier var, fld;
statement S,S1;
@@
(
- T@p2 *var;

   + T var;
      ...
   - var@p1 = malloc(sizeof(T));
   + magic_init(&var);
   |
   - T@p2 *var@p1 = malloc(sizeof(T));
   + T var;
      ... when != S
   + magic_init(&var);
      S1

)
  ... when any
(
- free(var);
|
- *var
+ var
|
- var->fld
+ var.fld
|
- var
+ &var
)

However, since I match S1 after the added "magic_init(&var)", this means that the statement "more->i_val = 1;" does not get a replacement and the result is this:

   mats@abzu:~/lang/cocci/hacks$ spatch -D patch --cocci-file
   elim-malloc-free.cocci code/dynalloc.c
   init_defs_builtins: /usr/lib/coccinelle/standard.h
   (ONCE) Expected tokens malloc
   HANDLING: code/dynalloc.c
   diff =
   diff -u -p a/dynalloc.c b/dynalloc.c
   --- a/dynalloc.c
   +++ b/dynalloc.c
   @@ -9,10 +9,10 @@ struct magic {
   extern void magic_init(struct magic *);

void foo_2(struct magic *out) {
-  struct magic *ptr = malloc(sizeof(struct magic));
+  struct magic ptr;

   +  magic_init(&ptr);
      ptr->i_val = 1;

-  printf("%d", ptr->i_val);
-  free(ptr);
+  printf("%d", ptr.i_val);
}

I've tried various constructions, including:

* Skipping S1, but it insists that it needs a token to attach to.
* Using a ( ... & ... ) to match a statement and do the replacement, but it insists that it needs a token to attach to.
* Using declaration list before, but again, it needs a token to attach to.

In essence, I need some kind of "zero-length match" that can follow the replacement.

Any suggestions?

Best wishes,
Mats Kindahl

#1 lore raw
Quoted 79 lines · Mats Kindahl

Hi again,

Here is one case again that is stumping me. Suppose that we want to write an SmPL to replace dynamic allocations inside a function where the allocated object is not visible outside the function. For example, consider this example:

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

      struct magic {
        int i_val;
        float f_val;
      };

      extern void magic_init(struct magic *);

      void foo_2(void) {
        struct magic more = malloc(sizeof(struct magic));
        more->i_val = 1;
        printf("%d", more->i_val);
        free(more);
      }

Here we want this to be rewritten to

      void foo_2(void) {
        struct magic more;
        magic_init(&more);
        more.i_val = 1;
        printf("%d", more.i_val);
      }

However, if we for some reason return the pointer, we do not want it to be rewritten.

      struct magic *foo_3(void) {
        struct magic *ptr = malloc(sizeof(struct magic));
        ptr->i_val = 1;
        printf("%d", ptr->i_val);
        return ptr;
      }

There are a few more cases, but this is the basics. In particular I ignore assigning to and from the variable as well as calling other functions, because this is not part of the problem right now. Note that I want the call to "magic_init()" to be after all the declarations.

Using the following semantic script, we want to capture these cases and replace it with a stack allocation. This requires rewriting internal references as well, so we have a piece at the end that updates the references. Here I use the pattern of catching the case with a base rule, and then using that in a dependent rule. This allows be to capture the malloc call to a local idexpression but find the identifier when it is being declared so that I can replace it.

      @base exists@
      type T;
      local idexpression T *var;
      position p1;
      @@
        var@p1 = malloc(sizeof(T))
        ... when forall
            when != return var;

      @depends on patch exists@
      type base.T;
      position base.p1, p2;
      identifier var, fld;
      statement S,S1;
      @@
      (
      - T@p2 *var;
      + T var;
        ...
      - var@p1 = malloc(sizeof(T));
      + magic_init(&var);
      |
      - T@p2 *var@p1 = malloc(sizeof(T));
      + T var;
        ... when != S
      + magic_init(&var);
        S1
      )
        ... when any
      (
      - free(var);
      |
      - *var
Quoted 8 lines
      + var
      |
      - var->fld
      + var.fld
      |
      - var
      + &var
      )

You can try

(
+ magic_init(&var);
S1 & <... ( - free(var); | and so on ) ...> )
&
<...
(
- free(var);
|
// other cases
)
...>
)

I would suggest to separate the second rule into two, which will require duplicating the first rule, because you can't inherit a position over a change. I will play around with it shortly and get back to you.

julia

Quoted 39 lines

However, since I match S1 after the added "magic_init(&var)", this means that the statement "more->i_val = 1;" does not get a replacement and the result is this:

      mats@abzu:~/lang/cocci/hacks$ spatch -D patch --cocci-file elim-malloc-free.cocci code/dynalloc.c
      init_defs_builtins: /usr/lib/coccinelle/standard.h
      (ONCE) Expected tokens malloc
      HANDLING: code/dynalloc.c
      diff =  
      diff -u -p a/dynalloc.c b/dynalloc.c
      --- a/dynalloc.c
      +++ b/dynalloc.c
      @@ -9,10 +9,10 @@ struct magic {
      extern void magic_init(struct magic *);
       
      void foo_2(struct magic *out) {
      -  struct magic *ptr = malloc(sizeof(struct magic));
      +  struct magic ptr;
      +  magic_init(&ptr);
        ptr->i_val = 1;
      -  printf("%d", ptr->i_val);
      -  free(ptr);
      +  printf("%d", ptr.i_val);
      }

I've tried various constructions, including:

 *  Skipping S1, but it insists that it needs a token to attach to.
 *  Using a ( ... & ... ) to match a statement and do the replacement, but it insists that it needs a token to attach to.
 *  Using declaration list before, but again, it needs a token to attach to.

In essence, I need some kind of "zero-length match" that can follow the replacement.

Any suggestions?

Best wishes,
Mats Kindahl

#2 lore raw
Quoted 104 lines · Julia Lawall
Quoted 78 lines · Mats Kindahl

Hi again,

Here is one case again that is stumping me. Suppose that we want to write an SmPL to replace dynamic allocations inside a function where the allocated object is not visible outside the function. For example, consider this example:

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

       struct magic {
         int i_val;
         float f_val;
       };

       extern void magic_init(struct magic *);

       void foo_2(void) {
         struct magic more = malloc(sizeof(struct magic));
         more->i_val = 1;
         printf("%d", more->i_val);
         free(more);
       }

Here we want this to be rewritten to

       void foo_2(void) {
         struct magic more;
         magic_init(&more);
         more.i_val = 1;
         printf("%d", more.i_val);
       }

However, if we for some reason return the pointer, we do not want it to be rewritten.

       struct magic *foo_3(void) {
         struct magic *ptr = malloc(sizeof(struct magic));
         ptr->i_val = 1;
         printf("%d", ptr->i_val);
         return ptr;
       }

There are a few more cases, but this is the basics. In particular I ignore assigning to and from the variable as well as calling other functions, because this is not part of the problem right now. Note that I want the call to "magic_init()" to be after all the declarations.

Using the following semantic script, we want to capture these cases and replace it with a stack allocation. This requires rewriting internal references as well, so we have a piece at the end that updates the references. Here I use the pattern of catching the case with a base rule, and then using that in a dependent rule. This allows be to capture the malloc call to a local idexpression but find the identifier when it is being declared so that I can replace it.

       @base exists@
       type T;
       local idexpression T *var;
       position p1;
       @@
         var@p1 = malloc(sizeof(T))
         ... when forall
             when != return var;

       @depends on patch exists@
       type base.T;
       position base.p1, p2;
       identifier var, fld;
       statement S,S1;
       @@
       (
       - T@p2 *var;
       + T var;
         ...
       - var@p1 = malloc(sizeof(T));
       + magic_init(&var);
       |
       - T@p2 *var@p1 = malloc(sizeof(T));
       + T var;
         ... when != S
       + magic_init(&var);
         S1
       )
         ... when any
       (
       - free(var);
       |
       - *var
Quoted 8 lines
       + var
       |
       - var->fld
       + var.fld
       |
       - var
       + &var
       )

You can try

(

+ magic_init(&var);
   S1 & <... ( - free(var); | and so on ) ...> )

&
<...
(
- free(var);
|
// other cases
)
...>
)

Quoted 3 lines

I would suggest to separate the second rule into two, which will require duplicating the first rule, because you can't inherit a position over a change. I will play around with it shortly and get back to you.

Thanks Julia!

Splitting the rules worked and does what I expect:

   @base2 exists@
   type T;
   local idexpression T *var;
   position p1;
   expression E;
   @@
      var@p1 = malloc(sizeof(T))
      ... when forall
          when != return var;
          when != E = var
          when != var = E

@depends on patch exists@
type base2.T;
position base2.p1;
identifier var;
identifier fld;
@@
  var@p1 = malloc(sizeof(T))
  ... when any
(
- free(var);
|
- *var
+ var
|
- var->fld
+ var.fld
|
- var
+ &var
)

   @base3 exists@
   type T;
   local idexpression T *var;
   position p1;
   expression E;
   @@
      var@p1 = malloc(sizeof(T))
      ... when forall
          when != return var;
          when != E = var
          when != var = E

@depends on patch exists@
type base3.T;
position base3.p1, p2;
identifier var;
statement S,S1;
@@
(
- T@p2 *var;

   + T var;
      ...
   - var@p1 = malloc(sizeof(T));
   + magic_init(&var);
   |
   - T@p2 *var@p1 = malloc(sizeof(T));
   + T var;
      ... when != S
   + magic_init(&var);
      S1

)

Best wishes,
Mats Kindahl

#3 lore raw
Quoted 1 line

Splitting the rules worked and does what I expect:

Interesting …

…

Quoted 1 line

@depends on patch exists@…

I suggest to reconsider the need for such SmPL dependency specifications once more.

Regards,
Markus

#4 lore raw
In reply to Mats Kindahl

I tried the following, in line with what I previously suggested:

virtual patch

@bad1@
type T;
local idexpression T *var;
position p1;
@@
var@p1 = malloc(sizeof(T))
...
return var;

@depends on patch@
type T;
position p1 != bad1.p1;
identifier var, fld;
@@
- T *var;
+ T var;
...
- var@p1 = malloc(sizeof(T));
+ magic_init(&var);
<...
(
- free(var);
|
- *var
+ var
|
- var->fld
+ var.fld
|
- var
+ &var
)
...>

@bad2@
type T;
local idexpression T *var;
position p1;
@@
var@p1 = malloc(sizeof(T))
...
return var;

@depends on patch@
type T;
position p1 != bad2.p1;
identifier var, fld;
statement S,S1;
@@

- T *var@p1 = malloc(sizeof(T));
+ T var;
... when != S
(
<...
(
- free(var);
|
- *var
+ var
|
var
- ->fld
+ .fld
|
- var
+ &var
)
...>
&
+ magic_init(&var);
S1
)

-----------------------------

You matched the case that you want in the first rule with a forall. I instead matched the case that is not wanted, and then check that the position later is different from that one.

I'm not sure which is better. My approach may turn out to be expensive if some functions include multiple mallocs. An approach could be to add a positive rule after the negative one, eg:

@good1@
type T;
identifier var;
position p1 != bad2.p1;
@@

var@p1 = malloc(sizeof(T));

and then inherit good1.p1 into the rule that makes the change.

Then, as compared to what I previously suggested, I switched the branches of the & in the last rule. This parses, while the other way doesn't. This seems like an undesirable feature, because the way I wrote it previously had the S1 pattern marking a place of interest in the first branch, but we may as well follow what already works.

Another issue is that if S1 starts with *var, there will be an already tagged token error, because there is one transformation that changes *var and another that adds magic_init(&var); just before *var. I guess having *var as the start of S1 would be unlikely. But this is why I write:

var
- ->fld
+ .fld

to leave the start of the statement matching S1 unchanged.

There would be a problem if S1 matches a free(var) as well; again this case seems unlikely.

julia

#5 lore raw
Quoted 78 lines · Julia Lawall

I tried the following, in line with what I previously suggested:

virtual patch

@bad1@
type T;
local idexpression T *var;
position p1;
@@
var@p1 = malloc(sizeof(T))
...
return var;

@depends on patch@
type T;
position p1 != bad1.p1;
identifier var, fld;
@@
- T *var;

+ T var;
   ...

- var@p1 = malloc(sizeof(T));
+ magic_init(&var);
<...
(
- free(var);
|
- *var
+ var
|
- var->fld
+ var.fld
|
- var
+ &var
)
...>

@bad2@
type T;
local idexpression T *var;
position p1;
@@
var@p1 = malloc(sizeof(T))
...
return var;

@depends on patch@
type T;
position p1 != bad2.p1;
identifier var, fld;
statement S,S1;
@@

- T *var@p1 = malloc(sizeof(T));

+ T var;
   ... when != S

(
<...
(
- free(var);
|
- *var
+ var
|
var
- ->fld
+ .fld
|
- var
+ &var
)
...>
&

+ magic_init(&var);
   S1

)

Quoted 8 lines

-----------------------------

You matched the case that you want in the first rule with a forall. I instead matched the case that is not wanted, and then check that the position later is different from that one.

I'm not sure which is better. My approach may turn out to be expensive if some functions include multiple mallocs.

I tried this approach on a large code base, and it seems to be significantly faster. This approach took about 2 seconds, the one I attempted took more than 2 minutes. Going to check that it matches the same things, but otherwise this seems a lot better.

Thanks for the help Julia,
Mats Kindahl

#6 lore raw
Quoted 1 line

I tried this approach on a large code base, and it seems to be significantly faster. This approach took about 2 seconds, the one I attempted took more than 2 minutes. Going to check that it matches the same things, but otherwise this seems a lot better.

Would we like to clarify software run time characteristics in more detail with any additional tools?

Regards,
Markus

#7 lore raw

Re: [cocci] Software evolution for special handling of pointers?

In reply to Julia Lawall

…

Quoted 2 lines

Then, as compared to what I previously suggested, I switched the branches of the & in the last rule. This parses, while the other way doesn't.

Do you indicate an open issue here for the handling of an SmPL conjunction which would be similar to my bug report.
How to fix a parse error for a detailed SmPL disjunction? 2024-10-05
https://github.com/coccinelle/coccinelle/issues/379

Quoted 8 lines

This seems like an undesirable feature, because the way I wrote it previously had the S1 pattern marking a place of interest in the first branch, but we may as well follow what already works.

Another issue is that if S1 starts with *var, there will be an already tagged token error, because there is one transformation that changes *var and another that adds magic_init(&var); just before *var. I guess having *var as the start of S1 would be unlikely. But this is why I

…

Quoted 2 lines

There would be a problem if S1 matches a free(var) as well; again this case seems unlikely.

How will source code transformation concerns evolve further for affected implementation details?

Regards,
Markus

#8 lore raw
In reply to Mats Kindahl

…

Quoted 1 line

However, if we for some reason return the pointer, we do not want it to be rewritten.…

I guess that such a data processing requirement will trigger various software development challenges.

Regards,
Markus