首页 > 解决方案 > 在汇编代码中调用 pthread_create 时应该为寄存器设置什么值?

问题描述

出于学习目的,我正在尝试创建一个玩具汇编程序,该程序在单独的线程中运行一个函数。我的机器采用 x86-64 架构并运行 Ubuntu 操作系统。我pthread为此目的使用该库:

extern pthread_create
extern pthread_join

section .data
    ; a separate thread will print the "Hello" message
    text: db "Hello", 10
    text_len: equ $-text
    thread_id: dq 0

section .text
global main
main:
    mov eax, 0
    mov ecx, 0
    mov edx, thread ; the function address to be executed in a thread
    
    ; With the "mov esi, 0" instruction, the call to pthread_create
    ; throws a segfault. Without this instruction, the call to
    ; pthread_create returns, but produces no observable effect.
    mov esi, 0

    mov rdi, thread_id
    call pthread_create

    mov eax, 0
    mov rsi, 0
    mov rdi, [thread_id]
    ; this call should block until the thread terminates, shouldn't it?
    call pthread_join
    ret

thread:
    ; printing "Hello" to the screen
    mov eax, 4
    mov ebx, 1
    mov ecx, text
    mov edx, text_len
    int 80h
    ret

a.out我使用以下命令编译可执行文件:

nasm -f elf64 code.s
gcc -no-pie code.o -lpthread

可执行文件无法正常运行,代码中指出了错误。我怀疑失败的原因是在调用pthread_create. 如何正确设置参数?

更新:

我将pthread_create论点更改为

mov eax, 0
mov ecx, 0
mov edx, thread_0
mov rdi, thread0_id

pthread_join论据

mov eax, 0
mov ecx, 0
mov rdi, thread0_id

现在代码抛出一个bus error. 难道是pthread_t没有权限打印消息?

标签: linuxassemblyx86pthreadsx86-64

解决方案


推荐阅读