go-defer.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* go-defer.c -- manage the defer stack.
  2. Copyright 2009 The Go Authors. All rights reserved.
  3. Use of this source code is governed by a BSD-style
  4. license that can be found in the LICENSE file. */
  5. #include <stddef.h>
  6. #include "runtime.h"
  7. #include "go-alloc.h"
  8. #include "go-panic.h"
  9. #include "go-defer.h"
  10. /* This function is called each time we need to defer a call. */
  11. void
  12. __go_defer (_Bool *frame, void (*pfn) (void *), void *arg)
  13. {
  14. G *g;
  15. struct __go_defer_stack *n;
  16. g = runtime_g ();
  17. n = runtime_newdefer ();
  18. n->__next = g->defer;
  19. n->__frame = frame;
  20. n->__panic = g->panic;
  21. n->__pfn = pfn;
  22. n->__arg = arg;
  23. n->__retaddr = NULL;
  24. n->__makefunc_can_recover = 0;
  25. n->__special = 0;
  26. g->defer = n;
  27. }
  28. /* This function is called when we want to undefer the stack. */
  29. void
  30. __go_undefer (_Bool *frame)
  31. {
  32. G *g;
  33. g = runtime_g ();
  34. while (g->defer != NULL && g->defer->__frame == frame)
  35. {
  36. struct __go_defer_stack *d;
  37. void (*pfn) (void *);
  38. d = g->defer;
  39. pfn = d->__pfn;
  40. d->__pfn = NULL;
  41. if (pfn != NULL)
  42. (*pfn) (d->__arg);
  43. g->defer = d->__next;
  44. /* This may be called by a cgo callback routine to defer the
  45. call to syscall.CgocallBackDone, in which case we will not
  46. have a memory context. Don't try to free anything in that
  47. case--the GC will release it later. */
  48. if (runtime_m () != NULL)
  49. runtime_freedefer (d);
  50. /* Since we are executing a defer function here, we know we are
  51. returning from the calling function. If the calling
  52. function, or one of its callees, paniced, then the defer
  53. functions would be executed by __go_panic. */
  54. *frame = 1;
  55. }
  56. }
  57. /* This function is called to record the address to which the deferred
  58. function returns. This may in turn be checked by __go_can_recover.
  59. The frontend relies on this function returning false. */
  60. _Bool
  61. __go_set_defer_retaddr (void *retaddr)
  62. {
  63. G *g;
  64. g = runtime_g ();
  65. if (g->defer != NULL)
  66. g->defer->__retaddr = __builtin_extract_return_addr (retaddr);
  67. return 0;
  68. }