Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this x86 inline assembly doing?

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!

like image 904
MK. Avatar asked Aug 13 '09 17:08

MK.


People also ask

What is inline assembly explain with an example?

In computer programming, an inline assembler is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C or Ada.

What is asm volatile?

asm volatile ("" ::: "memory") AFAIK is the same as the previous. The volatile keyword tells the compiler that it's not allowed to move this assembly block. For example, it may be hoisted out of a loop if the compiler decides that the input values are the same in every invocation.

Is inline assembly part of C standard?

Is inline assembly part of the C standard (ANSII or ISO) or not? There is no such thing as ANSII. ANSI is the American National Standards Institute, which issued the original C standard in 1989. All later versions of the standard (1990, 1999, 2011) have been issued by ISO.


2 Answers

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)

like image 170
Chris Dodd Avatar answered Oct 02 '22 09:10

Chris Dodd


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

like image 40
Ian Clelland Avatar answered Oct 02 '22 11:10

Ian Clelland