首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(x86-64) GNU程序集宏

(x86-64) GNU程序集宏
EN

Stack Overflow用户
提问于 2022-10-13 19:02:22
回答 1查看 71关注 0票数 0

我刚开始学习程序集,但我与.macro函数混淆了。我已经找到了一些例子,这些例子被用来在一个范围内添加一些数字,但是没有字符串。如果我想编写一个宏来重复3行文本,代码会是什么样的呢?

#编辑

我和我的导师谈过了,他提供了一个示例,我用它来编写下面的汇编代码:

代码语言:javascript
复制
.altmacro

.macro .printPlusPlus a
.print "\a"
.endm


.printPlusPlus <Hello, programmers!!>
.printPlusPlus <Welcome to the world of,>
.printPlusPlus <Linux assembly programing!!>
EN

回答 1

Stack Overflow用户

发布于 2022-10-13 21:34:45

GAS有一个.rept宏,允许您重复一些代码n次。此外,.macro页面中的第一个示例基本上为您提供了另一种方法来生成一个.repeat times,another_macro宏,该宏可以将其称为第二个参数times倍。

我基本上从来没有真正使用过GAS,下面的代码只是一个PoC。

它展示了如何使用.rept,上面提到的.repeat宏和sys_writesys_exit的两个宏。

总之,我不喜欢它(我肯定有更好的方法来编写宏),但是它是有注释的,可以作为一个答案。

代码语言:javascript
复制
#
# 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
    exit
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74060585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档