From fe8d87ef9521f75c958ff7b7d18f447cf2f215d2 Mon Sep 17 00:00:00 2001 From: Ross Nordby Date: Sat, 13 Jan 2024 15:34:37 -0600 Subject: [PATCH] Guarded against stackalloc-induced overflow for large compounds. --- .../CompoundPairOverlapFinder.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/BepuPhysics/CollisionDetection/CollisionTasks/CompoundPairOverlapFinder.cs b/BepuPhysics/CollisionDetection/CollisionTasks/CompoundPairOverlapFinder.cs index c019cdb1..ddf7ef78 100644 --- a/BepuPhysics/CollisionDetection/CollisionTasks/CompoundPairOverlapFinder.cs +++ b/BepuPhysics/CollisionDetection/CollisionTasks/CompoundPairOverlapFinder.cs @@ -26,7 +26,18 @@ public static unsafe void FindLocalOverlaps(ref Buffer pairs, } overlaps = new CompoundPairOverlaps(pool, pairCount, totalCompoundChildCount); ref var pairsToTest = ref overlaps.pairQueries; - var subpairData = stackalloc SubpairData[totalCompoundChildCount]; + //Stack overflows are very possible with larger compounds! Guard against it. + Buffer subpairData; + const int stackallocThreshold = 1024; + if (totalCompoundChildCount <= stackallocThreshold) + { + var memory = stackalloc SubpairData[totalCompoundChildCount]; + subpairData = new Buffer(memory, totalCompoundChildCount); + } + else + { + subpairData = new Buffer(totalCompoundChildCount, pool); + } int nextSubpairIndex = 0; for (int i = 0; i < pairCount; ++i) { @@ -112,8 +123,10 @@ out GatherScatter.Get(ref maximumRadius, j), } //Doesn't matter what mesh/compound instance is used for the function; just using it as a source of the function. Debug.Assert(totalCompoundChildCount > 0); - Unsafe.AsRef(pairsToTest[0].Container).FindLocalOverlaps(ref pairsToTest, pool, shapes, ref overlaps); - + Unsafe.AsRef(pairsToTest[0].Container).FindLocalOverlaps(ref pairsToTest, pool, shapes, ref overlaps); + + if (subpairData.Length > stackallocThreshold) + subpairData.Dispose(pool); } }