coroutine-sigaltstack.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*
  2. * sigaltstack coroutine initialization code
  3. *
  4. * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
  5. * Copyright (C) 2011 Kevin Wolf <kwolf@redhat.com>
  6. * Copyright (C) 2012 Alex Barcelo <abarcelo@ac.upc.edu>
  7. ** This file is partly based on pth_mctx.c, from the GNU Portable Threads
  8. ** Copyright (c) 1999-2006 Ralf S. Engelschall <rse@engelschall.com>
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  22. */
  23. /* XXX Is there a nicer way to disable glibc's stack check for longjmp? */
  24. #ifdef _FORTIFY_SOURCE
  25. #undef _FORTIFY_SOURCE
  26. #endif
  27. #include "qemu/osdep.h"
  28. #include <pthread.h>
  29. #include "qemu/coroutine_int.h"
  30. #ifdef CONFIG_SAFESTACK
  31. #error "SafeStack is not compatible with code run in alternate signal stacks"
  32. #endif
  33. typedef struct {
  34. Coroutine base;
  35. void *stack;
  36. size_t stack_size;
  37. sigjmp_buf env;
  38. } CoroutineSigAltStack;
  39. /**
  40. * Per-thread coroutine bookkeeping
  41. */
  42. typedef struct {
  43. /** Currently executing coroutine */
  44. Coroutine *current;
  45. /** The default coroutine */
  46. CoroutineSigAltStack leader;
  47. /** Information for the signal handler (trampoline) */
  48. sigjmp_buf tr_reenter;
  49. volatile sig_atomic_t tr_called;
  50. void *tr_handler;
  51. } CoroutineThreadState;
  52. static pthread_key_t thread_state_key;
  53. static CoroutineThreadState *coroutine_get_thread_state(void)
  54. {
  55. CoroutineThreadState *s = pthread_getspecific(thread_state_key);
  56. if (!s) {
  57. s = g_malloc0(sizeof(*s));
  58. s->current = &s->leader.base;
  59. pthread_setspecific(thread_state_key, s);
  60. }
  61. return s;
  62. }
  63. static void qemu_coroutine_thread_cleanup(void *opaque)
  64. {
  65. CoroutineThreadState *s = opaque;
  66. g_free(s);
  67. }
  68. static void __attribute__((constructor)) coroutine_init(void)
  69. {
  70. int ret;
  71. ret = pthread_key_create(&thread_state_key, qemu_coroutine_thread_cleanup);
  72. if (ret != 0) {
  73. fprintf(stderr, "unable to create leader key: %s\n", strerror(errno));
  74. abort();
  75. }
  76. }
  77. /* "boot" function
  78. * This is what starts the coroutine, is called from the trampoline
  79. * (from the signal handler when it is not signal handling, read ahead
  80. * for more information).
  81. */
  82. static void coroutine_bootstrap(CoroutineSigAltStack *self, Coroutine *co)
  83. {
  84. /* Initialize longjmp environment and switch back the caller */
  85. if (!sigsetjmp(self->env, 0)) {
  86. siglongjmp(*(sigjmp_buf *)co->entry_arg, 1);
  87. }
  88. while (true) {
  89. co->entry(co->entry_arg);
  90. qemu_coroutine_switch(co, co->caller, COROUTINE_TERMINATE);
  91. }
  92. }
  93. /*
  94. * This is used as the signal handler. This is called with the brand new stack
  95. * (thanks to sigaltstack). We have to return, given that this is a signal
  96. * handler and the sigmask and some other things are changed.
  97. */
  98. static void coroutine_trampoline(int signal)
  99. {
  100. CoroutineSigAltStack *self;
  101. Coroutine *co;
  102. CoroutineThreadState *coTS;
  103. /* Get the thread specific information */
  104. coTS = coroutine_get_thread_state();
  105. self = coTS->tr_handler;
  106. coTS->tr_called = 1;
  107. co = &self->base;
  108. /*
  109. * Here we have to do a bit of a ping pong between the caller, given that
  110. * this is a signal handler and we have to do a return "soon". Then the
  111. * caller can reestablish everything and do a siglongjmp here again.
  112. */
  113. if (!sigsetjmp(coTS->tr_reenter, 0)) {
  114. return;
  115. }
  116. /*
  117. * Ok, the caller has siglongjmp'ed back to us, so now prepare
  118. * us for the real machine state switching. We have to jump
  119. * into another function here to get a new stack context for
  120. * the auto variables (which have to be auto-variables
  121. * because the start of the thread happens later). Else with
  122. * PIC (i.e. Position Independent Code which is used when PTH
  123. * is built as a shared library) most platforms would
  124. * horrible core dump as experience showed.
  125. */
  126. coroutine_bootstrap(self, co);
  127. }
  128. Coroutine *qemu_coroutine_new(void)
  129. {
  130. CoroutineSigAltStack *co;
  131. CoroutineThreadState *coTS;
  132. struct sigaction sa;
  133. struct sigaction osa;
  134. stack_t ss;
  135. stack_t oss;
  136. sigset_t sigs;
  137. sigset_t osigs;
  138. sigjmp_buf old_env;
  139. static pthread_mutex_t sigusr2_mutex = PTHREAD_MUTEX_INITIALIZER;
  140. /* The way to manipulate stack is with the sigaltstack function. We
  141. * prepare a stack, with it delivering a signal to ourselves and then
  142. * put sigsetjmp/siglongjmp where needed.
  143. * This has been done keeping coroutine-ucontext as a model and with the
  144. * pth ideas (GNU Portable Threads). See coroutine-ucontext for the basics
  145. * of the coroutines and see pth_mctx.c (from the pth project) for the
  146. * sigaltstack way of manipulating stacks.
  147. */
  148. co = g_malloc0(sizeof(*co));
  149. co->stack_size = COROUTINE_STACK_SIZE;
  150. co->stack = qemu_alloc_stack(&co->stack_size);
  151. co->base.entry_arg = &old_env; /* stash away our jmp_buf */
  152. coTS = coroutine_get_thread_state();
  153. coTS->tr_handler = co;
  154. /*
  155. * Preserve the SIGUSR2 signal state, block SIGUSR2,
  156. * and establish our signal handler. The signal will
  157. * later transfer control onto the signal stack.
  158. */
  159. sigemptyset(&sigs);
  160. sigaddset(&sigs, SIGUSR2);
  161. pthread_sigmask(SIG_BLOCK, &sigs, &osigs);
  162. sa.sa_handler = coroutine_trampoline;
  163. sigfillset(&sa.sa_mask);
  164. sa.sa_flags = SA_ONSTACK;
  165. /*
  166. * sigaction() is a process-global operation. We must not run
  167. * this code in multiple threads at once.
  168. */
  169. pthread_mutex_lock(&sigusr2_mutex);
  170. if (sigaction(SIGUSR2, &sa, &osa) != 0) {
  171. abort();
  172. }
  173. /*
  174. * Set the new stack.
  175. */
  176. ss.ss_sp = co->stack;
  177. ss.ss_size = co->stack_size;
  178. ss.ss_flags = 0;
  179. if (sigaltstack(&ss, &oss) < 0) {
  180. abort();
  181. }
  182. /*
  183. * Now transfer control onto the signal stack and set it up.
  184. * It will return immediately via "return" after the sigsetjmp()
  185. * was performed. Be careful here with race conditions. The
  186. * signal can be delivered the first time sigsuspend() is
  187. * called.
  188. */
  189. coTS->tr_called = 0;
  190. pthread_kill(pthread_self(), SIGUSR2);
  191. sigfillset(&sigs);
  192. sigdelset(&sigs, SIGUSR2);
  193. while (!coTS->tr_called) {
  194. sigsuspend(&sigs);
  195. }
  196. /*
  197. * Inform the system that we are back off the signal stack by
  198. * removing the alternative signal stack. Be careful here: It
  199. * first has to be disabled, before it can be removed.
  200. */
  201. sigaltstack(NULL, &ss);
  202. ss.ss_flags = SS_DISABLE;
  203. if (sigaltstack(&ss, NULL) < 0) {
  204. abort();
  205. }
  206. sigaltstack(NULL, &ss);
  207. if (!(oss.ss_flags & SS_DISABLE)) {
  208. sigaltstack(&oss, NULL);
  209. }
  210. /*
  211. * Restore the old SIGUSR2 signal handler and mask
  212. */
  213. sigaction(SIGUSR2, &osa, NULL);
  214. pthread_mutex_unlock(&sigusr2_mutex);
  215. pthread_sigmask(SIG_SETMASK, &osigs, NULL);
  216. /*
  217. * Now enter the trampoline again, but this time not as a signal
  218. * handler. Instead we jump into it directly. The functionally
  219. * redundant ping-pong pointer arithmetic is necessary to avoid
  220. * type-conversion warnings related to the `volatile' qualifier and
  221. * the fact that `jmp_buf' usually is an array type.
  222. */
  223. if (!sigsetjmp(old_env, 0)) {
  224. siglongjmp(coTS->tr_reenter, 1);
  225. }
  226. /*
  227. * Ok, we returned again, so now we're finished
  228. */
  229. return &co->base;
  230. }
  231. void qemu_coroutine_delete(Coroutine *co_)
  232. {
  233. CoroutineSigAltStack *co = DO_UPCAST(CoroutineSigAltStack, base, co_);
  234. qemu_free_stack(co->stack, co->stack_size);
  235. g_free(co);
  236. }
  237. CoroutineAction qemu_coroutine_switch(Coroutine *from_, Coroutine *to_,
  238. CoroutineAction action)
  239. {
  240. CoroutineSigAltStack *from = DO_UPCAST(CoroutineSigAltStack, base, from_);
  241. CoroutineSigAltStack *to = DO_UPCAST(CoroutineSigAltStack, base, to_);
  242. CoroutineThreadState *s = coroutine_get_thread_state();
  243. int ret;
  244. s->current = to_;
  245. ret = sigsetjmp(from->env, 0);
  246. if (ret == 0) {
  247. siglongjmp(to->env, action);
  248. }
  249. return ret;
  250. }
  251. Coroutine *qemu_coroutine_self(void)
  252. {
  253. CoroutineThreadState *s = coroutine_get_thread_state();
  254. return s->current;
  255. }
  256. bool qemu_in_coroutine(void)
  257. {
  258. CoroutineThreadState *s = pthread_getspecific(thread_state_key);
  259. return s && s->current->caller;
  260. }