Beginning and end of segments of the C / C ++ process

I need to get the start and end addresses of the following process segments: code, data, stack, environment. I understand how it is in memory, but I don’t know how to get it using api calls or something else. I found how to start some segments with this code

#include <stdio.h>

int temp_data = 100;
static int temp_bss;

void print_addr ( void )
{
        int local_var = 100;
        int *code_segment_address = ( int* ) &print_addr;
        int *data_segment_address = &temp_data;
        int *bss_address = &temp_bss;
        int *stack_segment_address = &local_var;

        printf ( "\nAddress of various segments:" );
        printf ( "\n\tCode Segment : %p" , code_segment_address );
        printf ( "\n\tData Segment : %p" , data_segment_address );
        printf ( "\n\tBSS : %p" , bss_address );
        printf ( "\n\tStack Segment : %p\n" , stack_segment_address );

}

int main ( )
{
        print_addr ();
        return 0;
}

But I do not know how to find the end of each segment. I mean only that the end of one segment is the beginning of another segment. Please explain how I can do this using the C and linux API.

+4
source share
4 answers

, ( , , libc.so). , , , . , .

malloc mmap (2) munmap , sbrk

proc (5). , /proc/self/maps ( /proc/1234/maps pid 1234) /proc/self/smaps; cat /proc/self/maps fopen (3) "/proc/self/maps" ( fgets readline , , fclose). , dladdr (3) .

ELF , . of /proc/self/exe. . readelf (1) objdump (1) execve (2) (5) ld.so(8) libelf, Levine Linkers and Loaders book Drepper: .

. ( ). , Linux ASLR, , , .

strace (1) . syscalls (2). Linux

+5

. man 3 end:

#include <stdio.h>
extern etext;
extern edata;
extern end;
int
main(int ac, char **av, char **env)
{
        printf("main %p\n", main);
        printf("etext %p\n", &etext);
        printf("edata %p\n", &edata);
        printf("end %p\n", &end);
        return 0;
}

, .

enivonrment main(), , , &argv[0]. NULL (32 64 ) . NULL .

- " " (ASLR) . "" , ( alloca()), . , "" .

ELF. . man getauxval C . ELF, .

+3

, , Linux . , mmap() brk(), .

, brk(), , etext, edata end, . ( " " ) . , , , , , - brk.

. .

+2

Windows Linux , , 0 2 ^ 32-1 ( 32- ) 2 ^ 64-1 ( 64- ). , . , , - .

, ELF, Linux, . , , ++.

Windows GetModuleHandle (0). , COFF, , , . ; ( DLL) , , VirtualAlloc() - (HeapAlloc(), , ).

If you want to print only good stack traces or something else, then there are many ready-made libraries that can do this for you. If you want to do checksums, then things get a lot more complicated; better to use code signatures or ready-made libraries. The real answer to your question depends on what your real problem really is ...

+1
source

All Articles