/***********************************************************
 * Stack exploit
 * 
 * (c) 2015 Cynthia Lee
 * 
 * This is an example of how you can overwrite the return
 * address in order to start executing code that is not
 * what was supposed to come next!
 ************************************************************/
 
#include "console.h"
#include "simpio.h"
using namespace std;

#include <iostream>

int fun1(int x);
int fun2(int x);
int fun3(int x);

int main() {
    setConsoleFont("Monospaced-18"); //bigger font for in-lecture display

    cout << "Starting main" << endl;
    int ret = fun1(77);
    cout << "Ending main: " << ret << endl;
    return 0;
}


int fun1(int x) {
    int arr[] = {1, 2};
    cout << endl << "Starting fun1(" << x << ")" << endl;
    for (int i = 0; i < 2; i++) {
        cout << "(" << arr + i << ") arr[" << i << "]: "
             << hex << arr[i] << endl;
    }
    int ret = fun2(x + arr[0]);
    cout << "Ending fun1" << endl;

    return arr[5] + ret;
}

int fun2(int x) {
    int arr[] = {3, 4};
    cout << endl << "Starting fun2(" << x << ")" << endl;

    for (int i = 0; i < 14; i++) {
        cout << "(" << arr + i << ") arr[" << i << "]: "
             << hex << arr[i] << endl;
    }
    int ret = fun3(x + arr[0]);
    cout << "Ending fun2" << endl;

    return arr[5] + ret;
}

int fun3(int x) {
    int arr[] = {5, 6};
    cout << endl << "Starting fun3(" << x << ")" << endl;

    for (int i = 0; i < 13; i++) {
        cout << "(" << arr + i << ") arr[" << i << "]: "
             << hex << arr[i] << endl;
    }

    arr[6] = 0x401999;
    cout << "Ending fun3" << endl;
    return x + arr[6];
}
