C / C ++ maps binary data to structure members

Suppose I have the following text file:

Listing 1:

Endianess=little AddressModel=32 typedef struct{ int x; int y; float f; double d; } A; instance1:0x0000000100000002000048C19A99999999993C40 instance2:0x00100257000000090000000FBA99359976992397 

Where instance1 corresponds to an instance of struct A, for example:

Listing 2:

 A->x = 0x00000001 = 1 A->y = 0x00000002 = 2 A->f = 0x000048C1 = -12.5 A->d = 0x9A99999999993C40 = 28.6 

Task:

Write an application that takes as a text file, an arbitrary C data structure and an arbitrary memory dump, and prints in an easy-to-read format, restoring an instance of this structure (for example, see Listing 2).

Questions:

  • What is the best way to do this?
  • Instead of reinventing the wheel, are there (are) any open source solutions that might cause this problem?

What to consider:

Decision will be

  • consider the length of the data type.
  • handle different models of addresses and judgments.
  • displays both hex and native screen for this particular data type.
  • take the C structures that were NOT associated with the program you are writing.

Bonus question:

Handle the case with inline structures:

 typedef struct{ int q; int p; A a; //embedded struct of type A defined in listing 1 } B; 

Thanks in advance to everyone!

+4
source share
1 answer

You cannot use reflection in C or C ++ so that it does not. This means that you will need to write a parser than read the definitions of the C-structure. This is actually not difficult.

You can do it yourself if you want: C tokenization and parsing is not difficult. Or you can use tools like lex and yacc. Or you can use a C ++ library like Boost Spirit.

Once you have a parser, you can create a data reader in C. You do not want to reproduce the structure in your C code. You just want to be able to read it correctly.

I would write an array of types and data names during the analysis step. During binary reading, a step going through the array and reading, however, a lot of bytes to read, then create an output string. Repeat until you finish the data types in the array.

+1
source

Source: https://habr.com/ru/post/1339428/


All Articles