makecontext.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Create new context.
  2. Copyright (C) 2015-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <sysdep.h>
  16. #include <stdarg.h>
  17. #include <stdint.h>
  18. #include <ucontext.h>
  19. /* makecontext sets up a stack and the registers for the
  20. user context. The stack looks like this:
  21. +-----------------------+
  22. | padding as required |
  23. +-----------------------+
  24. sp -> | parameters 5 to n |
  25. +-----------------------+
  26. The registers are set up like this:
  27. r4--r7 : parameter 1 to 4
  28. r16 : uc_link
  29. sp : stack pointer.
  30. */
  31. void
  32. __makecontext (ucontext_t *ucp, void (*func) (void), int argc, ...)
  33. {
  34. extern void __startcontext (void);
  35. unsigned long *sp;
  36. va_list ap;
  37. int i;
  38. sp = (unsigned long *)
  39. ((uintptr_t) ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
  40. /* Allocate stack arguments. */
  41. sp -= argc < 4 ? 0 : argc - 4;
  42. /* Keep the stack aligned. */
  43. sp = (unsigned long*) (((uintptr_t) sp) & -4L);
  44. /* Init version field. */
  45. ucp->uc_mcontext.version = 2;
  46. /* Keep uc_link in r16. */
  47. ucp->uc_mcontext.regs[15] = (uintptr_t) ucp->uc_link;
  48. /* Return address points to __startcontext(). */
  49. ucp->uc_mcontext.regs[23] = (uintptr_t) &__startcontext;
  50. /* Frame pointer is null. */
  51. ucp->uc_mcontext.regs[24] = (uintptr_t) 0;
  52. /* Restart in user-space starting at 'func'. */
  53. ucp->uc_mcontext.regs[27] = (uintptr_t) func;
  54. /* Set stack pointer. */
  55. ucp->uc_mcontext.regs[28] = (uintptr_t) sp;
  56. va_start (ap, argc);
  57. for (i = 0; i < argc; ++i)
  58. if (i < 4)
  59. ucp->uc_mcontext.regs[i + 3] = va_arg (ap, unsigned long);
  60. else
  61. sp[i - 4] = va_arg (ap, unsigned long);
  62. va_end (ap);
  63. }
  64. weak_alias (__makecontext, makecontext)