Do I need to initialize the processor registers in the assembly code that is called from C?

I am reading a book by Paul Carter pcasm . It uses NASM, the C driver application that calls my build code, and a companion library that simplifies basic I / O operations in the assembly.

This is what my function that will be called from C looks like this:

segment .text global _asm_main _asm_main: enter 0,0 ; setup routine pusha mov bx, 0034h ; bx = 52 (stored in 16 bits) mov cl, bl ; cl = lower 8-bits of bx mov eax, ecx call print_int popa mov eax, 0 ; return back to C leave ret 

The print_int function prints the value store in eax as an integer. But this outputs garbage to stdout:

 4200244 

If I initialize the ecx register to 0 with mov ecx, 0000h before using it, I get the expected result:

 52 

Initialization is always required, and if so, is there a quick way to initialize all registers to 0 (or a user-defined initializer) from C or NASM?

I am using XP32, MinGW 4.4.0 and NASM 2.09.04.

+4
source share
2 answers

The print_int function prints the value eax . In the code, you assign the smallest of the four bytes eax (aka al ) through the following assignment chain: bl β†’ cl β†’ al . The remaining three bytes of eax remain uninitialized. Your code inherits any values ​​that were in these three bytes at the beginning of your routine. That is why you get trash.

You must initialize all the registers and memory cells that you use.

My x86 build is a little rusty, but I'm sure there is not a single instruction that sets all general registers to zero. If you were so addicted, you could write a macro that does this for you.

+4
source

Yes, it is necessary.

Nothing has been done for you in the meeting.
You must initialize each register as you want.

+2
source

Source: https://habr.com/ru/post/1340200/


All Articles