On Fri, Mar 17, 2023 at 01:18:32PM +0100, Richard Biener wrote:
> The following adds a missing range-op for __builtin_expect which
> helps -Wuse-after-free to detect the case a realloc original
> pointer is used when the result was NULL.
> 
> Bootstrap and regtest running on x86_64-unknown-linux-gnu, OK?
> 
>       PR tree-optimization/109170
>       * gimple-range-op.cc (cfn_expect): New.
>       (gimple_range_op_handler::maybe_builtin_call): Handle
>       __builtin_expect.
> 
>       * gcc.dg/Wuse-after-free-pr109170.c: New testcase.

Shouldn't that be something we handle generically for all
ERF_RETURNS_ARG calls (and not just for irange, but for any
supported ranges)?

Though, admittedly __builtin_expect probably doesn't set that
and all the other current builtins with ERF_RETURNS_ARG return
pointers I think.

So, I think LGTM, but give Andrew/Aldy a chance to chime in.

> diff --git a/gcc/gimple-range-op.cc b/gcc/gimple-range-op.cc
> index a5d625387e7..f3d6e29e58d 100644
> --- a/gcc/gimple-range-op.cc
> +++ b/gcc/gimple-range-op.cc
> @@ -309,6 +309,25 @@ public:
>    }
>  } op_cfn_constant_p;
>  
> +// Implement range operator for integral CFN_BUILT_IN_EXPECT.
> +class cfn_expect : public range_operator
> +{
> +public:
> +  using range_operator::fold_range;
> +  virtual bool fold_range (irange &r, tree, const irange &lh,
> +                        const irange &, relation_trio) const
> +  {
> +    r = lh;
> +    return true;
> +  }
> +  virtual bool op1_range (irange &r, tree, const irange &lhs,
> +                       const irange &, relation_trio) const
> +  {
> +    r = lhs;
> +    return true;
> +  }
> +} op_cfn_expect;
> +
>  // Implement range operator for CFN_BUILT_IN_SIGNBIT.
>  class cfn_signbit : public range_operator_float
>  {
> @@ -966,6 +985,12 @@ gimple_range_op_handler::maybe_builtin_call ()
>        m_int = &op_cfn_parity;
>        break;
>  
> +    case CFN_BUILT_IN_EXPECT:
> +      m_valid = true;
> +      m_op1 = gimple_call_arg (call, 0);
> +      m_int = &op_cfn_expect;
> +      break;
> +
>      default:
>        break;
>      }
> diff --git a/gcc/testsuite/gcc.dg/Wuse-after-free-pr109170.c 
> b/gcc/testsuite/gcc.dg/Wuse-after-free-pr109170.c
> new file mode 100644
> index 00000000000..fa7dc66d66c
> --- /dev/null
> +++ b/gcc/testsuite/gcc.dg/Wuse-after-free-pr109170.c
> @@ -0,0 +1,15 @@
> +/* { dg-do compile } */
> +/* { dg-options "-O2 -Wuse-after-free" } */
> +
> +unsigned long bufmax = 0;
> +unsigned long __open_catalog_bufmax;
> +void *realloc(void *, __SIZE_TYPE__);
> +void free(void *);
> +
> +void __open_catalog(char *buf)
> +{
> +  char *old_buf = buf;
> +  buf = realloc (buf, bufmax);
> +  if (__builtin_expect ((buf == ((void *)0)), 0))
> +    free (old_buf); /* { dg-bogus "used after" } */
> +}
> -- 
> 2.35.3

        Jakub

Reply via email to