簡體   English   中英

靜態計算地址的對齊頁面

[英]Calculate align page of an address statically

我需要靜態計算包含elf文本段的第一頁的地址,以便使用mprotect()並使文本段可寫。

Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al .. [14] .text PROGBITS 08048380 000380 0002e0 00 AX 0 0 128

有任何想法嗎?

正常編譯且不會崩潰的程序如何處理。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/mman.h>

extern char __executable_start;
extern char __etext;

int
main (int argc, char **argv)
{
  int pagesize = sysconf (_SC_PAGE_SIZE);
  char *start =
    (char *) (((uintptr_t) & __executable_start) & ~(pagesize - 1));
  char *end =
    (char *) (((uintptr_t) & __etext + pagesize - 1) & ~(pagesize - 1));
  mprotect (start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
  printf ("Hello world\n");
  void *m = main;
  *((char *) m) = 0;
  exit (0);
}

我使用了__executable_start__etext ,但是您可能會更好地看看是否可以使用它們,至少在手冊頁中有記錄:

名稱

  `etext`, `edata`, `end` - end of program segments 

概要

  extern etext; extern edata; extern end; 

描述

  The addresses of these symbols indicate the end of various program segments: `etext` This is the first address past the end of the text segment (the program code). `edata` This is the first address past the end of the initialized data segment. `end` This is the first address past the end of the uninitialized data segment (also known as the BSS segment). 

符合

  Although these symbols have long been provided on most UNIX systems, they are not standardized; use with caution. 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM