#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main(void) {
    long page = sysconf(_SC_PAGESIZE);
    if (page <= 0) return 1;
    size_t size = (size_t)page;

    // 1. Allocate anonymous memory (read/write: RW)
    void *area = mmap(NULL, size, PROT_READ | PROT_WRITE,
                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (area == MAP_FAILED) { perror("mmap"); return 1; }

    // Write a byte to memory (test RW access)
    ((unsigned char *)area)[0] = 0x90; // NOP byte
    printf("pid=%ld area=%p size=%zu (State: RW)\n", (long)getpid(), area, size);
    fflush(stdout);

    // Wait five seconds to inspect /proc/<pid>/maps
    sleep(5);

    // 2. Change memory permissions to read/execute (RX)
    if (mprotect(area, size, PROT_READ | PROT_EXEC) == -1) {
        perror("mprotect");
        munmap(area, size);
        return 1;
    }
    puts("mprotect changed permissions to RX; no code is executed in this region!");
    fflush(stdout);

    // Wait another five seconds to inspect the mapping change
    sleep(5);

    // 3. Release the mapping
    if (munmap(area, size) == -1) { perror("munmap"); return 1; }
    return 0;
}
