Undocumented iOS. Coroutines with C/C++

Problem

We have some third-party project (made with C or C++) with syncronos network code which produces big memory consumption by opening a thread on each incomming connection. As result of this behavior, OS kills our application.

The classic solutions

Actually we have two main different solutions:

  1. Rewrite this third-party project in a callback based asynchronous code. This is a hard way. It needs alot of time for investigation, alot of time for development, alot of time for debugging and alot of time for testing. Also, after this work we will be unable to update this third-party project to a newer version without investin the same amount of resources again.

  2. We can move from the threads to coroutines and implement coroutine manager and a stack compression code. It need time for development, debugging and testing almost only for a coroutine manager and a stack compression implementation. Ofcourse we still need some time for original sources investigation but only once. Also we will be able to update this third-party project in a future without significant time investment.

Of course coroutines are preffered.

So what's wrong with coroutines on iOS?

Usually we can use POSIX ucontext related calls for coroutines implementation. Or fibers on Windows.
The bad thing is that we can't use ucontext related calls on iOS: although they exist in SDK and can be included and calld, their code is not implemented internally at all - those calls are just stubs for returning an error. This behavior is unfortunatelly undocumented in Apple docs.

Mmm. And what can we do with this?

Actually solution exists.

In a C++ world, there is a well known library - Boost.
For a C++ project we can use Boost.context which is stated and actually has an iOS support.

Boost.coroutine hovewer, does not support iOS at the moment of this post writting.

OK. What about C?

Actually almost the same. Boost.context functions only thanks to several assembly files and a header. We just need to include needed assembly files and a header into our C code build config (and of course include header into our C code sources).

Assembly files are in the folder
src\asm We are interested in three arm64 related files for macho executable file format (Apple made file format):

jump_arm64_aapcs_macho_gas.S  
make_arm64_aapcs_macho_gas.S  
ontop_arm64_aapcs_macho_gas.S  

Header:
include\boost\context\detail\fcontext.hpp

Header should be slightly modified to be compatible with C code of course.

For Xcode we just need to drag all needed files into the list of files of our project.