/* =============================================================================
 * 03_memory_referencing_bug.c  --  Reality #3: C gives you no memory
 *                                  protection; bugs act "at a distance".
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - What happens when you write one slot PAST the end of an array in C?
 *   - Why is the effect "system specific" -- fine for some indices, a wrong
 *     answer for others, a crash for others still?
 *   - How do the sanitizers (AddressSanitizer, UBSan) turn this silent horror
 *     into a loud, located error?
 *
 * [How to build & run]
 *   make  &&  ./03_memory_referencing_bug          # the raw bug, swept
 *   make asan  &&  ./03_memory_referencing_bug.asan 4   # caught by ASan
 *   make ubsan &&  ./03_memory_referencing_bug.ubsan 4  # caught by UBSan
 *   # (pass one index as an argument to run a single case without forking.)
 *
 * [How to read the output]
 *   With no argument we sweep i = 0..24, running EACH in a fresh child process
 *   (via fork) so that a crash in one case does not stop the sweep. For each i
 *   we print either the returned value of fun(i) or the signal that killed it.
 *   The textbook's classic cases are i = 2, 3 (wrong value) and higher i (crash).
 *
 * [Systems link / CS:APP 1.* and 3.10]
 *   This is Bryant & O'Hallaron's own example (Lecture 1, "Memory Referencing
 *   Bug"). The struct is laid out in memory as:
 *       offset 0 : a[0]   (4 bytes)
 *       offset 4 : a[1]   (4 bytes)
 *       offset 8 : d      (8 bytes, a double)
 *   Writing a[i] for i >= 2 steps OFF the 2-element array and into d, into
 *   padding, into the return address, or into whatever else happens to be on
 *   the stack. C does zero bounds checking: the write just happens. Whether it
 *   is harmless, corrupts a value, or crashes depends entirely on what is next
 *   to the array in memory -- and THAT depends on the compiler, the optimizer
 *   and the CPU architecture. That is why the result is "system specific".
 *
 * [Architecture note]
 *   CS:APP targets x86-64. This demo is architecture-SENSITIVE: which indices
 *   corrupt d, which land unnoticed in the caller's frame, and which segfault differ between
 *   x86-64 and arm64 because the two ABIs lay out and align the stack
 *   differently. The LESSON (undefined, system-specific) is the same; the
 *   exact index->effect table is not. The code README reports both.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>     /* atoi, exit                                          */
#include <string.h>     /* strsignal                                           */
#include <unistd.h>     /* fork, _exit                                         */
#include <sys/wait.h>   /* waitpid, WIFSIGNALED, WTERMSIG, WEXITSTATUS         */

/* The textbook struct. `volatile` on the local in fun() keeps the optimizer    */
/* from deleting the "useless" store and read, so we observe real memory.        */
typedef struct {
    int    a[2];   /* a 2-element array: valid indices are ONLY 0 and 1         */
    double d;      /* sits right after the array                                */
} struct_t;

/* ---------------------------------------------------------------------------
 * fun  --  the buggy function, verbatim from CS:APP.
 *
 * [Idea]
 *   Store 3.14 into d, then store a big value into a[i]. For i in {0,1} that is
 *   legal. For i >= 2 it writes outside the array -- undefined behavior. We mark
 *   it noinline so the compiler cannot dissolve the whole thing away.
 * [Parameters] i -- the (possibly out-of-bounds) array index.
 * [Returns] the value of d afterward, as a double.
 * [Edge cases] i >= 2 or i < 0 is out of bounds: result is undefined and
 *   system-specific -- possibly 3.14 (untouched), possibly a corrupted double,
 *   possibly a crash before this function even returns.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static double fun(int i) {
    volatile struct_t s;
    s.d = 3.14;
    s.a[i] = 1073741824;        /* 1073741824 = 2^30 = 0x40000000              */
    return s.d;
}

/* ---------------------------------------------------------------------------
 * run_one  --  run fun(i) in a FRESH CHILD PROCESS and report the outcome.
 *
 * [Idea]
 *   Because some indices crash the program (segmentation fault), we cannot just
 *   call fun() in a loop -- the first crash would end everything. fork() makes a
 *   copy of the process; the child runs the risky call and the parent survives
 *   to wait() for it and report how it ended. This "sacrificial child" pattern
 *   is itself a preview of Lectures 16-17 (processes and exceptional control
 *   flow): a signal such as SIGSEGV is the kernel turning a hardware fault into
 *   something the parent can observe.
 * [Parameters] i -- the index to test.
 * [Returns] void; prints one line.
 * [Edge cases] if fork() fails it returns -1; we report that and move on.
 * ------------------------------------------------------------------------- */
static void run_one(int i) {
    fflush(stdout);            /* [C tip] flush now so the child does not       */
                               /* inherit and later re-print buffered text.     */
    pid_t pid = fork();        /* returns 0 in the child, child's pid in parent */
    if (pid < 0) {
        printf("  i=%2d  fork failed\n", i);
        return;
    }
    if (pid == 0) {            /* ---- child ----                               */
        double r = fun(i);
        printf("  i=%2d  fun(i) = %.15g\n", i, r);
        fflush(stdout);
        _exit(0);              /* _exit, not exit: do not re-run atexit/buffers */
    }
    /* ---- parent ----                                                         */
    int status;
    waitpid(pid, &status, 0);  /* block until this child finishes               */
    if (WIFSIGNALED(status)) { /* did a signal kill it (e.g. SIGSEGV)?          */
        int sig = WTERMSIG(status);
        printf("  i=%2d  killed by signal %d (%s)\n", i, sig, strsignal(sig));
    }
    /* if it exited normally the child already printed its line                 */
}

int main(int argc, char **argv) {
    printf("=== Demo 03: a memory-referencing bug that acts at a distance ===\n");
    printf("struct_t layout: a[0]@0, a[1]@4, d@8 (bytes). Valid a[] indices: 0,1.\n\n");

    if (argc > 1) {
        /* Single-case mode: used by the ASan/UBSan targets so the sanitizer    */
        /* reports cleanly without the fork noise.                              */
        int i = atoi(argv[1]);
        double r = fun(i);
        printf("fun(%d) = %.15g\n", i, r);
        return 0;
    }

    printf("Sweeping i = 0..24, each in its own child process:\n");
    for (int i = 0; i <= 24; i++)
        run_one(i);

    printf("\nObservations:\n");
    printf("  * i=0,1: legal, returns 3.14.\n");
    printf("  * i=2,3: writes into the bytes of d -> fun returns a CORRUPTED\n");
    printf("    double (e.g. 3.1399998664856, 2.00000061035156), no crash, no\n");
    printf("    warning. This is the dangerous case: a wrong ANSWER.\n");
    printf("  * larger i: eventually writes over the return address or off the\n");
    printf("    stack -> the kernel delivers SIGSEGV (segmentation fault).\n");
    printf("  * EXACTLY which i does which depends on compiler/optimizer/CPU --\n");
    printf("    that is what 'system specific' means. Run the .asan / .ubsan\n");
    printf("    builds (see the Makefile) to turn this into a located error.\n");
    printf("  * C and C++ give NO memory protection (Reality #3). Safer languages\n");
    printf("    bounds-check; in C you use tools (ASan, UBSan, valgrind) instead.\n");
    return 0;
}
