views:

331

answers:

3

I came across this code and need to understand what it is doing. It just seems to be declaring two bytes and then doing nothing...

uint64_t x;
__asm__ __volatile__ (".byte 0x0f, 0x31" : "=A" (x));

Thanks!

+8  A: 

This is generating two bytes (0F 31) directly into the code stream. This is an RDTSC instruction, which reads the time-stamp counter into EDX:EAX, which will then be copied to the variable 'x' by the output constraint "=A"(x)

Chris Dodd
Ah ok!! And the "=A" (x) syntax (I am using gcc4.1) to use %eax and %edx together - will it work on x86_64 arch? I think so but I dont know much about assembly.
MK
Yes -- the 'A' constraint means a 64-bit value in the EDX:EAX register pair in both i386 and x86_64 gcc machine descriptions
Chris Dodd
+3  A: 

0F 31 is the x86 opcode for the RDTSC (read time stamp counter) instruction; it places the value read into the EDX and EAX registers.

The _ _ asm__ directive isn't just declaring two bytes, it's placing inline assembly into the C code. Presumably, the program has a way of using the value in those registers immediately afterwards.

http://en.wikipedia.org/wiki/Time_Stamp_Counter

Ian Clelland
+1  A: 

It's inserting an 0F 31 opcode, which according to this site is:

0F 31   P1+   f2   RDTSC EAX EDX IA32_T...        Read Time-Stamp Counter

Then it is storing the result in the x variable

AShelly