Advertisement
homer512

Test mapping smaps flags

Oct 12th, 2024 (edited)
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #include <sys/mman.h>
  4.  
  5.  
  6. int main(void)
  7. {
  8.   void* private_noaccess, *private_read, *private_rw, *private_file;
  9.   FILE* file;
  10.   int i, buf;
  11.   /*
  12.    * Create file to test MAP_PRIVATE of a file
  13.    */
  14.   if(! (file = fopen("/tmp/maptest", "w+b")))
  15.     return 1;
  16.   for(i = 0; i < 4096 / sizeof(int); ++i)
  17.     fwrite(&i, sizeof(i), 1, file);
  18.   fflush(file);
  19.   /*
  20.    * Will appear as rw-p mapping in smaps with Rss = 0 kiB,
  21.    * meaning no anonymous memory is actually consumed until written to
  22.    */
  23.   private_file = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE,
  24.                      fileno(file), 0);
  25.   fclose(file);
  26.   /*
  27.    * Will appear as rw-p with Rss = 0 kiB
  28.    */
  29.   private_rw = mmap(NULL, 4096, PROT_READ|PROT_WRITE,
  30.                     MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  31.   /*
  32.    * Will appear as r--p in smaps
  33.    */
  34.   private_read = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  35.   /*
  36.    * Will appear as ---p in smaps
  37.    */
  38.   private_noaccess = mmap(NULL, 4096, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS,
  39.                           -1, 0);
  40.   /*
  41.    * Print mapping locations so that we can compare them with smaps
  42.    */
  43.   printf("file=%p rw=%p r=%p noaccess=%p\n",
  44.          private_file, private_rw, private_read, private_noaccess);
  45.   /*
  46.    * Print smaps content
  47.    */
  48.   if(! (file = fopen("/proc/self/smaps", "r")))
  49.     return 2;
  50.   while((buf = getc(file)) != EOF)
  51.     putchar(buf);
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement