gpt4 book ai didi

用 C 和汇编编写一个简单的线程

转载 作者:太空狗 更新时间:2023-10-29 16:56:03 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的用户级线程库,作为我的操作系统类(class)的练习。作为第一步,我试图运行一个程序并跳转到一个离开第一个程序的函数。到目前为止的代码是这样的:

初始程序:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>

#define STACK_SIZE (sizeof(void *) * 512)


void proc2() //This is the function that should run as the thread.
{
int i;
for(i=0;i<30;i++)
{
printf("Here I am!\n");
sleep(0.5);
}
exit(0);
}

void* malloc_stack() //used to malloc the stack for the new thread.
{
void *ptr = malloc(STACK_SIZE + 16);
if (!ptr) return NULL;
ptr = (void *)(((unsigned long)ptr & (-1 << 4)) + 0x10); //size align
return ptr;
}

int main()
{
int *bp, *sp;
sp = malloc_stack();
bp = (int*) ((unsigned long)sp + STACK_SIZE);
proc1(&proc2,sp,bp); //the actual code that runs the thread. Written in assembly
assert(0);
}

然后我编写了一个名为 proc1 的简单汇编代码,它接受三个参数、函数指针(用作指令指针)、堆栈指针和基指针,并用这些值替换当前寄存器。我写的代码是:

.globl  proc1
proc1:
movq %rdx, %rbp #store the new base pointer
movq %rsi,%rsp #store the new stack pointer
jmp %rdi #jump to the new instruction pointer.

但是当我运行这段代码时,我得到的是一个段错误。请帮我找出这里的错误。

当我使用以下命令在 GDB 下运行它时,它工作正常:

gcc -g test.c switch.s
gdb a.out
run

但是当它像 ./a.out 一样单独运行时,它不起作用!!!!请帮忙。

提前致谢。

最佳答案

尝试更改代码以直接在 C 源代码中包含汇编指令,如下所示:

void proc1(void (*fun)(), int *sp, int *bp){
register int *sptr asm ("%rsi") = sp;
register int *bptr asm ("%rdx") = bp;
register void (*fptr)() asm ("%rdi") = fun;

asm (
"mov %rdx, %ebp\n"
"mov %rsi, %esp\n"
"jmp *%rdi\n"
);
}

上面的代码确保 proc1 的参数在正确的寄存器中(尽管你的代码在 abi 方面似乎是正确的)。请注意 jmp 参数前面的 *,这是我第一次尝试您的代码时警告我的 gnu 版本。

有了上面的函数,以及用-g编译的代码,你应该能够正确地调试它(在proc1上使用breakpoint指令)和 info registers 检查 cpu 的内容)。


问题实际上是在 %rsp 指针上,它必须始终等于或大于 %rbp(堆栈向下增长).简单地将 bp 而不是 sp 传递给 main 中的 proc1 应该可以解决问题:

 proc1(&proc2, bp, bp);

2个小备注:

  • 不要忘记在 asm 版本的 C 代码中给出 proc1 原型(prototype):

    extern void proc1(void (*)(), int *, int *);
  • sleep libc 函数只接受unsigned long,不接受float

    sleep(1);

关于用 C 和汇编编写一个简单的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16128759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com