Download presentation
Presentation is loading. Please wait.
Published byHadi Hartanto Modified over 5 years ago
1
The ‘asm’ construct An introduction to the GNU C/C++ compiler’s obscure syntax for doing inline assembly language
2
The ‘asm’ construct When using C/C++ for systems programs, we sometimes need to employ processor-specific instructions (e.g., to access CPU registers or the current stack area) Because our high-level languages strive for ‘portability’ across different hardware platforms, these languages don’t provide direct access to CPU registers or stack
3
gcc/g++ extensions The GNU compilers support an extension to the language which allows us to insert assembler code into our instruction-stream Operands in registers or global variables can directly appear in assembly language, like this (as can immediate operands): int count = 4; // global variable asm(“ movl count , %eax “); asm(“ imull $5, %eax, %ecx “);
4
Local variables Variables defined as local to a function are more awkward to reference by name with the ‘asm’ construct, because they reside on the stack and require the generation of offsets from the %ebp register-contents A special syntax is available for handling such situations in a manner that gcc/g++ can decipher
5
Template The general construct-format is as follows:
asm( instruction-template : output-operand : input-operand : clobber-list );
6
Example from ‘switcher.cpp’
void upon_signal( int signum ) { unsigned long *tos; asm(" movl %%ebp, %0 " : "=m" (tos) ); for (int i = 0; i < 22; i++) printf( "tos[%d]=%08X \n", i, tos[i] ); }
7
Example from ‘pgfaults.c’
void load_IDTR( void *img ) { asm(“ lidt %0 “ : : “m” (*img) ); } Here’s how we used this function: unsigned short newidtr[ 3 ]; load_IDTR( newidtr );
8
How to see your results You can ask the gcc compiler to stop after translating your C/C++ source-file into x86 assembly language: $ gcc –S myprog.cpp Then you can view the output ‘myprog.s’ by using the ‘cat’ command (or an editor) $ cat myprog.s | more
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.