我刚开始学习程序集,但我与.macro函数混淆了。我已经找到了一些例子,这些例子被用来在一个范围内添加一些数字,但是没有字符串。如果我想编写一个宏来重复3行文本,代码会是什么样的呢?
#编辑
我和我的导师谈过了,他提供了一个示例,我用它来编写下面的汇编代码:
.altmacro
.macro .printPlusPlus a
.print "\a"
.endm
.printPlusPlus <Hello, programmers!!>
.printPlusPlus <Welcome to the world of,>
.printPlusPlus <Linux assembly programing!!>发布于 2022-10-13 21:34:45
GAS有一个.rept宏,允许您重复一些代码n次。此外,.macro页面中的第一个示例基本上为您提供了另一种方法来生成一个.repeat times,another_macro宏,该宏可以将其称为第二个参数times倍。
我基本上从来没有真正使用过GAS,下面的代码只是一个PoC。
它展示了如何使用.rept,上面提到的.repeat宏和sys_write和sys_exit的两个宏。
总之,我不喜欢它(我肯定有更好的方法来编写宏),但是它是有注释的,可以作为一个答案。
#
# Constants
#
SYS_WRITE=1
SYS_EXIT=60
STDOUT=1
#
#This macro is similar to .rept but it takes the body to repeat as an argument
#This argument should be a name denoting a macro with no arguments
#
.macro repeat times, body
#Call the macro
\body
#Recurse if the next value of times is not 0
.if \times-1
repeat "(\times-1)",\body
.endif
.endm
#
#This macro print the string text given as its argument
#This work by switching to the data section, defining a local label 0 before the string and
# a local label 1 after the string (so we can get the string length as the difference), switching
# back to the text section and inserting a system call for SYS_WRITE
#
.macro print text
#Write the string in the data section and sorround it with two labels
.section .data
0:
.string "\text"
1:
#Go back to the text section and invoke the system call
.section .text
mov $SYS_WRITE, %eax
mov $STDOUT, %edi
lea 0b(%rip), %rsi
mov $(1b-0b-1), %edx #The -1 is because GAS always add a null-term
syscall
.endm
#
#This is a simple macro to call SYS_EXIT returning the optional argument ret
#
.macro exit ret=0
mov $SYS_EXIT, %eax
mov $\ret, %edi
syscall
.endm
#
#Since the repeat macro requires a 0-arity macro name, we need a wrapper macro for print
# with its string argument
#
.macro print_hello
print "Hello, programmers! Welcome to the world of, Linux assembly programming!\n"
.endm
#
# CODE
#
.global _start
.section .text
_start:
#Use our repeat macro
repeat 3,print_hello
#Use GAS .rept
.rept 3
print "Hello scripters! This is not like assembly at all!\n"
.endr
#Exit
exithttps://stackoverflow.com/questions/74060585
复制相似问题