ossrs / state-threads

Lightweight thread library for C/C++ coroutine (similar to goroutine), for high performance network servers.

Home Page:http://sourceforge.net/projects/state-threads

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support OSX, the ST thread and stack model

winlinvip opened this issue · comments

Analysis ST thread model, for mac __amd64__ or __x86_64__.

The asm code:

    __st_md_cxt_save:

        /* Save SP */
        leaq 8(%rsp), %rdx              /* Save *(int64_t*)(rsp+8) to rdx, https://my.oschina.net/guonaihong/blog/508907 */
        movq %rdx, (JB_RSP*8)(%rdi)     /* Save rdx(rsp) to env[6], *(int64_t*)(rdi+6)=rdx */

which save RSP, the stack address to rdx, then save rdx to jmpbuf[JB_RSP].

The asm code:

    __st_md_cxt_save:
        /* Save PC we are returning to */
        movq (%rsp), %rax               /* Save PC(parent function address) %(rsp) to rax */
        movq %rax, (JB_PC*8)(%rdi)      /* Save rax(PC) to env[7], *(int64_t*)(rdi+7)=rax */

which save the content of RSP, that is the previous function address(PC), to rax, then save rax to jmpbuf[JB_PC].

寄存器布局,osx和linux是一样的,参考:https://en.wikipedia.org/wiki/X86_calling_conventions

image

  • 函数参数:RDI, RSI, RDX, RCX, R8, R9
  • 返回值:RAX

由于save和restore最多只有两个参数:

        extern int _st_md_cxt_save(jmp_buf env);
        extern void _st_md_cxt_restore(jmp_buf env, int val);

因此,我们可以将其他的参数寄存器当作临时变量用,比如存储RSP和PC的内容:

  • rdx,在save时保存RSP的值到jmpbuf。现在改成了寄存器r8。
  • rax,在save时保存PC的值到jmpbuf。虽然rax是返回值,但是临时用下也可以。现在改成了寄存器r9。
    __st_md_cxt_save:
        /* Save SP */
        leaq 8(%rsp), %r8              /* Save *(int64_t*)(rsp+8) to r8, https://github.com/ossrs/state-threads/issues/11#issuecomment-888709759 */
        movq %r8, (JB_RSP*8)(%rdi)     /* Save r8(rsp) to env[6], *(int64_t*)(rdi+6)=r8 */
        /* Save PC we are returning to */
        movq (%rsp), %r9               /* Save PC(parent function address) %(rsp) to r9 */
        movq %r9, (JB_PC*8)(%rdi)      /* Save r9(PC) to env[7], *(int64_t*)(rdi+7)=r9 */
  • rdx,在restore时从jmpbuf恢复PC寄存器。现在改成了寄存器r8。
    __st_md_cxt_restore:
        /* Restore PC and RSP */
        movq (JB_PC*8)(%rdi), %r8      /* Load r8(PC) from env[7] */
        movq (JB_RSP*8)(%rdi), %rsp     /* Load rsp from env[6] */
        /* Jump to saved PC */
        jmpq *%r8                      /* Jump to r8(PC) */

Note: PC寄存器就是函数执行的地址。RSP是堆栈地址。