【发布时间】:2019-05-18 17:57:44
【问题描述】:
我有一个函数switchContext(void*& from, void*& to)。它接收两个堆栈指针并应更改进程的上下文。因此,如果我有一个协程 A 并且它使用特定函数 resume(),协程 B 将继续工作。
目前我无法让我的代码正常工作。
我正在使用 Nasm 和 GCC 进行编译。
汇编程序:(switchContext(void*& from, void*& to)):
switchContext:
; epb = esp
mov ebp, esp
; save registers
push ebp
push ebx
push esi
push edi
; from <= returnadress
; eax <= returnadress
mov eax, [ebp+16]
mov edx, ebp
add edx, 20 ; make edx point to 'from'
; overwrite 'from' with returnadress
mov [edx], eax
; what to do now: returnadress <= to
; eax <= to
mov eax, [ebp+24]
mov edx, ebp
add edx, 16 ; make edx point to returnadress
; overwrite returnadress with 'to'
mov [edx], eax
pop edi ; RSA = esp + 12
pop esi ; RSA = esp + 8
pop ebx ; RSA = esp + 4
pop ebp ; RSA = esp + 0
; use new returnadress to jump to 'to'
ret
这是对应的 C++ 类:
extern "C" {
void switchContext(void*& from, void*& to);
}
class Coroutine {
public:
const char* name;
Coroutine(void* tos = 0)
{
setup(tos);
}
void resume(Coroutine* next)
{
switchContext(this->sp, next->sp);
}
virtual void body() = 0;
virtual void exit() = 0;
private:
static void startup(Coroutine* obj) {
obj->body();
obj->exit();
};
void setup(void* tos) {
if (tos == 0) {
unsigned temp_stack[1024];
this->sp = &temp_stack;
return;
}
this->sp = &tos;
return;
};
void* sp;
};
目前我的程序只是崩溃了。但它只能通过用 'to' 覆盖汇编器中的返回地址来实现。
我在这个过程中哪里出错了?
【问题讨论】:
-
为了完成这个,你能否提供一个小测试程序,使用这个类来设置几个协程。对于发现此问题的任何人来说,这至少可以使其成为minimal reproducible example。
-
我会为你不使用内联汇编并决定更直接的事情而鼓掌。
标签: c++ assembly x86 coroutine context-switch