www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to get the body of a function/asm statement in hexadecimal

reply Ruby the Roobster <rubytheroobster yandex.com> writes:
I'm trying to do something like

```d
void main()
{
     auto d = &c;
     *d.writeln;
}

void c()
{
}
```

In an attempt to get the hexadecimal representation of the 
machine code of a function.  Of course, function pointers cannot 
be dereferenced.  What do?

Furthermore, I would like to be able to do the same for an `asm` 
statement.
Jan 29 2023
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 1/29/23 13:45, Ruby the Roobster wrote:

 Of course, function pointers cannot be dereferenced.
Since you want to see the bytes, just cast it to ubyte*. The following function dumps its own bytes: import std; void main() { enum end = 0xc3; for (auto p = cast(ubyte*)&_Dmain; true; ++p) { writefln!" %02x"(*p); if (*p == end) { break; } } } (It can be written more elegantly as a range expression.)
 Furthermore, I would like to be able to do the same for an `asm` 
statement. I don't know how to get the address of asm blocks. Ali
Jan 29 2023
prev sibling parent reply max haughton <maxhaton gmail.com> writes:
On Sunday, 29 January 2023 at 21:45:11 UTC, Ruby the Roobster 
wrote:
 I'm trying to do something like

 ```d
 void main()
 {
     auto d = &c;
     *d.writeln;
 }

 void c()
 {
 }
 ```

 In an attempt to get the hexadecimal representation of the 
 machine code of a function.  Of course, function pointers 
 cannot be dereferenced.  What do?

 Furthermore, I would like to be able to do the same for an 
 `asm` statement.
The function pointer can be casted to a pointer type. It is worth saying, however, that it is not trivial to find where the *end* of a function is. In X86 it's not even trivial to find the end of an instruction! If you'd just like the bytes for inspection, you could use a tool like objdump. For more complicated situations you will need to use a hack to tell you where the end of a function is.
Jan 29 2023
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 1/29/23 14:19, max haughton wrote:

 it is not trivial to find where the *end* of a
 function is
I suspected as much and did run ...
 objdump
... to fool myself into thinking that 0xc3 was <end>. Well, arguments e.g. pointer values can have 0xc3 bytes in them. So, yes, I am fooled! :) Ali
Jan 29 2023