mirror of
https://github.com/cirosantilli/linux-kernel-module-cheat.git
synced 2026-01-23 02:05:57 +01:00
mmap anonymous
This commit is contained in:
@@ -5,18 +5,27 @@
|
||||
#include <stdlib.h>
|
||||
|
||||
int main(void) {
|
||||
size_t bytes = sizeof(int) * 2;
|
||||
/* Allocate 2 ints. */
|
||||
int *is = malloc(bytes);
|
||||
int *is;
|
||||
size_t nbytes = 2 * sizeof(*is);
|
||||
|
||||
/* Allocate 2 ints. Note that unlike traditional stack arrays (non-VLA)
|
||||
* this value does not have to be determined at compile time! */
|
||||
is = malloc(nbytes);
|
||||
|
||||
/* This can happen for example if we ask for too much memory. */
|
||||
if (is == NULL) {
|
||||
perror("malloc");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Write to and read from the allocated memory. */
|
||||
is[0] = 1;
|
||||
is[1] = 2;
|
||||
assert(is[0] == 1);
|
||||
assert(is[1] == 2);
|
||||
|
||||
/* Free the allocated memory. */
|
||||
free(is);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
This directory contains glibc extensions to POSIX / ANSI C.
|
||||
@@ -1 +0,0 @@
|
||||
../build
|
||||
@@ -1 +0,0 @@
|
||||
../test
|
||||
40
userland/linux/mmap_anonymous.c
Normal file
40
userland/linux/mmap_anonymous.c
Normal file
@@ -0,0 +1,40 @@
|
||||
/* https://cirosantilli.com/linux-kernel-module-cheat#mmap-map-anonymous */
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void) {
|
||||
int *is;
|
||||
size_t nbytes = 2 * sizeof(*is);
|
||||
|
||||
/* Allocate 2 ints. */
|
||||
is = mmap(
|
||||
NULL,
|
||||
nbytes,
|
||||
PROT_READ | PROT_WRITE,
|
||||
MAP_SHARED | MAP_ANONYMOUS,
|
||||
-1,
|
||||
0
|
||||
);
|
||||
|
||||
/* This can happen for example if we ask for too much memory. */
|
||||
if (is == NULL) {
|
||||
perror("mmap");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Write to and read from the allocated memory. */
|
||||
is[0] = 1;
|
||||
is[1] = 2;
|
||||
assert(is[0] == 1);
|
||||
assert(is[1] == 2);
|
||||
|
||||
/* Free the allocated memory. */
|
||||
munmap(is, nbytes);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -1,13 +1,4 @@
|
||||
/* https://cirosantilli.com/linux-kernel-module-cheat#mmap
|
||||
*
|
||||
* Example of mmap on files.
|
||||
*
|
||||
* Create a file, mmap to it, write to maped memory, close.
|
||||
*
|
||||
* Then read the file and confirm it was written to.
|
||||
*
|
||||
* Implemented in Linux by the mmap syscall.
|
||||
*/
|
||||
/* https://cirosantilli.com/linux-kernel-module-cheat#mmap-file */
|
||||
|
||||
#define _XOPEN_SOURCE 700
|
||||
#include <assert.h>
|
||||
|
||||
Reference in New Issue
Block a user