mmap

mmap: A new system call, which lets you map a file into the process address space. This allows you to manipulate a file as an array of bytes in normal memory, saving you the need of the open/read/write/close cycle.

For example, the following code maps an ELF file into memory, and computes a pointer to the Elf32_Ehdr:

   int fd;
   void *map_start; /* will point to the start of the memory mapped file */
   struct stat fd_stat; /* this is needed to  the size of the file */
   Elf32_Ehdr *header; /* this will point to the header structure */
   int num_of_section_headers;

   if( (fd = open(argv[1], O_RDWR)) < 0 ) {
      perror("error in open");
      exit(-1);
   }

   if( fstat(fd, &fd_stat) != 0 ) {
      perror("stat failed");
      exit(-1);
   }

   if ( (map_start = mmap(0, fd_stat.st_size, PROT_READ | PROT_WRITE , MAP_SHARED, fd, 0)) == MAP_FAILED ) {
      perror("mmap failed");
      exit(-4);
   }

   /* now, the file is mapped starting at map_start.
    * all we need to do is tell *header to point at the same address:
    */

   header = (Elf32_Ehdr *) map_start;
   /* now we can do whatever we want with header!!!!
    * for example, the number of section header can be obtained like this:
    */
   num_of_section_headers = header->e_shnum;

   /* now, we unmap the file */
   munmap(map_start, fd_stat.st_size);