On 06/18/2016 05:55 PM, Martin Sebor wrote:


I think detecting potentially problematic uses of alloca would
be useful, especially when done in an intelligent way like in
your patch (as opposed to simply diagnosing every call to
the function regardless of the value of its argument).  At
the same time, it seems that an even more reliable solution
than pointing out potentially unsafe calls to the function
and relying on users to modify their code to use malloc for
large/unbounded allocations would be to let GCC do it for
them automatically (i.e., in response to some other option,
emit a call to malloc instead, and insert a call to free when
appropriate).
As Joseph pointed out, this may not be valid in certain contexts. THough it is an interesting idea.


I found the "warning: unbounded use of alloca" misleading when
a call to the function was, in fact, bounded but to a limit
that's greater than alloca-max-size as in the program below:

  void f (void*);

  void g (int n)
  {
    void *p;
    if (n < 4096)
      p = __builtin_alloca (n);
    else
      p = __builtin_malloc (n);
    f (p);
  }
  t.C: In function ā€˜gā€™:
  t.C:7:7: warning: unbounded use of alloca [-Walloca]
       p = __builtin_alloca (n);

I would suggest to rephrase the diagnostic to mention the limit,
e.g.,

  warning: calling alloca with an argument in excess of '4000'
  bytes
Agreed.


As a separate enhancement, since in the (idiomatic) example
above the malloc memory is allowed to leak, issuing a distinct
warning for it would help detect this class of bugs that's
likely to be common as users replace unbounded uses of alloca
with malloc in response to the new option and forget to free
the memory.  Diagnosing freeing the alloca memory would be
a nice touch as well.
Aldy and I have been kicking around additional warnings in this space. It's a good idea I'll encourage him to add.

I also think that VLA diagnostics would be better controlled
by a separate option, and emit a different diagnostic (one
that mentions VLA rather than alloca).
Probably wise -- I wouldn't necessarily expect everyone to understand the relationship between the VLA language construct and how it's implemented in GCC in terms of stack allocations.



 Although again, and
for VLAs even more so than for alloca, providing an option
to have GCC use dynamic allocation, would be an even more
robust solution than issuing warnings.  IIRC, this was the
early implementation of VLAs in GCC so there is a precedent
for it.  (Though this seems complementary to the warnings.)
In addition, I'm of the opinion that potentially unbounded
VLA allocation should be checked at runtime and made trap on
size overflow in C and throw an exception in C++ (e.g., when
int a [A][B] when A * B * sizeof (int) exceeds SIZE_MAX / 2
or some runtime-configurable limit).  My C++ patch for bug
69517 does just that (it needs to be resubmitted with the
runtime configuration limit added).
Right.

Jeff

Reply via email to