11/*
2- * Copyright (c) 2016, 2022 , Oracle and/or its affiliates. All rights reserved.
2+ * Copyright (c) 2016, 2025 , Oracle and/or its affiliates. All rights reserved.
33 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44 *
55 * This code is free software; you can redistribute it and/or modify it
2929import java .lang .reflect .Field ;
3030import java .lang .reflect .InvocationTargetException ;
3131import java .lang .reflect .Method ;
32+ import java .util .Collections ;
33+ import java .util .IdentityHashMap ;
34+ import java .util .Set ;
3235import java .util .stream .IntStream ;
3336import jdk .jshell .spi .ExecutionControl ;
3437import jdk .jshell .spi .SPIResolutionException ;
@@ -335,10 +338,15 @@ private static boolean needsEscape(int idx, int cp) {
335338 * @throws ExecutionControl.InternalException for internal problems
336339 */
337340 protected String throwConvertedInvocationException (Throwable cause ) throws RunException , InternalException {
338- throw asRunException (cause );
341+ // Guard against recursive cause chains by
342+ // using a Set with identity equality semantics.
343+ Set <Throwable > dejaVu = Collections .newSetFromMap (new IdentityHashMap <>());
344+ dejaVu .add (cause );
345+
346+ throw asRunException (cause , dejaVu );
339347 }
340348
341- private RunException asRunException (Throwable ex ) {
349+ private RunException asRunException (Throwable ex , Set < Throwable > dejaVu ) {
342350 if (ex instanceof SPIResolutionException ) {
343351 SPIResolutionException spire = (SPIResolutionException ) ex ;
344352 return new ResolutionException (spire .id (), spire .getStackTrace ());
@@ -347,7 +355,14 @@ private RunException asRunException(Throwable ex) {
347355 ex .getClass ().getName (),
348356 ex .getStackTrace ());
349357 Throwable cause = ex .getCause ();
350- ue .initCause (cause == null ? null : asRunException (cause ));
358+ if (cause != null ) {
359+ Throwable throwable = dejaVu .add (cause )
360+ ? asRunException (cause , dejaVu )
361+ : new UserException ("CIRCULAR REFERENCE!" ,
362+ cause .getClass ().getName (),
363+ cause .getStackTrace ());
364+ ue .initCause (throwable );
365+ }
351366 return ue ;
352367 }
353368 }
0 commit comments