From 3bff6a8446ca17f4d4140a128a5db979ca22d241 Mon Sep 17 00:00:00 2001 From: Alex Hedges Date: Thu, 8 Dec 2022 15:45:14 -0500 Subject: [PATCH] Fix StackOverflowError when a wire is connected to itself During each tick, electrical components are checked for whether they connect to ground with the help of the method `Terminal.connectsToGround()`. The method contains a `maxSteps` parameter that is decremented on each recursive call to prevent infinite recursion. However, the value of `maxSteps` was never checked, so the method would recurse infinitely until the stack overflowed when one terminal of a wire was connected to the other terminal. Adding checks to stop recursing when `maxSteps` reaches 0 prevents the error. --- .../objects/electricalcomponent/ElectricalComponent.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/simulator/src/main/scala/scienceworld/objects/electricalcomponent/ElectricalComponent.scala b/simulator/src/main/scala/scienceworld/objects/electricalcomponent/ElectricalComponent.scala index b4d450fb..6615bc1c 100644 --- a/simulator/src/main/scala/scienceworld/objects/electricalcomponent/ElectricalComponent.scala +++ b/simulator/src/main/scala/scienceworld/objects/electricalcomponent/ElectricalComponent.scala @@ -219,7 +219,7 @@ class Terminal(val parentObject:EnvObject, _name:String = "terminal") extends En return false } // Other terminal doesn't exist or is not connected in a switch, return false // Other terminal exists, traverse/recurse - if ( otherTerminal.get.connectsToGround(maxSteps-1) == true) { + if ( maxSteps > 0 && otherTerminal.get.connectsToGround(maxSteps-1) == true) { //println("true2") return true } // If the recursive case returns true, then that pin connects to ground. If it doesn't, continue on other connections. @@ -237,7 +237,7 @@ class Terminal(val parentObject:EnvObject, _name:String = "terminal") extends En return false } // Other terminal doesn't exist or is not connected in a switch, return false // Other terminal exists, traverse/recurse - if ( otherTerminal.get.connectsToGround(maxSteps-1) == true) { + if ( maxSteps > 0 && otherTerminal.get.connectsToGround(maxSteps-1) == true) { //println("true2") return true } // If the recursive case returns true, then that pin connects to ground. If it doesn't, continue on other connections. @@ -259,7 +259,7 @@ class Terminal(val parentObject:EnvObject, _name:String = "terminal") extends En return false } // Other terminal doesn't exist or is not connected in a switch, return false // Other terminal exists, traverse/recurse - if ( otherTerminal.get.connectsToGround(maxSteps-1) == true) { + if ( maxSteps > 0 && otherTerminal.get.connectsToGround(maxSteps-1) == true) { //println("true2") return true } // If the recursive case returns true, then that pin connects to ground. If it doesn't, continue on other connections.