Re: Understanding Linux addr space, malloc, and heap

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Clearly, it was a mistake to post that code. I had no idea so many people would point out the bleeding obvious.

Here is a more elaborate version--that does the same thing, but more lines of code. In it malloc'd memory is mprotect'd. The program generates a SIGSEGV, a page fault.

----------------
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>

#include <limits.h>    /* for PAGESIZE */
#ifndef PAGESIZE
#define PAGESIZE 4096
#endif

int
main(void)
{
  char *p;
  char c;

  /* Allocate a buffer; it will have the default
     protection of PROT_READ|PROT_WRITE. */
  p = malloc(1024+PAGESIZE-1);
  if (!p) {
    perror("Couldn’t malloc(1024)");
    exit(errno);
  }

  /* Align to a multiple of PAGESIZE, assumed to be a power of two */
  p = (char *)(((int) p + PAGESIZE-1) & ~(PAGESIZE-1));

  c = p[666];         /* Read; ok */
  p[666] = 42;        /* Write; ok */

  /* Mark the buffer read-only. */
  if (mprotect(p, 1024, PROT_READ)) {
    perror("Couldn’t mprotect");
    exit(errno);
  }

  c = p[666];         /* Read; ok */
  p[666] = 42;        /* Write; program dies on SIGSEGV */

  exit(0);
}


Arjan van de Ven wrote:
But I can't mprotect the 66th page I malloc.  And mprotect fails SILENTLY!


I'm not convinced it does that.. not until the bugs are out of the
code.... since right now it mprotects the wrong stuff, which sometimes
overlaps with what you malloced, sometimes not.


-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/

[Index of Archives]     [Kernel Newbies]     [Netfilter]     [Bugtraq]     [Photo]     [Stuff]     [Gimp]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Video 4 Linux]     [Linux for the blind]     [Linux Resources]
  Powered by Linux