/* =============================================================================
 * 05_frames_in_real_memory.c  --  stack frames on the real machine, and what
 *                                 happens when recursion runs out of stack
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The simulator showed one frame per active call. Do real frames look like
 *     that -- one block per call, each at a lower address than its caller's?
 *     How big is a frame on this machine?
 *   - The stack is not infinite (the slides: "8MB limit"). What happens when a
 *     recursion uses it all up? (The slides' "Runaway Stack Example".)
 *
 * [How to build & run]
 *   make                                   (builds native and x86-64 versions)
 *   ./build/05_frames_in_real_memory       native (arm64 on an Apple-Silicon Mac)
 *   ./build/05_frames_in_real_memory_x86   x86-64 (under Rosetta 2 on a Mac)
 *
 * [How to read the output]
 *   PART A prints the address of a local variable in 5 nested calls: the
 *   difference between two levels is the size of one frame. PART B lets a
 *   COPY of this program (made with fork) recurse with a 128 KiB local array
 *   until the stack is exhausted, and reports how deep it got and how it died.
 *   Addresses change from run to run (address-space randomization, Lecture 6);
 *   the differences do not.
 *
 * [Systems link / CS:APP 3.7, 9.9]
 *   The stack is one contiguous region with a fixed maximum size (the
 *   RLIMIT_STACK resource limit, usually 8 MiB for the main thread). Below it
 *   lies an unmapped "guard" region; touching it is a segmentation fault. That
 *   is the whole story of "stack overflow" in the sense of too-deep recursion.
 * -------------------------------------------------------------------------- */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/wait.h>

#define NOINLINE __attribute__((noinline))

/* --------------------------------------------------------------------------
 * PART A: the address of a local variable at each level of a recursion.
 * -------------------------------------------------------------------------- */

/*
 * [Idea] Record &local at every level. `local` must live in memory because
 *   its address is taken, and it is used AFTER the recursive call, so the
 *   compiler cannot turn the recursion into a loop (demo 04, PART E).
 * [Parameters] level -- current depth (0 for the first call); max -- deepest
 *   level; addrs -- array of max+1 slots that receives &local per level.
 * [Returns] the sum 0 + 1 + ... + max (just to use every local).
 * [Edge cases] max must be small (the array is fixed-size in main).
 */
NOINLINE static long depth_probe(int level, int max, uintptr_t *addrs)
{
    volatile long local = level;     /* [C tip] volatile: really store it in memory */
    addrs[level] = (uintptr_t)&local;
    if (level == max)
        return local;
    long r = depth_probe(level + 1, max, addrs);
    return r + local;
}

static void part_a(void)
{
    enum { LEVELS = 5 };
    uintptr_t addrs[LEVELS];
    long sum = depth_probe(0, LEVELS - 1, addrs);
    printf("PART A: &local in 5 nested calls of depth_probe (sum = %ld)\n", sum);
    for (int k = 0; k < LEVELS; k++) {
        printf("  level %d   &local = %#lx", k, (unsigned long)addrs[k]);
        if (k > 0)
            printf("   %lu bytes below level %d", (unsigned long)(addrs[k - 1] - addrs[k]), k - 1);
        printf("\n");
    }
    printf("  Each call's local sits a FIXED distance below its caller's: that distance\n"
           "  is one frame (return address, saved registers, the local, padding).\n\n");
}

/* --------------------------------------------------------------------------
 * PART B: the slides' runaway stack, run in a child process.
 * -------------------------------------------------------------------------- */

static int report_fd = -1;           /* pipe to the parent */

/* [Idea] Tell the parent "I reached depth d; my array is at a". write() goes
 *   straight to the kernel (no stdio buffer), so nothing is lost when the
 *   child dies suddenly. */
static void report(int depth, int x, const int *a)
{
    char buf[96];
    int n = snprintf(buf, sizeof buf, "%d %d %p\n", depth, x, (const void *)a);
    if (write(report_fd, buf, (size_t)n) < 0)
        _exit(2);
}

