[PATCH] fortran: Fix UB in transfer_expr [PR124450]

Jakub Jelinek <[email protected]>
Newsgroups gmane.comp.gcc.patches,gmane.comp.gcc.fortran
Message-ID <abJztBPi1SsylNUy@tucnak>
Hi!

trans-io.cc (transfer_array_component) calls transfer_expr with
NULL code:
  transfer_expr (&se, &cm->ts, tmp, NULL, NULL_TREE);
I'm surprised it doesn't ICE in other spots that dereference
code->whatever but each one is guarded with some condition
that perhaps don't trigger in that case for some reason.
Anyway, the &code->loc case does trigger, it doesn't ICE, but
it is undefined behavior in the compiler when code is NULL,
and we'd crash if the where argument of 3*sizeof(void*) is
dereferenced.  Code I've checked can handle NULL where though.

Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?

2026-03-12  Jakub Jelinek  <[email protected]>

	PR fortran/124450
	* trans-io.cc (transfer_expr): If code is NULL, call
	transfer_array_component with NULL where argument rather than
	&code->loc.

	* gfortran.dg/pr124450.f90: New test.

--- gcc/fortran/trans-io.cc.jj	2026-01-08 09:44:44.078248379 +0100
+++ gcc/fortran/trans-io.cc	2026-03-11 15:33:59.334057907 +0100
@@ -2513,7 +2513,9 @@ transfer_expr (gfc_se * se, gfc_typespec
 
 		  if (c->attr.dimension)
 		    {
-		      tmp = transfer_array_component (tmp, c, & code->loc);
+		      tmp = transfer_array_component (tmp, c,
+						      code ? &code->loc
+						      : NULL);
 		      gfc_add_expr_to_block (&se->pre, tmp);
 		    }
 		  else
--- gcc/testsuite/gfortran.dg/pr124450.f90.jj	2026-03-11 15:48:59.240915829 +0100
+++ gcc/testsuite/gfortran.dg/pr124450.f90	2026-03-11 15:53:08.482724401 +0100
@@ -0,0 +1,14 @@
+! PR fortran/124450
+! { dg-do compile }
+
+  type ta
+    integer(kind=4) :: a(1)
+    integer(kind=4) :: b(1)
+  end type ta
+  type tb
+    type(ta) :: c(1) = ta(1, 2)
+  end type tb
+  type(tb) :: e = tb(ta(3, 4))
+
+  print *, e
+end

	Jakub
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.