1

So, I have an unsigned int variable with a decimal value address stored on it, let's say unsigned int var = 1232342, what I am trying to do is, without knowing the type of the variable but knowing the size of it and the address where it is stored, get the values as a byte array. For example, let's say I have an int var = 20 with its address and bytesize. I want to be able to go to that address and return a byte array, in this case [00001100] and the same for char variables and data members of a struct.

A little bit of pseudocode would be something like:

for var.address until var.address = var.address + bytesize
    do 
       byte_array = *var.address
       var.address++ 

I am encountering some problems though, I am kind of new to C so I don't know how to treat an unsigned int as an address/pointer. Second, I don't know how to get the actual bytes out of the address, whenever I dereference the address what I get is the actual value of it, but that is if I know the type for the variable.

A little bit of background: I am working on a tool called Pin which gives me the option to hook into a running process, then I am using the DWARF and ELF info. So I do have access to the virtual memory space I am trying to access

Matt
  • 22,721
  • 17
  • 71
  • 112
attis
  • 171
  • 1
  • 4
  • 16

2 Answers2

1

"a" is the address from where you want to get 4 bytes. "bytes" is where you want to store your results. I assigned the address of "i" to "a", then read 4 bytes from that address.

#include <stdio.h>
int main(int argc, char *argv[]) {
    unsigned char bytes[4];
    int i = 65535, j;
    unsigned long a = (unsigned long) &i;

    for (j = 0; j < 4; j++) {
        bytes[j] = *((unsigned char*) a + j);
    }

    for (j = 0; j < 4; j++) {
        printf("bytes[%d]: %d\n", j, bytes[j]);
    }
}
buga
  • 11
  • 2
1

Take a look at the hexdump function by epatel here

Off-the-Shelf C++ Hex Dump Code

In spite of the title it's really C code. I'll copy it here for your convenience

#include <ctype.h>
#include <stdio.h>

void hexdump(void *ptr, int buflen) {
  unsigned char *buf = (unsigned char*)ptr;
  int i, j;
  for (i=0; i<buflen; i+=16) {
    printf("%06x: ", i);
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%02x ", buf[i+j]);
      else
        printf("   ");
    printf(" ");
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.');
    printf("\n");
  }
}
Community
  • 1
  • 1
amdn
  • 11,314
  • 33
  • 45