/*
 * [Idea] The slides' recurse(): every level has a 128 KiB local array, so the
 *   stack runs out after roughly 8 MiB / 128 KiB = 64 levels.
 * [Parameters] x -- countdown value; depth -- how many levels so far.
 * [Returns] -1 - (number of levels) if x reaches 0 (it never does here).
 * [Edge cases] a[0] is read again after the call, which keeps the array (and
 *   the frame) alive across the call, as in the original.
 */
NOINLINE static int recurse(int x, int depth)
{
    int a[1 << 15];                  /* 4 * 2^15 = 128 KiB */
    a[0] = (1 << 14) - 1;
    a[a[0]] = x - 1;
    report(depth, x, a);
    if (a[a[0]] == 0)
        return -1;
    int r = recurse(a[a[0]], depth + 1);
    return r - 1 + (a[0] - ((1 << 14) - 1));    /* = r - 1, but uses a[0] */
}

static void part_b(void)
{
    struct rlimit rl;
    getrlimit(RLIMIT_STACK, &rl);
    printf("PART B: runaway recursion with a 128 KiB array per call\n");
    printf("  stack size limit (RLIMIT_STACK, soft) = %lu KiB\n", (unsigned long)(rl.rlim_cur / 1024));

    int fds[2];
    if (pipe(fds) != 0) { perror("pipe"); return; }
    fflush(stdout);
    /* [Systems link] fork() makes a copy of this whole process (Lecture 16).
     * The COPY runs the runaway recursion and dies; this process survives,
     * collects its reports and asks the OS how it died (waitpid). */
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return; }
    if (pid == 0) {                                /* child */
        close(fds[0]);
        report_fd = fds[1];
        recurse(1000000, 1);                       /* would need ~122 GiB of stack */
        _exit(0);
    }
    close(fds[1]);                                 /* parent */
    char line[96];
    long first_a = 0, prev_a = 0, last_a = 0, step = 0;
    int last_depth = 0;
    FILE *in = fdopen(fds[0], "r");
    while (fgets(line, sizeof line, in)) {
        int d, x;
        void *a;
        if (sscanf(line, "%d %d %p", &d, &x, &a) != 3) continue;
        if (d <= 3)
            printf("  x = %d.  a at %p\n", x, a);
        if (d == 1) first_a = (long)a;
        if (d == 2) step = prev_a - (long)a;
        prev_a = (long)a;
        last_a = (long)a;
        last_depth = d;
    }
    fclose(in);
    int status;
    waitpid(pid, &status, 0);
    printf("  . . .\n  last report: depth %d, a at %#lx\n", last_depth, (unsigned long)last_a);
    if (WIFSIGNALED(status))
        printf("  the child was killed by signal %d (%s) -- a \"segmentation fault\"\n",
               WTERMSIG(status), strsignal(WTERMSIG(status)));
    else
        printf("  the child exited normally with status %d (unexpected)\n", WEXITSTATUS(status));
    printf("  frame size = %ld bytes (128 KiB array + %ld bytes of other frame data)\n",
           step, step - (1L << 17));
    printf("  stack used at the last report: %ld KiB of the %lu KiB limit\n",
           (first_a - last_a) / 1024 + step / 1024, (unsigned long)(rl.rlim_cur / 1024));
    printf("  predicted maximum depth = limit / frame size = %lu\n\n",
           (unsigned long)(rl.rlim_cur / (unsigned long)step));
}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#elif defined(__aarch64__)
    const char *arch = "arm64";
#else
    const char *arch = "unknown";
#endif
    printf("=== Demo 05: frames in real memory (%s) ===\n\n", arch);
    part_a();
    part_b();
    printf("Observations:\n");
    printf("  * Real frames are what the simulator showed: one block per active call,\n"
           "    each below its caller's, all the same size for the same function.\n");
    printf("  * The stack has a hard size limit. A recursion that needs more is killed\n"
           "    by the OS when it touches the unmapped page below the stack -- a\n"
           "    segmentation fault, not a C error message.\n");
    printf("  * Big local arrays make frames big: 128 KiB per call allows only ~63\n"
           "    levels. Put large data on the heap (malloc, Lectures 13-14) instead.\n");
    return 0;
}
