简体   繁体   English

C - 获取存储在进程虚拟内存中某个地址的值

[英]C - get value stored at an address in the virtual memory of a process

I am given an address (a hexadecimal number) that represents a memory address in the virtual memory of a process.我得到一个地址(一个十六进制数),它代表进程虚拟内存中的内存地址。

I have verified that the address exists in the heap.我已验证该地址存在于堆中。 But now I want to access the value of the byte located at this address.但现在我想访问位于该地址的字节的值。

This is what I have so far:这是我到目前为止:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/*
  - Takes a single arg: required_address
  - if the address is in virtual memory:
  -   print to stdout the value of the single byte of memory located at address
  -   return with exit code 1
  - else:
  -   print nothing
  -   return with exit code 0

  - 00405000-00426000 [heap]

 */

int main(int argc, char const *argv[]) {
    unsigned long ret_adr = strtoul(argv[1], NULL, 16);
    int pid = getpid();

    char find[10] = "heap";
    char high[32], low[32];

    // Read maps file
    char maps_file_addr[20];
    sprintf(maps_file_addr, "/proc/%d/maps", pid);
    puts(maps_file_addr);
    FILE* maps_file = fopen(maps_file_addr, "r");
    char line[256];

    if (maps_file == NULL){
       printf("Error! opening maps file\n");

       // Program exits if the file pointer returns NULL.
       exit(1);
    }

    // Get range of heap
    while (fgets(line, sizeof(line), maps_file) != NULL) {
        if(strstr(line, find)){
            char * token = strtok(line, " ");
            strcpy(low, strtok(token, "-"));
            strcpy(high, strtok(NULL, "-"));
        }
    }

    unsigned long low_hex = strtoul(low, NULL, 16);
    unsigned long high_hex = strtoul(high, NULL, 16);

    printf("Address: %lu\n", ret_adr);
    printf("Low Hex: %lu\n", low_hex);
    printf("High Hex: %lu\n", high_hex);

    // Check if address is in heap range
    if (low_hex < ret_adr < high_hex) {
        char *p = (char *)ret_adr;
        printf("%c\n", *p);
    } else {
        exit(1);
    }

    fclose(maps_file);
    return 0;
}

In this line:在这一行:

if (low_hex < ret_adr < high_hex) {
        char *p = (char *)ret_adr;
        printf("%c\n", *p);
}

I tried to access the value that is stored in the virtual memory a the ret_adr location.我试图访问存储在ret_adr位置的虚拟内存中的ret_adr But nothing is being printed out.但是没有打印出来。 How do I access the value stored at that location?如何访问存储在该位置的值?

Terminal for reference:参考终端:

[task1]$ setarch x86_64 -R ./task1 400000
/proc/24603/maps
Address: 4194304
Low Hex: 4214784
High Hex: 4349952


if (low_hex < ret_adr < high_hex) {

这一行是不正确的,它应该是:

if (low_hex <= ret_adr && ret_addr < high_hex) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM