Macro substituting a constant number in GAS

烈酒焚心 提交于 2020-12-05 04:58:25

问题


What't wrong with that macro on X86 GNU Assembly? It says the symbol S is undefined during linking.

.macro S size=40
\size
.endm

I'm using it like

mov %eax, S

回答1:


Macros are used to create templates for code you frequently use, not to input a constant number. As such, I do not believe the assembler does macro expansion within an expression. Since you simply want a number, you could use .set to define a constant.

.set S, 40
mov %eax, S

Also, in case you usually use intel syntax, make sure you realize what this code is doing: It currently stores the value of eax in memory at the address 0x28. If you want to put the number 40 in eax, you need to reverse the operands and use a dollar sign in front of S.

mov $S, %eax



回答2:


You can also directly assign symbols with the equals sign =:

S = 40

which the GNU as manual says is equivalent to using .set https://sourceware.org/binutils/docs-2.19/as/Setting-Symbols.html#Setting-Symbols

A symbol can be given an arbitrary value by writing a symbol, followed by an equals sign =', followed by an expression (see Expressions). This is equivalent to using the .set directive. See .set. In the same way, using a double equals sign='`=' here represents an equivalent of the .eqv directive. See .eqv.

.equ is yet another synonym...

 .equ S, 40

One typical use case of such constants, is to calculate the length of static strings, e.g. the Linux x86_64 hello world can be written as:

hello_world.S

    .data
hello_world:
    .ascii "hello world\n"
    hello_world_len = . - hello_world
.text
.global _start
_start:
    /* write */
    mov $1, %rax
    mov $1, %rdi
    mov $hello_world, %rsi
    mov $hello_world_len, %rdx
    syscall

    /* exit */
    mov $60, %rax
    mov $0, %rdi
    syscall

which you can compile and run wth:

as -o hello_world.o hello_world.S
ld -o hello_world.out hello_world.o
./hello_world.out

GitHub upstream.

%rdx will then contain the length of the string to be written.

The $ is required just like for any regular address label, otherwise you would be trying to access that memory address instead of moving an immediate.



来源:https://stackoverflow.com/questions/5899399/macro-substituting-a-constant-number-in-gas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!