gc_hooks.nim 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2019 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Hooks for memory management. Can be used to implement custom garbage
  10. ## collectors etc.
  11. type
  12. GlobalMarkerProc = proc () {.nimcall, benign, raises: [], tags: [].}
  13. var
  14. globalMarkersLen: int
  15. globalMarkers: array[0..3499, GlobalMarkerProc]
  16. threadLocalMarkersLen: int
  17. threadLocalMarkers: array[0..3499, GlobalMarkerProc]
  18. proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
  19. if globalMarkersLen <= high(globalMarkers):
  20. globalMarkers[globalMarkersLen] = markerProc
  21. inc globalMarkersLen
  22. else:
  23. cstderr.rawWrite("[GC] cannot register global variable; too many global variables")
  24. rawQuit 1
  25. proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
  26. if threadLocalMarkersLen <= high(threadLocalMarkers):
  27. threadLocalMarkers[threadLocalMarkersLen] = markerProc
  28. inc threadLocalMarkersLen
  29. else:
  30. cstderr.rawWrite("[GC] cannot register thread local variable; too many thread local variables")
  31. rawQuit 1
  32. proc traverseGlobals*() =
  33. for i in 0..globalMarkersLen-1:
  34. globalMarkers[i]()
  35. proc traverseThreadLocals*() =
  36. for i in 0..threadLocalMarkersLen-1:
  37. threadLocalMarkers[i]()
  38. var
  39. newObjHook*: proc (typ: PNimType, size: int): pointer {.nimcall, tags: [], raises: [], gcsafe.}
  40. traverseObjHook*: proc (p: pointer, op: int) {.nimcall, tags: [], raises: [], gcsafe.}
  41. proc nimGCvisit(p: pointer, op: int) {.inl, compilerRtl.} =
  42. traverseObjHook(p, op)
  43. proc newObj(typ: PNimType, size: int): pointer {.inl, compilerRtl.} =
  44. result = newObjHook(typ, size)