Search code examples
cgdbcoredump

How to convert hex data to a data structure in gdb


I usually analyzing some hex dump from crash log, this hex dump belong to some very complicate data structure.

So I wander if gdb has some convenient command to translate the hexdump to data structure.

For example, I got some the hexdump 0xAAABBCCDDEEFF, is there a way to convert it back to the data structure?

for example:

p ((struct very_complcate_structure)(0xAABBCCDDEEFF)).u.flag.a

Solution

  • I got some the hexdump 0xAAABBCCDDEEFF

    The trick is to get these values into memory of a running process. It may be useful to write a tiny helper program for this.

    For example, suppose that you have a hex dump of a packet, and the remote server printed that packet out, then crashed. (The usual way to debug this is to make remote server dump core, and then debug that core -- this will allow you to debug many more problems than what is possible to debug using your "logging" approach, but I digress).

    So we write a helper program like this (using this answer):

    #include <string.h>
    #include <sstream>
    #include <iostream>
    
    #include "packet.h"   // "complicated" packet structure defined here.
    
    int main(int argc, char *argv[]) {
      struct packet pkt;
      static const int num_ints = ((sizeof(pkt) + sizeof(int) - 1) & ~(sizeof(int) - 1)) / sizeof(int);
    
      for (int j = 1; j < argc; j++) {
        memset(&pkt, 0, sizeof(pkt));  // start in clean state
    
        // chop input string into 8-char chunks
        std::string s = argv[j];
        for (int k = 0; k < num_ints && k < (s.size() / 8) + 1 ; k++) {
          std::stringstream ss;
          ss << std::hex << s.substr(8 * k, 8);
    
          unsigned int x;
          ss >> x;
          ((unsigned int *)&pkt)[k] = x;
        }
        std::cout << std::endl;  // break here.
      }
    }
    

    Now compile this program with g++ -g helper.cc -o helper, run it with

    gdb -q ./helper AAABBCCDDEEFF....
    

    Set breakpoint on line 24 (the "break here" line), and use print pkt to examine the decoded packet.