2017-04-21 90 views
0

我正在阅读boost fcontext的实现。Boost上下文实现

make_fcontext的函数原型是 typedef void* fcontext_t; fcontext_t BOOST_CONTEXT_CALLDECL make_fcontext(void * sp, std::size_t size, void (* fn)(intptr_t));

第一个参数是顶上下文堆栈,从升压文档的示例如下:

// context-function 
void f(intptr); 


// creates a new stack 
std::size_t size = 8192; 
void* sp(std::malloc(size)); 

// context fc uses f() as context function 
// fcontext_t is placed on top of context stack 
// a pointer to fcontext_t is returned 
fcontext_t fc(make_fcontext(sp,size,f)); 

当我在读的实施make_context在i386_elf中,实现总是减少sp,它会在sp之前将内存存储在内存中,这是malloc的内存不足。它可以覆盖不属于协程的memroy吗?

/* first arg of make_fcontext() == top of context-stack */ 
movl 0x4(%esp), %eax 

/*decrease the adress of sp here*/ 
/* reserve space for first argument of context-function 
    rax might already point to a 16byte border */ 
leal -0x8(%eax), %eax 

/* shift address in EAX to lower 16 byte boundary */ 
andl $-16, %eax 

/* reserve space for context-data on context-stack */ 
/* size for fc_mxcsr .. EIP + return-address for context-function */ 
/* on context-function entry: (ESP -0x4) % 8 == 0 */ 
leal -0x20(%eax), %eax 

/* third arg of make_fcontext() == address of context-function */ 
movl 0xc(%esp), %edx 
movl %edx, 0x18(%eax) 

/* save MMX control- and status-word */ 
stmxcsr (%eax) 
/* save x87 control-word */ 
fnstcw 0x4(%eax) 
+1

加速是一个C++类库,不C库。您可能需要相应地更新标签。 – Gerhardh

+0

谢谢你提醒。 – Jayce

回答

2

根据您的CPU架构,堆栈可能会增长向上(向高地址)或向下(向低地址,因为是在x86的情况下)。这通常在指令集中通过pushpop指令修改堆栈指针的方式进行硬编码。例如,x86 push指令从[er]?sp中减去。

make_fcontext预计堆栈指针在平台所需的架构特定方向上有足够的空间。在x86上,这意味着之前必须有可用空间,而不是之后。通过直接从malloc收到的指针,您违反了此合同。

这就是为什么存在stack_allocator抽象。它们返回指向堆栈右端的指针,具体取决于架构。

(作为一个方面说明,我相信目前Boost.Context支持的所有架构都向下发展的堆栈。)