简体   繁体   English

我是否必须在从 C 调用的汇编代码中初始化 CPU 寄存器?

[英]Do I have to initialize the CPU registers in assembly code that is called from C?

I'm reading Paul Carter's pcasm book.我正在阅读 Paul Carter 的pcasm书。 It uses NASM, a C driver app that calls my assembly code, and a companion library that makes it easy to do basic I/O in assembly.它使用 NASM,一个调用我的汇编代码的 C 驱动程序应用程序,以及一个可以轻松在汇编中执行基本 I/O 的配套库。

This is what my function that will be called from C looks like:这是我将从 C 调用的函数的样子:

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 at eax as an integer. print_int函数将eax的值存储打印为整数。 But this prints out garbage to stdout:但这会将垃圾打印到标准输出:

4200244

If I initialize the ecx register to 0 with mov ecx, 0000h before using it, I will get the expected output:如果我在使用之前用mov ecx, 0000hecx寄存器初始化为 0,我将得到预期的输出:

52

Is initialization always required, and if so, is there a quick way of initializing all the registers to 0 (or a user-defined initializer), from either C or NASM?是否总是需要初始化,如果需要,是否有一种从 C 或 NASM 将所有寄存器初始化为 0(或用户定义的初始化程序)的快速方法?

I'm using XP32, MinGW 4.4.0, and NASM 2.09.04.我使用的是 XP32、MinGW 4.4.0 和 NASM 2.09.04。

The function print_int prints out the value of eax .函数print_int打印出eax的值。 In your code you only assign to the lowest of the four bytes of eax (aka al ) via the following chain of assignments: bl -> cl -> al .在您的代码中,您只能通过以下分配链分配给eax (又名al )的四个字节中最低的一个: bl -> cl -> al The remaining three bytes of eax are left uninitialized. eax的其余三个字节未初始化。 Your code inherits whatever values happened to be in those three bytes at the start of your routine.您的代码继承了例程开始时这三个字节中发生的任何值。 This is why you get garbage.这就是你得到垃圾的原因。

You have to initialize all the registers and memory locations that you use.您必须初始化您使用的所有寄存器和内存位置。

My x86 assembly is a bit rusty, but I am pretty sure there isn't a single instruction that would set all general-purpose registers to zero.我的 x86 程序集有点生疏,但我很确定没有一条指令可以将所有通用寄存器设置为零。 If you were so inclined, you could probably write a macro that would do this for you.如果您愿意,您可能会编写一个宏来为您执行此操作。

Yes, it's required.是的,这是必需的。

Nothing is done for you, in assembly.在组装中,没有什么是为你做的。
You have to initialize every register the way you want it.你必须按照你想要的方式初始化每个寄存器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM