Hacker News new | ask | show | jobs
by spc476 2956 days ago
I implemented coroutines for C with assembly [1] (x86 32 and 64 bit). I took advantage of the calling convention to cut down on the amount of state to save (4 registers for x86 32b and six for x86 64b). Mixing this with signals is probably unwise [2]. So far I've tested the code on Linux and Mac OS-X and it works (although I might not use it for C++ either).

[1] https://github.com/spc476/C-Coroutines

[2] In my not-so humble opinion, using signals at all is not wise.

2 comments

The shortest contest switch sequence I could come up on x86-64 is three instructions:

  xchg  %rsp, %rdx
  leaq  1f(%rip), %rax
  jmp   *%rsi
1:

It it expect the target stack ptr/ip pair to be in rdx/rsi and saves the current stack ptr and ip in rdx/rax. It does not save any register and uses gcc asm clobbers to instruct the compiler to save any other register.

Code at [1]. The comments about hacks and ub is because I'm trying to transparently propagate exceptions across coroutines, otherwise the stack switching us fairly robust (although GCC specific).

[1] https://github.com/gpderetta/delimited/blob/master/delimited...

Signals, done correctly, are hard. I agree with your NSHO for the most part. Neat code!