/* =============================================================================
 * 03_memory_layout.c  --  where does everything go? (the slides' example)
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - A running program has code, global data, a heap and a stack (and shared
 *     libraries). Where is each one in the address space?
 *   - Small and huge malloc blocks: do they come from the same place?
 *   - Do the addresses stay the same from one run to the next?
 *
 * [How to build & run]
 *   make && ./build/03_memory_layout
 *   (it runs ITSELF three times with --once and compares the three runs)
 *
 * [How to read the output]
 *   One row per object, highest address first (like the slides' picture,
 *   stack at the top). The three address columns are three separate runs.
 *   The last column says which parts of the address changed between runs.
 *
 * [Systems link / CS:APP 3.10.1, 9.7-9.9]
 *   These are VIRTUAL addresses (Lectures 11-12): each process sees its own
 *   private 2^47-byte address space, and the OS maps the pieces in use to
 *   physical memory. Modern systems deliberately place the pieces at
 *   RANDOM positions in every run (address-space layout randomization,
 *   ASLR) -- one of the defenses in this lecture.
 * -------------------------------------------------------------------------- */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* [C tip] `static` here means "visible only in this file" (Lecture 7); it
 * also keeps the macOS linker from warning about these huge arrays. */
static char big_array[1L << 24];      /* 16 MiB of zero-initialized globals (.bss) */
static char huge_array[1L << 30];     /* 1 GiB (the slides use 2 GiB) */
int global = 0;

int useless(void) { return 0; }

#define NOBJ 11

/* [Idea] Print every object's address as "name address" lines. */
static void once(void)
{
    void *phuge1, *psmall2, *phuge3, *psmall4;
    int local = 0;
    phuge1 = malloc(1L << 28);     /* 256 MiB */
    psmall2 = malloc(1L << 8);     /* 256 B   */
    phuge3 = malloc(1L << 32);     /*   4 GiB: only reserved, never touched */
    psmall4 = malloc(1L << 8);     /* 256 B   */
    printf("local %p\n", (void *)&local);
    printf("phuge1 %p\n", phuge1);
    printf("phuge3 %p\n", phuge3);
    printf("psmall4 %p\n", psmall4);
    printf("psmall2 %p\n", psmall2);
    printf("big_array %p\n", (void *)big_array);
    printf("huge_array %p\n", (void *)huge_array);
    printf("global %p\n", (void *)&global);
    printf("main() %p\n", (void *)(uintptr_t)&once);
    printf("useless() %p\n", (void *)(uintptr_t)&useless);
    printf("printf() %p\n", (void *)(uintptr_t)&printf);
    free(phuge1); free(psmall2); free(phuge3); free(psmall4);
}

struct row { char name[16]; unsigned long addr[3]; };

static const char *kind(const char *name)
{
    if (!strcmp(name, "local")) return "stack";
    if (!strncmp(name, "phuge", 5)) return "huge malloc block";
    if (!strncmp(name, "psmall", 6)) return "small malloc block (heap)";
    if (!strcmp(name, "printf()")) return "shared library (libc)";
    if (strstr(name, "()")) return "text (code)";
    return "data (globals)";
}

int main(int argc, char **argv)
{
    if (argc > 1 && !strcmp(argv[1], "--once")) {
        once();
        return 0;
    }
    struct row rows[NOBJ];
    memset(rows, 0, sizeof rows);
    for (int run = 0; run < 3; run++) {
        char cmd[1024];
        snprintf(cmd, sizeof cmd, "'%s' --once", argv[0]);
        FILE *p = popen(cmd, "r");                  /* run this program again */
        if (!p) { perror("popen"); return 1; }
        char name[16];
        void *addr;
        for (int k = 0; k < NOBJ && fscanf(p, "%15s %p", name, &addr) == 2; k++) {
            strcpy(rows[k].name, name);
            rows[k].addr[run] = (unsigned long)addr;
        }
        pclose(p);
    }
    for (int a = 1; a < NOBJ; a++)                   /* sort by run-1 address, high first */
        for (int b = a; b > 0 && rows[b].addr[0] > rows[b - 1].addr[0]; b--) {
            struct row t = rows[b]; rows[b] = rows[b - 1]; rows[b - 1] = t;
        }
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 03: memory layout of a running program (%s) ===\n\n", arch);
    printf("  %-11s %-18s %-18s %-18s %-26s %s\n", "object", "run 1", "run 2", "run 3",
           "region", "bits that changed");
    int lib_moved = 0, code_moved = 0, lo_code = -1, lo_stack = -1;
    for (int k = 0; k < NOBJ; k++) {
        unsigned long d = rows[k].addr[0] ^ rows[k].addr[1];
        d |= rows[k].addr[0] ^ rows[k].addr[2];
        int hi = 0, lo = 0;
        while (d >> hi) hi++;                            /* highest differing bit + 1 */
        while (d && !((d >> lo) & 1)) lo++;              /* lowest differing bit */
        char changed[64];
        if (d == 0) strcpy(changed, "none");
        else snprintf(changed, sizeof changed, "%d..%d", lo, hi - 1);
        if (!strcmp(rows[k].name, "printf()")) lib_moved = d != 0;
        if (!strcmp(rows[k].name, "main()")) { code_moved = d != 0; lo_code = d ? lo : -1; }
        if (!strcmp(rows[k].name, "local")) lo_stack = d ? lo : -1;
        printf("  %-11s %#-18lx %#-18lx %#-18lx %-26s %s\n", rows[k].name, rows[k].addr[0],
               rows[k].addr[1], rows[k].addr[2], kind(rows[k].name), changed);
    }
    printf("\nObservations:\n");
    printf("  * Code and globals sit together, low in the address space (main(),\n"
           "    useless(), global and the two arrays are a few MiB apart).\n");
    if (!strcmp(rows[0].name, "local"))
        printf("  * The stack is the highest region, as in the slides' Linux picture.\n");
    else
        printf("  * Unlike the slides' Linux picture (stack at the very top, 0x7ff...),\n"
               "    this OS puts the main thread's stack BELOW the malloc regions: the\n"
               "    OS chooses the layout; C and the hardware do not care.\n");
    printf("  * Small and huge malloc blocks come from different places, gigabytes\n"
           "    apart: the allocator maps huge requests separately.\n");
    printf("  * Stack, heap, code and globals move %s every run (ASLR). Code and\n"
           "    globals move as ONE block: the distances inside it never change. The\n"
           "    lowest bit of main() that changed is bit %d, so its offset inside a\n"
           "    page (the low 12 bits) is the same in every run: whole pages move.\n",
           code_moved ? "in" : "NOT in", lo_code);
    if (lo_stack >= 0 && lo_stack < 12)
        printf("    The stack also moved by a small amount INSIDE a page (bit %d changed).\n",
               lo_stack);
    if (!lib_moved)
        printf("  * printf() in the shared C library did NOT move: macOS randomizes the\n"
               "    shared-library region once per BOOT, not per process (Linux does it\n"
               "    per process).\n");
    else
        printf("  * The shared C library (printf) moves too, in every run.\n");
    printf("  * The 1 GiB array and the 4 GiB malloc cost nothing until touched: virtual\n"
           "    memory only reserves addresses (Lectures 11-12).\n");
    return 0;
}
