Skip to content

Instantly share code, notes, and snippets.

@a10y
Created September 24, 2016 21:33
Show Gist options
  • Select an option

  • Save a10y/2167314d7ed2b638ed64f06ccb811a30 to your computer and use it in GitHub Desktop.

Select an option

Save a10y/2167314d7ed2b638ed64f06ccb811a30 to your computer and use it in GitHub Desktop.
/**
* mm-test: A simple test of using mmap() to manipulate files as if they are
* regions of memory. This example has full error checking, and allows the user
* to specify a file, as well as replacement text and an optional offset value.
*
* Andrew Duffy, 2016
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
int
main(int argc, char *argv[])
{
int fd, offset = 0;
char *ptr;
struct stat st;
if (argc < 3) {
fprintf(stderr, "Usage: %s FILE \"TEXT\" [OFFSET]\n", argv[0]);
return 1;
}
if (argc == 4) {
offset = atoi(argv[3]);
}
if ((fd = open(argv[1], O_RDWR)) < 0) {
fprintf(stderr, "Error, could not open %s\n", argv[1]);
return 1;
}
if (fstat(fd, &st) < 0) {
fprintf(stderr, "Could not fstat() file %s\n", argv[1]);
return 1;
}
int fsize = st.st_size;
if (strlen(argv[2]) + offset >= fsize) {
fprintf(stderr, "Aborting, combined offset + inserted text exceeds size of the file\n");
return 1;
}
fprintf(stderr, "File size = %d bytes\n", fsize);
// Map the entire region into memory
if ((ptr = mmap(NULL, fsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
fprintf(stderr, "error, failed to map\n");
return 1;
}
fprintf(stderr, "Mapped file %s to address 0x%x\n", argv[1], ptr);
strcpy(ptr + offset, argv[2]); // copy into the file
if (munmap(ptr, 256) < 0) {
fprintf(stderr, "Error, could not unmap region\n");
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment