Skip to content

Constituent registration aliases memory in both directions (host <-> framework; use-after-free bugs) #797

Open

Description

@climbfuji

Description

Three use-after-free bugs with one root cause: constituent registration shares
pointers between the framework and the host model, in both directions.

The framework stores pointers into memory the host owns, the host stores a
pointer into memory the framework owns, and the lifetime and ordering rules that
keep all of them valid are nowhere stated. All four constituent-exercising
end-to-end tests violat at least one. They pass anyway, because of how glibc
handles freed blocks and because stale reads return plausible data.

The framework keeps pointers in two places:

  • ccpp_hash_table.F90:312,335 — entry_value => newval, where newval is the
    class(ccpp_hashable_t), target dummy of add_hash_key
  • ccpp_constituent_prop_mod.F90:114 — ccpp_constituent_prop_ptr_t holds
    type(ccpp_constituent_properties_t), pointer :: prop, and const_metadata(:)
    is an array of those wrappers

Both are reached through generated ccpp_register_constituents
(capgen/generator/host_constituents.py:181 emits
const_prop => host_constituents(index)) → new_field →
ccp_model_const_add_metadata, whose dummy is
type(ccpp_constituent_properties_t), target, intent(in) :: field_data
(ccpp_constituent_prop_mod.F90:1258) → add_hash_key.

The host's pointer runs the other way: ccp_model_const_data_lock allocates
this%vars_layer (:1561), ccp_field_data_ptr hands it out as
const_ptr => this%vars_layer (:1953), and the generated
ccpp_constituents_array() returns that to the host.

Bug 1 — the host's constituent array must outlive the constituent tables

There is no rule for it, intent(in) suggests the opposite, and under F2018 8.5.17
the association is not even guaranteed to survive the call if a compiler chooses
copy-in/copy-out at either hop.

end-to-end-tests/instances_advection/main.F90 deallocates and reallocates its
host_consts array once per instance. For instance 1, the table points into freed
memory. Observable as a SIGSEGV at address 0x0 under LLVM 23.1.2
(flang-new) on an NRL HPC, in _FortranAAssign under ccp_properties_get_key.

Before the crash, ccp_model_const_data_lock reads each constituent's
default_value and min_value through the same stale pointers.

Bug 2 — the constituent tables must be torn down before ccpp_final

ccpp_final → <suite>_final frees the per-suite
<suite>_dynamic_constituents buffer. ccpp_deallocate_dynamic_constituents
then calls ccp_model_const_reset, which loops over const_metadata(:) and
reads framework_owns_me to decide whether to deallocate this%prop.
The free/don't-free decision is made based on invalid/freed memory. Under
glibc the flag turns out to be a stale .false., nothing visibly breaks.

All four advection end-to-end-tests used the wrong order: ccpp_final
first, constituent teardown second. The intended order is the reverse,
see capgen/generator/host_constituents.py:532-537: the buffers are deliberately
not freed in ccpp_deallocate_dynamic_constituents because <suite>_final
owns them — which only works if constituent teardown has already run. The
dependency is one-directional, thus reordering the calls in the tests is safe.

Bug 3 — the host model pointers into the constituent array

This bug affects the advection and advection_auto_clone end-to-end tests.

phys_state%q is declared real(kind=kind_phys), dimension(:,:,:), pointer
(advection/test_host_data.F90:12) and pointer-assigned from the framework's
array: advection/test_host.F90:373 takes ccpp_constituents_array(), and in
test_host_data.F90:92: state%q => constituents.

ccp_model_const_reset frees vars_layer at :1626, and nothing
nullifies, notifies, or flags the host pointer that still refers to it. Reading
phys_state%q after constituent teardown is reading freed memory.

For both advection and advection_auto_clone, the final answer check
(compare_data) runs after ccpp_deallocate_dynamic_constituents. Before fixing
bug 2, this was harmless, because the teardown came afterwards. The correct order
is ccpp_physics_final → verification → constituent teardown → ccpp_final.
We don't hvae any documentation for that.

Steps to Reproduce

CCPP Framework branch feature/capgen-v1 commit 207cb1b, i.e. before
#795. No modifications otherwise.

  1. Bug 1: build end-to-end-tests with LLVM 23.1.2 (flang-new) and run
    instances_advection/test_instances_advection.x → SIGSEGV, fault address
    0x0. Alternatively, run through valgrind --track-origins=yes with any compiler.
  2. Bug 2: build with gfortran and -fsanitize=address, then run the suite.
    9 of 13 tests pass; the four that exercise constituents —
    test_constituents_dim, test_advection, test_instances_advection,
    test_advection_auto_clone — all abort with heap-use-after-free.
  3. Bug 3: with the sanitizer build, apply only the bug-2 reorder (move
    ccpp_deallocate_dynamic_constituents above ccpp_final) and re-run.

