Skip to content

Commit

Permalink
#Centipede Use recursion level instead of stack limit as the error co…
Browse files Browse the repository at this point in the history
…ndition.

This is because on some platforms (MacOS) stack limit is not enforced (in my experiments), which causes the puzzle to timeout.

PiperOrigin-RevId: 678252582
  • Loading branch information
xinhaoyuan authored and copybara-github committed Sep 24, 2024
1 parent 22ca8ff commit b0efd83
Showing 1 changed file with 4 additions and 15 deletions.
19 changes: 4 additions & 15 deletions centipede/puzzles/deep_recursion.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// Centipede puzzle: deep recursion that may cause stack overflow.
// Centipede puzzle: use callstack features to reach deep recursion
// clang-format off
// RUN: Run --callstack_level=10 --use_cmp_features=0 --max_len=10 --num_runs=10000000 # NOLINT
// RUN: SolutionIs ABCDEF
Expand All @@ -21,25 +21,14 @@

#include <cstddef>
#include <cstdint>
#include <cstdlib>

#include "absl/base/nullability.h"

// Set the stack size to something small (64K).
static struct rlimit rlim = {1 << 16, 1 << 16};
static int unused = setrlimit(RLIMIT_STACK, &rlim);

// Don't let the compiler be too smart.
static inline void BreakOptimization(absl::Nonnull<const void *> arg) {
__asm__ __volatile__("" : : "r"(arg) : "memory");
}

// Causes deep recursion on inputs like "ABCDEFGHIJKLMNOPQRSTUVWXYZABC...".
// Has a large stack frame, so that a relatively shallow recursion will overflow
// the stack.
// Deep recursion triggered by 'ABCDEF...'
void Recursive(const uint8_t *data, size_t size, size_t idx) {
if (idx > 5) std::abort();
if (idx >= size) return;
char large_stack_object[1024 * 16];
BreakOptimization(&large_stack_object[0]);
if (data[idx] == 'A' + (idx % 26)) Recursive(data, size, idx + 1);
}

Expand Down

0 comments on commit b0efd83

Please sign in to comment.