arm.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #define LIBCO_C
  2. #include "libco.h"
  3. #include "settings.h"
  4. #include <assert.h>
  5. #include <stdlib.h>
  6. #ifdef LIBCO_MPROTECT
  7. #include <unistd.h>
  8. #include <sys/mman.h>
  9. #endif
  10. #ifdef __cplusplus
  11. extern "C" {
  12. #endif
  13. static thread_local unsigned long co_active_buffer[64];
  14. static thread_local cothread_t co_active_handle = 0;
  15. static void (*co_swap)(cothread_t, cothread_t) = 0;
  16. #ifdef LIBCO_MPROTECT
  17. alignas(4096)
  18. #else
  19. section(text)
  20. #endif
  21. static const unsigned long co_swap_function[1024] = {
  22. 0xe8a16ff0, /* stmia r1!, {r4-r11,sp,lr} */
  23. 0xe8b0aff0, /* ldmia r0!, {r4-r11,sp,pc} */
  24. 0xe12fff1e, /* bx lr */
  25. };
  26. static void co_init() {
  27. #ifdef LIBCO_MPROTECT
  28. unsigned long addr = (unsigned long)co_swap_function;
  29. unsigned long base = addr - (addr % sysconf(_SC_PAGESIZE));
  30. unsigned long size = (addr - base) + sizeof co_swap_function;
  31. mprotect((void*)base, size, PROT_READ | PROT_EXEC);
  32. #endif
  33. }
  34. cothread_t co_active() {
  35. if(!co_active_handle) co_active_handle = &co_active_buffer;
  36. return co_active_handle;
  37. }
  38. cothread_t co_derive(void* memory, unsigned int size, void (*entrypoint)(void)) {
  39. unsigned long* handle;
  40. if(!co_swap) {
  41. co_init();
  42. co_swap = (void (*)(cothread_t, cothread_t))co_swap_function;
  43. }
  44. if(!co_active_handle) co_active_handle = &co_active_buffer;
  45. if(handle = (unsigned long*)memory) {
  46. unsigned int offset = (size & ~15);
  47. unsigned long* p = (unsigned long*)((unsigned char*)handle + offset);
  48. handle[8] = (unsigned long)p;
  49. handle[9] = (unsigned long)entrypoint;
  50. }
  51. return handle;
  52. }
  53. cothread_t co_create(unsigned int size, void (*entrypoint)(void)) {
  54. void* memory = malloc(size);
  55. if(!memory) return (cothread_t)0;
  56. return co_derive(memory, size, entrypoint);
  57. }
  58. void co_delete(cothread_t handle) {
  59. free(handle);
  60. }
  61. void co_switch(cothread_t handle) {
  62. cothread_t co_previous_handle = co_active_handle;
  63. co_swap(co_active_handle = handle, co_previous_handle);
  64. }
  65. int co_serializable() {
  66. return 1;
  67. }
  68. #ifdef __cplusplus
  69. }
  70. #endif