Professional Assembly Language 十二章系统调用例子for mac

本文介绍如何使用汇编语言实现简单的Hello, World!程序。文章详细展示了通过系统调用进行字符串输出的具体实现过程,并解释了相关寄存器的作用及栈的对齐方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编译

$ cc -arch i386 syscalltest.s
$ ./a.out
hello, world

代码

    .text
    .globl _main
    .p2align 4, 0x90
_main:
    pushl %ebp
    movl %esp, %ebp
    call L_0
L_0:
    popl %eax
    leal L_str-L_0(%eax), %eax
    pushl $nbyte    # nbyte
    pushl %eax      # buf
    pushl $1        # fildes stdout
    subl $4, %esp   # stack 16-bytes aligned
    movl $4, %eax   # ssize_t write(int fildes, const void *buf, size_t nbyte);
    int $0x80

    movl %ebp, %esp
    popl %ebp
    ret

    .cstring
L_str:
    .asciz "hello, world\n"
    .equ nbyte, . - L_str

说明

arguments passed on the stack, pushed right-to-left
stack 16-bytes aligned
syscall number in the eax register
call by interrupt 0x80
So what we have to do to print a “Hello world” is:

push the length of the string (int) to the stack
push a pointer to the string to the stack
push the stdout file descriptor (1) to the stack
align the stack by moving the stack pointer 4 more bytes (16 - 4 * 3)
set the eax register to the write syscall number (4)
interrupt 0x80

系统调用号所在头文件

/usr/include/sys/syscall.h

可以通过如下命令查找

$ cat /usr/include/sys/syscall.h | grep SYS_write
#define SYS_write          4
#define SYS_writev         121
#define SYS_write_nocancel 397
#define SYS_writev_nocancel 412

文件描述符通过如下命令查看

$ ls -l /dev/std*
lr-xr-xr-x  1 root  wheel  0  8  3 23:34 /dev/stderr -> fd/2
lr-xr-xr-x  1 root  wheel  0  8  3 23:34 /dev/stdin -> fd/0
lr-xr-xr-x  1 root  wheel  0  8  3 23:34 /dev/stdout -> fd/1

标准输出的文件描述符号为1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值