From aecc85e3d5f9bf80934af90ad3ec8cafbd42f88b Mon Sep 17 00:00:00 2001 From: Axel Kohlmeyer Date: Sat, 21 Jun 2025 16:37:21 -0400 Subject: [PATCH] avoid out-of-bounds memory access when registering fix external callbacks --- fortran/lammps.f90 | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/fortran/lammps.f90 b/fortran/lammps.f90 index 6d55eb4fc0..d296f7c870 100644 --- a/fortran/lammps.f90 +++ b/fortran/lammps.f90 @@ -3440,6 +3440,7 @@ CONTAINS TYPE(c_ptr) :: c_id, c_caller TYPE(c_funptr) :: c_callback INTEGER :: i, this_fix + TYPE(fix_external_data), DIMENSION(:), ALLOCATABLE :: tmp_ext_data c_id = f2c_string(id) IF (ALLOCATED(ext_data)) THEN @@ -3451,9 +3452,13 @@ CONTAINS END IF END DO IF (this_fix > SIZE(ext_data)) THEN - ! reallocates ext_data; this requires us to re-bind "caller" on the C + ! reallocate ext_data in a pre-fortran 2008 compatible way. + ALLOCATE(tmp_ext_data(this_fix)) + tmp_ext_data(1:this_fix-1) = ext_data(1:this_fix-1) + tmp_ext_data(this_fix) = fix_external_data() + CALL move_alloc(tmp_ext_data, ext_data) + ! this requires us to re-bind "caller" on the C ! side to the new data structure, which likely moved to a new address - ext_data = [ext_data, fix_external_data()] ! extends ext_data by 1 CALL rebind_external_callback_data() END IF ELSE