gpt4 book ai didi

c++ - Boost上下文实现

转载 作者:行者123 更新时间:2023-11-28 01:49:36 28 4
gpt4 key购买 nike

我正在阅读 boost fcontext 的实现。

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

第一个参数是上下文栈的顶部,来自boost文档的示例如下:

// 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));

当我阅读i386_elf 中make_context 的实现时,该实现总是减少sp,它会使上下文存储在sp 之前的内存中,这是malloc 内存不足的。是否可以覆盖不属于协程的内存?

/* 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)

最佳答案

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

make_fcontext 期望堆栈指针在平台所需的特定于体系结构的方向上有足够的空间。在 x86 上,这意味着指针之前必须有可用空间,而不是之后。通过直接传递从 malloc 接收到的指针,您违反了这个契约。

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

(作为旁注,我相信目前 Boost.Context 支持的所有架构都有向下增长的堆栈。)

关于c++ - Boost上下文实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43536637/

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