https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105310

Fritz Reese <foreese at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
     Ever confirmed|0                           |1
             Status|UNCONFIRMED                 |ASSIGNED
   Last reconfirmed|                            |2022-04-19
           Assignee|unassigned at gcc dot gnu.org      |foreese at gcc dot 
gnu.org

--- Comment #1 from Fritz Reese <foreese at gcc dot gnu.org> ---
Created attachment 52834
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=52834&action=edit
Patch which fixes the bug based on trunk

The bug is caused by gfc_conv_union_initializer in gcc/fortran/trans-expr.cc,
which accepts a pointer to a vector of constructor trees (vec<constructor_elt,
va_gc>*) as an argument, then appends one or two field constructors to the
vector. The problem is the use of CONSTRUCTOR_APPEND_ELT(v, ...) within
gfc_conv_union_initializer, which modifies the vector pointer v when a
reallocation of the vector occurs, but the pointer is passed by value.
Therefore, when a vector reallocation occurs, the vector caller's
(gfc_conv_structure) vector pointer is not updated and subsequently points to
freed memory. Chaos ensues.

The bug only occurs when gfc_conv_union_initializer itself triggers the
reallocation, which is whenever the vector is "full" (v->m_vecpfx.m_alloc ==
v->m_vecpfx.m_num). Since the vector defaults to allocating 8 elements and
doubles in size for every reallocation, the bug only occurs when there are 8,
16, 32, etc... fields with initializers prior to the union, causing the vector
of constructors to be resized when entering gfc_conv_union_initializer. The
-finit-derived and -finit-local-zero options together ensure each field has an
initializer, triggering the bug.

The patch fixes the bug by passing the vector pointer to
gfc_conv_union_initializer by reference, matching the signature of
vec_safe_push from within the CONSTRUCTOR_APPEND_ELT macro.

Reply via email to