Skip to content

Instantly share code, notes, and snippets.

@Gydo194
Created January 12, 2020 12:07
Show Gist options
  • Save Gydo194/a0cec0ba27109a3f5d6317356fed8473 to your computer and use it in GitHub Desktop.
Save Gydo194/a0cec0ba27109a3f5d6317356fed8473 to your computer and use it in GitHub Desktop.
Read binary data from a file into a C struct using mmap(2)
/*
* Load raw binary data from a mmap(2)'ed file
* Mind your endianness and alignment.
*
* Sun, 12 Jan 2020 12:00:00 +0000
* By Gydo194
*
* This code is in the public domain, you may use and redistribute this
* file as you wish, however I shall not be responsible for any damage caused
* by you doing so.
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/mman.h>
#define COLOR_RED "\e[31m"
#define COLOR_GREEN "\e[32m"
#define COLOR_RESET "\e[0m"
typedef unsigned char u8_t;
typedef unsigned short u16_t;
struct mtef
{
u8_t value1;
u8_t value2;
};
/* file as unsigned char for now */
unsigned char *file;
int size, status, fd;
struct stat s;
void mmap_file(const char * const filename)
{
/* open file */
fd = open (filename, O_RDONLY);
/* Get the size of the file. */
status = fstat (fd, & s);
size = s.st_size;
file = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fd, 0);
}
void interpret_memory_region(const void * const address)
{
const struct mtef * mtef_region;
u8_t parsed_value1, parsed_value2;
/* zero just to be sure */
parsed_value1 = 0x00;
parsed_value2 = 0x00;
/* cast raw memory region to struct */
mtef_region = (const struct mtef *) address;
printf(COLOR_GREEN "Loaded address '0x%X' as MTEF struct" COLOR_RESET "\n", mtef_region);
/* copy values from mapped address onto the stack */
puts("Loading values...");
parsed_value1 = mtef_region->value1;
parsed_value2 = mtef_region->value2;
puts(COLOR_GREEN "Success!" COLOR_RESET);
/* if all goes well.. */
printf(COLOR_GREEN "VALUE 1: '%d'\nVALUE 2: '%d'" COLOR_RESET "\n", parsed_value1, parsed_value2);
}
int main(int argc, char const *argv[])
{
if(argc < 2)
{
/* i do want a file path from you */
printf(COLOR_RED "Usage: %s <file>" COLOR_RESET "\n", argv[0]);
return 1;
}
printf("Loading file '%s' ...\n", argv[1]);
mmap_file(argv[1]);
puts(COLOR_GREEN "Success!" COLOR_RESET);
interpret_memory_region(file);
return 0;
}
@wonka007
Copy link

wonka007 commented Oct 6, 2020

You are not unmapping the memory and closing the file. That is a big uff

@Gydo194
Copy link
Author

Gydo194 commented Oct 7, 2020

You are not unmapping the memory and closing the file. That is a big uff

Left as an excersise to the reader.

This was just a proof of concept to show how this works to my friend. Error handling and proper cleanup has been neglected a bit. Maybe i should have stated that sonewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment