anotherCode245
anotherCode245

Reputation: 703

What is an easy way to trigger a page fault?

I'm looking for an easy way to trigger a real page fault (and not a segfault resulting from accessing an already mapped address or a protected address).

What could be one?

I thought of simply run

int main(void) {
    int *x = 1000;
    *x = 2000;
}

But it does not seem to result in a page fault but rather a memory violation.

Upvotes: 2

Views: 3612

Answers (3)

Michael F
Michael F

Reputation: 40869

If you're on Linux, you can also exploit fork(2)'s copy-on-write behaviour:

#include <unistd.h>
int main()
{
    int pid = 0, retcode = 0, poof = 0;
    if ((pid = fork()) == 0) {
        poof = 1; /* Page fault */
    } else {
        waitpid(pid, &retcode, 0);
    }
    return 0;
}

Another way to do it is:

#include <unistd.h>
int main()
{
    long pagesize = sysconf(_SC_PAGESIZE);
    unsigned char *p = malloc(pagesize + 1); /* Cross page boundaries. Page fault may occur depending on your allocator / libc implementation. */
    p[0] = 0;        /* Page fault. */
    p[pagesize] = 1; /* Page fault. */
    return 0;
}

Upvotes: 3

BЈовић
BЈовић

Reputation: 64283

If you are on linux, you can emulate segmentation fault and bus error by sending signals to the process. See man signal.

To emulate segmentation fault of a process with pid=1234, type in terminal :

kill -s 11 1234

To emulate bus error of a process with pid=1234, type in terminal :

kill -s 10 1234

In c, you can use raise() or kill() function

#include <sys/types.h>
#include <signal.h>

int main() {
    raise(SIGBUS);

    return 0;
}

Upvotes: 0

Lee Duhem
Lee Duhem

Reputation: 15121

I believe mmap() a disk file, and read from or write to it should be enough. At least it is enough on Linux.

Upvotes: 3

Related Questions