2017-04-21 76 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支持的所有架構都向下發展的堆棧。)