Steps 2 and 3 use the end-to-end-tests-asan job added in #795.

Additional Context

  • Machine: NRL Atlantis (bug 1); GitHub Actions ubuntu-22.04 (bugs 2 and 3)
  • Compiler: LLVM 23.1.2 (flang-new); bug 1 also reproduces under valgrind with
    GNU, bugs 2 and 3 under GNU with AddressSanitizer. Basic GNU builds pass all
    three.
  • No host model is affected today — multi-instance constituents are not yet used
    by any host — so this is framework-internal for now. Bug 1 blocks a change
    request (LLVM compiler update) on the HPC above.

Proposed long-term solution

#795 fixes the hosts and adds the sanitizer job, but leaves the implementation
as is: any host that frees its constituent list after registration, finalizes
before tearing down constituents, or reads its own phys_state%q afterwards
reproduces them. Suggested next steps from Claude (verbatim) - to be discussed:

<claude verbatim>

  1. The framework should own the properties it is given. Add
    class(ccpp_hashable_t), allocatable :: owned to table_entry_t and insert
    with allocate(entry%owned, source=newval); entry%entry_value => entry%owned,
    with const_metadata(i)%prop pointing at the owned copy. This closes bugs 1
    and 2
    at once: registration becomes a snapshot the caller may free
    immediately, and <suite>_final freeing or <suite>_register reallocating
    its buffers no longer invalidates anything, so teardown order stops
    mattering. It also removes the framework_owns_me read-through-a-foreign-
    pointer in ccpt_deallocate, since ownership becomes structural rather than a
    flag.
    This looks viable because nothing outside the framework reads const_index
    back off a host-owned object — every consumer goes through
    ccpp_model_constituents_obj(...)%const_index(...) by standard name, in
    generated code, the e2e hosts and CAM-SIMA alike — so the write-back
    table_lock performs through those pointers is only consumed internally.

  2. Make the host's borrowed pointer safe, or make the contract explicit.
    Bug 3 is not fixed by item 1, because here the framework owns the array and
    the host borrows it. Two options:

    • Document and enforce. State in doc/ and in the generated
      ccpp_constituents_array docstring that the returned pointer is valid only
      between ccpp_initialize_constituents and
      ccpp_deallocate_dynamic_constituents, and that the host must not read it
      afterwards. Cheap, but it is another unwritten-contract-made-written, and
      bug 2 shows how well hosts follow those.
    • Remove the hazard. Have ccp_model_const_reset leave vars_layer
      allocated and free it only at object destruction, or hand the host a copy
      instead of a pointer. Costs a copy of an ncols x nlev x nconst array per
      host.
      I [Claude] lean to documenting it for now and revisiting if a host trips over it,
      since the lifetime here is at least bounded by two calls the host makes
      itself — unlike bug 2, where the hazard was in the framework's own teardown
      path.
  3. Give host_constituents an instance dimension, following the rule the
    rest of the API already follows: the generated signature already gains
    instance, ninstances only when the pair is in the control metadata, and
    per-instance host data is already declared
    dimensions = (number_of_instances) and subscripted by the framework.
    host_constituents is the one argument whose rank does not follow, which is
    why instances currently share one properties object and one const_index,
    and why different instances cannot register different constituents. Open
    question: rectangular (n_consts, ninstances) is simpler but forces every
    instance to register the same number of constituents; a ragged per-instance
    list mirroring ccpp_dyn_const_buffer_t (items(:)) handles differing
    counts, which is the point of the change. Single-instance hosts see no change
    either way.

  4. Fail loudly rather than segfault: ccp_properties_get_key
    (ccpp_constituent_prop_mod.F90:364) and ccpp_hashable_char_get_key
    (ccpp_hashable.F90:60) read a deferred-length allocatable with no
    allocated() check, which is what turns a dangling entry into a segfault
    instead of a diagnostic; ccp_get_standard_name (:554-557) already guards
    the same component. Worth doing after item 1, so a guard never masks a
    dangling pointer as a silently missing constituent.

  5. Keep the end-to-end-tests-asan job. This bug class is invisible to a
    passing test: without a memory checker it surfaces only when a new compiler
    or allocator lays memory out differently. It found bug 2 on its first run and
    bug 3 on its second.

</claude verbatim>

Activity

  1. added
    bug
    on Nov 3, 2026
  2. self-assigned this
    on Nov 3, 2026
  3. added
    capgen
    on Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugcapgen

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions