Jonathan Beaudoin
Jonathan Beaudoin

Reputation: 2188

C++ Mac OS X 10.11.2 vm_read Giving Wrong Value

I'm trying to write a simple memory reader/writer on my mac operating system but I'm having an issue.

The writing aspect works fine, and even the vm_read returns KERN_SUCCESS. But when I try to print the buffer that I refer to in vm_read it gives me a wrong value.

#include <iostream>
#include <mach/mach_init.h>
#include <mach/mach.h>

using namespace std;

int main() {
    int start = 1337;
    int value = 100;

    uintptr_t buf;
    uint32_t bytesRead;

    task_t task;

    task_for_pid(current_task(), getpid(), &task);

    cout << "Step 1 (before write, should = 1337): " << start << endl;

    int reason = 0;
    if ((reason = vm_write(task, (uintptr_t) &start, (uintptr_t) &value, sizeof(int))) != KERN_SUCCESS) {
        cout << "Failed to write: " << reason << endl;
    }

    if ((reason = vm_read(task, (uintptr_t) &start, sizeof(int), &buf, &bytesRead)) != KERN_SUCCESS) {
        cout << "Failed to read: " << reason << endl;
    }

    cout << "Step 2 (after write, should = 100): " << buf << endl;
    return 0;
}

The following code outputs:

/Users/Jonathan/Library/Caches/CLion12/cmake/generated/4f3c65b6/4f3c65b6/Debug/helloworld
Step 1 (before write, should = 1337): 1337
Step 2 (after write, should = 100): 4415766528

Process finished with exit code 0

Step 2 should print 100 since I write a value of 100 to the start variable. (If I do cout << start << endl; it prints 100).

Any idea what is wrong? Thanks!

Upvotes: 1

Views: 530

Answers (1)

Bart Pelle
Bart Pelle

Reputation: 747

Try replacing step 2 with:

cout << "Step 2 (after write, should = 100): " << (*(int*)buf) << endl;

Buf is a pointer to the data you read, so you must dereference it to get the actual integer from there.

Upvotes: 1

Related Questions