views:

271

answers:

3

Hi,

I encountered an Error during running of the following Assembly Code

#cpuid using C library Functions
.section .data
output:
 .asciz "The Processor Vendor ID is '%s'\n"
.section .bss
 .lcomm buffer, 12
.section .text
.globl main
main:
 movq $0, %rax
 cpuid
 movq $buffer, %rdi
 movq %rbx, (%rdi)
 movq %rdx, (%rdi)
 movq %rcx, (%rdi)
 pushq $buffer
 pushq $output
 call printf
 addq $8, %rsp
 pushq $0
 call exit

It encountered segmentation fault at the part of C library Calling:call printf It is running in x86_64 mode. Anything I missed out during compiling of x64 code with regards to the c library? Or is there something wrong with the code

Thanks

A: 

not familiar with assembly, so a shot in the dark: are both your strings null terminated?

cobbal
+3  A: 

Is the C runtime library's initialization being called? That has to run first in order for stdout to be set up. BTW, a stack trace would eliminate doubt as to the cause of the problem.

Also, prevent the %s conversion from overflowing the buffer with %.12s, or just put a NUL byte after buffer.

wallyk
A: 

You need to null-terminate the string you write into $buffer, rather than write on top of one word three times. Also, wallyk is right: are you sure that the CRT is being initialized?

Honestly, you are really much better off writing this program, which calls a C library function, in C. Write the CPUID code as inline assembly inside a __cdecl function, have it write its result to a string pointer, and then call that function from a C program.

void GetCPUID( char *toStr )
{
 // inline assembly left as exercise for the reader.. 
 // write ebx to *toStr, ecx to *toStr+4, edx to *toStr+8, and 0 to *toStr+12
}

void PrintCPUID()
{
   char cpuidstr[16];
   GetCPUID( cpuidstr );
   printf( "cpuid: %s\n", cpuidstr );

}
Crashworks