gc.nim 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2016 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Garbage Collector
  10. #
  11. # Refcounting + Mark&Sweep. Complex algorithms avoided.
  12. # Been there, done that, didn't work.
  13. #[
  14. A *cell* is anything that is traced by the GC
  15. (sequences, refs, strings, closures).
  16. The basic algorithm is *Deferrent Reference Counting* with cycle detection.
  17. References on the stack are not counted for better performance and easier C
  18. code generation.
  19. Each cell has a header consisting of a RC and a pointer to its type
  20. descriptor. However the program does not know about these, so they are placed at
  21. negative offsets. In the GC code the type `PCell` denotes a pointer
  22. decremented by the right offset, so that the header can be accessed easily. It
  23. is extremely important that `pointer` is not confused with a `PCell`.
  24. In Nim the compiler cannot always know if a reference
  25. is stored on the stack or not. This is caused by var parameters.
  26. Consider this example:
  27. ```Nim
  28. proc setRef(r: var ref TNode) =
  29. new(r)
  30. proc usage =
  31. var
  32. r: ref TNode
  33. setRef(r) # here we should not update the reference counts, because
  34. # r is on the stack
  35. setRef(r.left) # here we should update the refcounts!
  36. ```
  37. We have to decide at runtime whether the reference is on the stack or not.
  38. The generated code looks roughly like this:
  39. ```C
  40. void setref(TNode** ref) {
  41. unsureAsgnRef(ref, newObj(TNode_TI, sizeof(TNode)))
  42. }
  43. void usage(void) {
  44. setRef(&r)
  45. setRef(&r->left)
  46. }
  47. ```
  48. Note that for systems with a continuous stack (which most systems have)
  49. the check whether the ref is on the stack is very cheap (only two
  50. comparisons).
  51. ]#
  52. {.push profiler:off.}
  53. const
  54. CycleIncrease = 2 # is a multiplicative increase
  55. InitialCycleThreshold = when defined(nimCycleBreaker): high(int)
  56. else: 4*1024*1024 # X MB because cycle checking is slow
  57. InitialZctThreshold = 500 # we collect garbage if the ZCT's size
  58. # reaches this threshold
  59. # this seems to be a good value
  60. withRealTime = defined(useRealtimeGC)
  61. when withRealTime and not declared(getTicks):
  62. include "system/timers"
  63. when defined(memProfiler):
  64. proc nimProfile(requestedSize: int) {.benign.}
  65. when hasThreadSupport:
  66. import std/sharedlist
  67. const
  68. rcIncrement = 0b1000 # so that lowest 3 bits are not touched
  69. rcBlack = 0b000 # cell is colored black; in use or free
  70. rcGray = 0b001 # possible member of a cycle
  71. rcWhite = 0b010 # member of a garbage cycle
  72. rcPurple = 0b011 # possible root of a cycle
  73. ZctFlag = 0b100 # in ZCT
  74. rcShift = 3 # shift by rcShift to get the reference counter
  75. colorMask = 0b011
  76. type
  77. WalkOp = enum
  78. waMarkGlobal, # part of the backup/debug mark&sweep
  79. waMarkPrecise, # part of the backup/debug mark&sweep
  80. waZctDecRef, waPush
  81. #, waDebug
  82. Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign, raises: [].}
  83. # A ref type can have a finalizer that is called before the object's
  84. # storage is freed.
  85. GcStat {.final, pure.} = object
  86. stackScans: int # number of performed stack scans (for statistics)
  87. cycleCollections: int # number of performed full collections
  88. maxThreshold: int # max threshold that has been set
  89. maxStackSize: int # max stack size
  90. maxStackCells: int # max stack cells in ``decStack``
  91. cycleTableSize: int # max entries in cycle table
  92. maxPause: int64 # max measured GC pause in nanoseconds
  93. GcStack {.final, pure.} = object
  94. when nimCoroutines:
  95. prev: ptr GcStack
  96. next: ptr GcStack
  97. maxStackSize: int # Used to track statistics because we can not use
  98. # GcStat.maxStackSize when multiple stacks exist.
  99. bottom: pointer
  100. when withRealTime or nimCoroutines:
  101. pos: pointer # Used with `withRealTime` only for code clarity, see GC_Step().
  102. when withRealTime:
  103. bottomSaved: pointer
  104. GcHeap {.final, pure.} = object # this contains the zero count and
  105. # non-zero count table
  106. stack: GcStack
  107. when nimCoroutines:
  108. activeStack: ptr GcStack # current executing coroutine stack.
  109. cycleThreshold: int
  110. zctThreshold: int
  111. when useCellIds:
  112. idGenerator: int
  113. zct: CellSeq # the zero count table
  114. decStack: CellSeq # cells in the stack that are to decref again
  115. tempStack: CellSeq # temporary stack for recursion elimination
  116. recGcLock: int # prevent recursion via finalizers; no thread lock
  117. when withRealTime:
  118. maxPause: Nanos # max allowed pause in nanoseconds; active if > 0
  119. region: MemRegion # garbage collected region
  120. stat: GcStat
  121. marked: CellSet
  122. additionalRoots: CellSeq # dummy roots for GC_ref/unref
  123. when hasThreadSupport:
  124. toDispose: SharedList[pointer]
  125. gcThreadId: int
  126. var
  127. gch {.rtlThreadVar.}: GcHeap
  128. when not defined(useNimRtl):
  129. instantiateForRegion(gch.region)
  130. template gcAssert(cond: bool, msg: string) =
  131. when defined(useGcAssert):
  132. if not cond:
  133. cstderr.rawWrite "[GCASSERT] "
  134. cstderr.rawWrite msg
  135. when defined(logGC):
  136. cstderr.rawWrite "[GCASSERT] statistics:\L"
  137. cstderr.rawWrite GC_getStatistics()
  138. GC_disable()
  139. writeStackTrace()
  140. #var x: ptr int
  141. #echo x[]
  142. rawQuit 1
  143. proc addZCT(s: var CellSeq, c: PCell) {.noinline.} =
  144. if (c.refcount and ZctFlag) == 0:
  145. c.refcount = c.refcount or ZctFlag
  146. add(s, c)
  147. proc cellToUsr(cell: PCell): pointer {.inline.} =
  148. # convert object (=pointer to refcount) to pointer to userdata
  149. result = cast[pointer](cast[int](cell)+%ByteAddress(sizeof(Cell)))
  150. proc usrToCell(usr: pointer): PCell {.inline.} =
  151. # convert pointer to userdata to object (=pointer to refcount)
  152. result = cast[PCell](cast[int](usr)-%ByteAddress(sizeof(Cell)))
  153. proc extGetCellType(c: pointer): PNimType {.compilerproc.} =
  154. # used for code generation concerning debugging
  155. result = usrToCell(c).typ
  156. proc internRefcount(p: pointer): int {.exportc: "getRefcount".} =
  157. result = usrToCell(p).refcount shr rcShift
  158. # this that has to equals zero, otherwise we have to round up UnitsPerPage:
  159. when BitsPerPage mod (sizeof(int)*8) != 0:
  160. {.error: "(BitsPerPage mod BitsPerUnit) should be zero!".}
  161. template color(c): untyped = c.refCount and colorMask
  162. template setColor(c, col) =
  163. when col == rcBlack:
  164. c.refcount = c.refcount and not colorMask
  165. else:
  166. c.refcount = c.refcount and not colorMask or col
  167. when defined(logGC):
  168. proc writeCell(msg: cstring, c: PCell) =
  169. var kind = -1
  170. var typName: cstring = "nil"
  171. if c.typ != nil:
  172. kind = ord(c.typ.kind)
  173. when defined(nimTypeNames):
  174. if not c.typ.name.isNil:
  175. typName = c.typ.name
  176. when leakDetector:
  177. c_printf("[GC] %s: %p %d %s rc=%ld from %s(%ld)\n",
  178. msg, c, kind, typName, c.refcount shr rcShift, c.filename, c.line)
  179. else:
  180. c_printf("[GC] %s: %p %d %s rc=%ld; thread=%ld\n",
  181. msg, c, kind, typName, c.refcount shr rcShift, gch.gcThreadId)
  182. template logCell(msg: cstring, c: PCell) =
  183. when defined(logGC):
  184. writeCell(msg, c)
  185. template gcTrace(cell, state: untyped) =
  186. when traceGC: traceCell(cell, state)
  187. # forward declarations:
  188. proc collectCT(gch: var GcHeap) {.benign, raises: [].}
  189. proc isOnStack(p: pointer): bool {.noinline, benign, raises: [].}
  190. proc forAllChildren(cell: PCell, op: WalkOp) {.benign, raises: [].}
  191. proc doOperation(p: pointer, op: WalkOp) {.benign, raises: [].}
  192. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign, raises: [].}
  193. # we need the prototype here for debugging purposes
  194. proc incRef(c: PCell) {.inline.} =
  195. gcAssert(isAllocatedPtr(gch.region, c), "incRef: interiorPtr")
  196. c.refcount = c.refcount +% rcIncrement
  197. # and not colorMask
  198. logCell("incRef", c)
  199. proc nimGCref(p: pointer) {.compilerproc.} =
  200. # we keep it from being collected by pretending it's not even allocated:
  201. let c = usrToCell(p)
  202. add(gch.additionalRoots, c)
  203. incRef(c)
  204. proc rtlAddZCT(c: PCell) {.rtl, inl.} =
  205. # we MUST access gch as a global here, because this crosses DLL boundaries!
  206. addZCT(gch.zct, c)
  207. proc decRef(c: PCell) {.inline.} =
  208. gcAssert(isAllocatedPtr(gch.region, c), "decRef: interiorPtr")
  209. gcAssert(c.refcount >=% rcIncrement, "decRef")
  210. c.refcount = c.refcount -% rcIncrement
  211. if c.refcount <% rcIncrement:
  212. rtlAddZCT(c)
  213. logCell("decRef", c)
  214. proc nimGCunref(p: pointer) {.compilerproc.} =
  215. let cell = usrToCell(p)
  216. var L = gch.additionalRoots.len-1
  217. var i = L
  218. let d = gch.additionalRoots.d
  219. while i >= 0:
  220. if d[i] == cell:
  221. d[i] = d[L]
  222. dec gch.additionalRoots.len
  223. break
  224. dec(i)
  225. decRef(usrToCell(p))
  226. include gc_common
  227. template beforeDealloc(gch: var GcHeap; c: PCell; msg: typed) =
  228. when false:
  229. for i in 0..gch.decStack.len-1:
  230. if gch.decStack.d[i] == c:
  231. sysAssert(false, msg)
  232. proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
  233. sysAssert(allocInv(gch.region), "begin nimGCunrefNoCycle")
  234. decRef(usrToCell(p))
  235. sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5")
  236. proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
  237. decRef(usrToCell(p))
  238. proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} =
  239. # the code generator calls this proc!
  240. gcAssert(not isOnStack(dest), "asgnRef")
  241. # BUGFIX: first incRef then decRef!
  242. if src != nil: incRef(usrToCell(src))
  243. if dest[] != nil: decRef(usrToCell(dest[]))
  244. dest[] = src
  245. proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
  246. deprecated: "old compiler compat".} = asgnRef(dest, src)
  247. proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc.} =
  248. # unsureAsgnRef updates the reference counters only if dest is not on the
  249. # stack. It is used by the code generator if it cannot decide whether a
  250. # reference is in the stack or not (this can happen for var parameters).
  251. if not isOnStack(dest):
  252. if src != nil: incRef(usrToCell(src))
  253. # XXX finally use assembler for the stack checking instead!
  254. # the test for '!= nil' is correct, but I got tired of the segfaults
  255. # resulting from the crappy stack checking:
  256. if cast[int](dest[]) >=% PageSize: decRef(usrToCell(dest[]))
  257. else:
  258. # can't be an interior pointer if it's a stack location!
  259. gcAssert(interiorAllocatedPtr(gch.region, dest) == nil,
  260. "stack loc AND interior pointer")
  261. dest[] = src
  262. proc initGC() =
  263. when not defined(useNimRtl):
  264. when traceGC:
  265. for i in low(CellState)..high(CellState): init(states[i])
  266. gch.cycleThreshold = InitialCycleThreshold
  267. gch.zctThreshold = InitialZctThreshold
  268. gch.stat.stackScans = 0
  269. gch.stat.cycleCollections = 0
  270. gch.stat.maxThreshold = 0
  271. gch.stat.maxStackSize = 0
  272. gch.stat.maxStackCells = 0
  273. gch.stat.cycleTableSize = 0
  274. # init the rt
  275. init(gch.zct)
  276. init(gch.tempStack)
  277. init(gch.decStack)
  278. init(gch.marked)
  279. init(gch.additionalRoots)
  280. when hasThreadSupport:
  281. init(gch.toDispose)
  282. gch.gcThreadId = atomicInc(gHeapidGenerator) - 1
  283. gcAssert(gch.gcThreadId >= 0, "invalid computed thread ID")
  284. proc cellsetReset(s: var CellSet) =
  285. deinit(s)
  286. init(s)
  287. {.push stacktrace:off.}
  288. proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) {.benign.} =
  289. var d = cast[int](dest)
  290. case n.kind
  291. of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op)
  292. of nkList:
  293. for i in 0..n.len-1:
  294. # inlined for speed
  295. if n.sons[i].kind == nkSlot:
  296. if n.sons[i].typ.kind in {tyRef, tyString, tySequence}:
  297. doOperation(cast[PPointer](d +% n.sons[i].offset)[], op)
  298. else:
  299. forAllChildrenAux(cast[pointer](d +% n.sons[i].offset),
  300. n.sons[i].typ, op)
  301. else:
  302. forAllSlotsAux(dest, n.sons[i], op)
  303. of nkCase:
  304. var m = selectBranch(dest, n)
  305. if m != nil: forAllSlotsAux(dest, m, op)
  306. of nkNone: sysAssert(false, "forAllSlotsAux")
  307. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) =
  308. var d = cast[int](dest)
  309. if dest == nil: return # nothing to do
  310. if ntfNoRefs notin mt.flags:
  311. case mt.kind
  312. of tyRef, tyString, tySequence: # leaf:
  313. doOperation(cast[PPointer](d)[], op)
  314. of tyObject, tyTuple:
  315. forAllSlotsAux(dest, mt.node, op)
  316. of tyArray, tyArrayConstr, tyOpenArray:
  317. for i in 0..(mt.size div mt.base.size)-1:
  318. forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op)
  319. else: discard
  320. proc forAllChildren(cell: PCell, op: WalkOp) =
  321. gcAssert(cell != nil, "forAllChildren: cell is nil")
  322. gcAssert(isAllocatedPtr(gch.region, cell), "forAllChildren: pointer not part of the heap")
  323. gcAssert(cell.typ != nil, "forAllChildren: cell.typ is nil")
  324. gcAssert cell.typ.kind in {tyRef, tySequence, tyString}, "forAllChildren: unknown GC'ed type"
  325. let marker = cell.typ.marker
  326. if marker != nil:
  327. marker(cellToUsr(cell), op.int)
  328. else:
  329. case cell.typ.kind
  330. of tyRef: # common case
  331. forAllChildrenAux(cellToUsr(cell), cell.typ.base, op)
  332. of tySequence:
  333. var d = cast[int](cellToUsr(cell))
  334. var s = cast[PGenericSeq](d)
  335. if s != nil:
  336. for i in 0..s.len-1:
  337. forAllChildrenAux(cast[pointer](d +% align(GenericSeqSize, cell.typ.base.align) +% i *% cell.typ.base.size), cell.typ.base, op)
  338. else: discard
  339. proc addNewObjToZCT(res: PCell, gch: var GcHeap) {.inline.} =
  340. # we check the last 8 entries (cache line) for a slot that could be reused.
  341. # In 63% of all cases we succeed here! But we have to optimize the heck
  342. # out of this small linear search so that ``newObj`` is not slowed down.
  343. #
  344. # Slots to try cache hit
  345. # 1 32%
  346. # 4 59%
  347. # 8 63%
  348. # 16 66%
  349. # all slots 68%
  350. var L = gch.zct.len
  351. var d = gch.zct.d
  352. when true:
  353. # loop unrolled for performance:
  354. template replaceZctEntry(i: untyped) =
  355. c = d[i]
  356. if c.refcount >=% rcIncrement:
  357. c.refcount = c.refcount and not ZctFlag
  358. d[i] = res
  359. return
  360. if L > 8:
  361. var c: PCell
  362. replaceZctEntry(L-1)
  363. replaceZctEntry(L-2)
  364. replaceZctEntry(L-3)
  365. replaceZctEntry(L-4)
  366. replaceZctEntry(L-5)
  367. replaceZctEntry(L-6)
  368. replaceZctEntry(L-7)
  369. replaceZctEntry(L-8)
  370. add(gch.zct, res)
  371. else:
  372. d[L] = res
  373. inc(gch.zct.len)
  374. else:
  375. for i in countdown(L-1, max(0, L-8)):
  376. var c = d[i]
  377. if c.refcount >=% rcIncrement:
  378. c.refcount = c.refcount and not ZctFlag
  379. d[i] = res
  380. return
  381. add(gch.zct, res)
  382. {.push stackTrace: off, profiler:off.}
  383. proc gcInvariant*() =
  384. sysAssert(allocInv(gch.region), "injected")
  385. when declared(markForDebug):
  386. markForDebug(gch)
  387. {.pop.}
  388. template setFrameInfo(c: PCell) =
  389. when leakDetector:
  390. if framePtr != nil and framePtr.prev != nil:
  391. c.filename = framePtr.prev.filename
  392. c.line = framePtr.prev.line
  393. else:
  394. c.filename = nil
  395. c.line = 0
  396. proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap): pointer =
  397. # generates a new object and sets its reference counter to 0
  398. incTypeSize typ, size
  399. sysAssert(allocInv(gch.region), "rawNewObj begin")
  400. gcAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1")
  401. collectCT(gch)
  402. var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell)))
  403. #gcAssert typ.kind in {tyString, tySequence} or size >= typ.base.size, "size too small"
  404. gcAssert((cast[int](res) and (MemAlign-1)) == 0, "newObj: 2")
  405. # now it is buffered in the ZCT
  406. res.typ = typ
  407. setFrameInfo(res)
  408. # refcount is zero, color is black, but mark it to be in the ZCT
  409. res.refcount = ZctFlag
  410. sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3")
  411. # its refcount is zero, so add it to the ZCT:
  412. addNewObjToZCT(res, gch)
  413. logCell("new cell", res)
  414. track("rawNewObj", res, size)
  415. gcTrace(res, csAllocated)
  416. when useCellIds:
  417. inc gch.idGenerator
  418. res.id = gch.idGenerator * 1000_000 + gch.gcThreadId
  419. result = cellToUsr(res)
  420. sysAssert(allocInv(gch.region), "rawNewObj end")
  421. {.pop.} # .stackTrace off
  422. {.pop.} # .profiler off
  423. proc newObjNoInit(typ: PNimType, size: int): pointer {.compilerRtl.} =
  424. result = rawNewObj(typ, size, gch)
  425. when defined(memProfiler): nimProfile(size)
  426. proc newObj(typ: PNimType, size: int): pointer {.compilerRtl, noinline.} =
  427. result = rawNewObj(typ, size, gch)
  428. zeroMem(result, size)
  429. when defined(memProfiler): nimProfile(size)
  430. {.push overflowChecks: on.}
  431. proc newSeq(typ: PNimType, len: int): pointer {.compilerRtl.} =
  432. # `newObj` already uses locks, so no need for them here.
  433. let size = align(GenericSeqSize, typ.base.align) + len * typ.base.size
  434. result = newObj(typ, size)
  435. cast[PGenericSeq](result).len = len
  436. cast[PGenericSeq](result).reserved = len
  437. when defined(memProfiler): nimProfile(size)
  438. {.pop.}
  439. proc newObjRC1(typ: PNimType, size: int): pointer {.compilerRtl, noinline.} =
  440. # generates a new object and sets its reference counter to 1
  441. incTypeSize typ, size
  442. sysAssert(allocInv(gch.region), "newObjRC1 begin")
  443. gcAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1")
  444. collectCT(gch)
  445. sysAssert(allocInv(gch.region), "newObjRC1 after collectCT")
  446. var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell)))
  447. sysAssert(allocInv(gch.region), "newObjRC1 after rawAlloc")
  448. sysAssert((cast[int](res) and (MemAlign-1)) == 0, "newObj: 2")
  449. # now it is buffered in the ZCT
  450. res.typ = typ
  451. setFrameInfo(res)
  452. res.refcount = rcIncrement # refcount is 1
  453. sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3")
  454. logCell("new cell", res)
  455. track("newObjRC1", res, size)
  456. gcTrace(res, csAllocated)
  457. when useCellIds:
  458. inc gch.idGenerator
  459. res.id = gch.idGenerator * 1000_000 + gch.gcThreadId
  460. result = cellToUsr(res)
  461. zeroMem(result, size)
  462. sysAssert(allocInv(gch.region), "newObjRC1 end")
  463. when defined(memProfiler): nimProfile(size)
  464. {.push overflowChecks: on.}
  465. proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} =
  466. let size = align(GenericSeqSize, typ.base.align) + len * typ.base.size
  467. result = newObjRC1(typ, size)
  468. cast[PGenericSeq](result).len = len
  469. cast[PGenericSeq](result).reserved = len
  470. when defined(memProfiler): nimProfile(size)
  471. {.pop.}
  472. proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer =
  473. collectCT(gch)
  474. var ol = usrToCell(old)
  475. sysAssert(ol.typ != nil, "growObj: 1")
  476. gcAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2")
  477. sysAssert(allocInv(gch.region), "growObj begin")
  478. var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell)))
  479. var elemSize,elemAlign = 1
  480. if ol.typ.kind != tyString:
  481. elemSize = ol.typ.base.size
  482. elemAlign = ol.typ.base.align
  483. incTypeSize ol.typ, newsize
  484. var oldsize = align(GenericSeqSize, elemAlign) + cast[PGenericSeq](old).len * elemSize
  485. copyMem(res, ol, oldsize + sizeof(Cell))
  486. zeroMem(cast[pointer](cast[int](res) +% oldsize +% sizeof(Cell)),
  487. newsize-oldsize)
  488. sysAssert((cast[int](res) and (MemAlign-1)) == 0, "growObj: 3")
  489. # This can be wrong for intermediate temps that are nevertheless on the
  490. # heap because of lambda lifting:
  491. #gcAssert(res.refcount shr rcShift <=% 1, "growObj: 4")
  492. logCell("growObj old cell", ol)
  493. logCell("growObj new cell", res)
  494. gcTrace(ol, csZctFreed)
  495. gcTrace(res, csAllocated)
  496. track("growObj old", ol, 0)
  497. track("growObj new", res, newsize)
  498. # since we steal the old seq's contents, we set the old length to 0.
  499. cast[PGenericSeq](old).len = 0
  500. when useCellIds:
  501. inc gch.idGenerator
  502. res.id = gch.idGenerator * 1000_000 + gch.gcThreadId
  503. result = cellToUsr(res)
  504. sysAssert(allocInv(gch.region), "growObj end")
  505. when defined(memProfiler): nimProfile(newsize-oldsize)
  506. proc growObj(old: pointer, newsize: int): pointer {.rtl.} =
  507. result = growObj(old, newsize, gch)
  508. {.push profiler:off, stackTrace:off.}
  509. # ---------------- cycle collector -------------------------------------------
  510. proc freeCyclicCell(gch: var GcHeap, c: PCell) =
  511. prepareDealloc(c)
  512. gcTrace(c, csCycFreed)
  513. track("cycle collector dealloc cell", c, 0)
  514. logCell("cycle collector dealloc cell", c)
  515. when reallyDealloc:
  516. sysAssert(allocInv(gch.region), "free cyclic cell")
  517. beforeDealloc(gch, c, "freeCyclicCell: stack trash")
  518. rawDealloc(gch.region, c)
  519. else:
  520. gcAssert(c.typ != nil, "freeCyclicCell")
  521. zeroMem(c, sizeof(Cell))
  522. proc sweep(gch: var GcHeap) =
  523. for x in allObjects(gch.region):
  524. if isCell(x):
  525. # cast to PCell is correct here:
  526. var c = cast[PCell](x)
  527. if c notin gch.marked: freeCyclicCell(gch, c)
  528. proc markS(gch: var GcHeap, c: PCell) =
  529. gcAssert isAllocatedPtr(gch.region, c), "markS: foreign heap root detected A!"
  530. incl(gch.marked, c)
  531. gcAssert gch.tempStack.len == 0, "stack not empty!"
  532. forAllChildren(c, waMarkPrecise)
  533. while gch.tempStack.len > 0:
  534. dec gch.tempStack.len
  535. var d = gch.tempStack.d[gch.tempStack.len]
  536. gcAssert isAllocatedPtr(gch.region, d), "markS: foreign heap root detected B!"
  537. if not containsOrIncl(gch.marked, d):
  538. forAllChildren(d, waMarkPrecise)
  539. proc markGlobals(gch: var GcHeap) {.raises: [].} =
  540. if gch.gcThreadId == 0:
  541. for i in 0 .. globalMarkersLen-1: globalMarkers[i]()
  542. for i in 0 .. threadLocalMarkersLen-1: threadLocalMarkers[i]()
  543. let d = gch.additionalRoots.d
  544. for i in 0 .. gch.additionalRoots.len-1: markS(gch, d[i])
  545. when logGC:
  546. var
  547. cycleCheckA: array[100, PCell]
  548. cycleCheckALen = 0
  549. proc alreadySeen(c: PCell): bool =
  550. for i in 0 .. cycleCheckALen-1:
  551. if cycleCheckA[i] == c: return true
  552. if cycleCheckALen == len(cycleCheckA):
  553. gcAssert(false, "cycle detection overflow")
  554. rawQuit 1
  555. cycleCheckA[cycleCheckALen] = c
  556. inc cycleCheckALen
  557. proc debugGraph(s: PCell) =
  558. if alreadySeen(s):
  559. writeCell("child cell (already seen) ", s)
  560. else:
  561. writeCell("cell {", s)
  562. forAllChildren(s, waDebug)
  563. c_printf("}\n")
  564. proc doOperation(p: pointer, op: WalkOp) =
  565. if p == nil: return
  566. var c: PCell = usrToCell(p)
  567. gcAssert(c != nil, "doOperation: 1")
  568. # the 'case' should be faster than function pointers because of easy
  569. # prediction:
  570. case op
  571. of waZctDecRef:
  572. #if not isAllocatedPtr(gch.region, c):
  573. # c_printf("[GC] decref bug: %p", c)
  574. gcAssert(isAllocatedPtr(gch.region, c), "decRef: waZctDecRef")
  575. gcAssert(c.refcount >=% rcIncrement, "doOperation 2")
  576. logCell("decref (from doOperation)", c)
  577. track("waZctDecref", p, 0)
  578. decRef(c)
  579. of waPush:
  580. add(gch.tempStack, c)
  581. of waMarkGlobal:
  582. markS(gch, c)
  583. of waMarkPrecise:
  584. add(gch.tempStack, c)
  585. #of waDebug: debugGraph(c)
  586. proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} =
  587. doOperation(d, WalkOp(op))
  588. proc collectZCT(gch: var GcHeap): bool {.benign, raises: [].}
  589. proc collectCycles(gch: var GcHeap) {.raises: [].} =
  590. when hasThreadSupport:
  591. for c in gch.toDispose:
  592. nimGCunref(c)
  593. # ensure the ZCT 'color' is not used:
  594. while gch.zct.len > 0: discard collectZCT(gch)
  595. cellsetReset(gch.marked)
  596. var d = gch.decStack.d
  597. for i in 0..gch.decStack.len-1:
  598. sysAssert isAllocatedPtr(gch.region, d[i]), "collectCycles"
  599. markS(gch, d[i])
  600. markGlobals(gch)
  601. sweep(gch)
  602. proc gcMark(gch: var GcHeap, p: pointer) {.inline.} =
  603. # the addresses are not as cells on the stack, so turn them to cells:
  604. sysAssert(allocInv(gch.region), "gcMark begin")
  605. var c = cast[int](p)
  606. if c >% PageSize:
  607. # fast check: does it look like a cell?
  608. var objStart = cast[PCell](interiorAllocatedPtr(gch.region, p))
  609. if objStart != nil:
  610. # mark the cell:
  611. incRef(objStart)
  612. add(gch.decStack, objStart)
  613. when false:
  614. let cell = usrToCell(p)
  615. if isAllocatedPtr(gch.region, cell):
  616. sysAssert false, "allocated pointer but not interior?"
  617. # mark the cell:
  618. incRef(cell)
  619. add(gch.decStack, cell)
  620. sysAssert(allocInv(gch.region), "gcMark end")
  621. #[
  622. This method is conditionally marked with an attribute so that it gets ignored by the LLVM ASAN
  623. (Address SANitizer) intrumentation as it will raise false errors due to the implementation of
  624. garbage collection that is used by Nim. For more information, please see the documentation of
  625. `CLANG_NO_SANITIZE_ADDRESS` in `lib/nimbase.h`.
  626. ]#
  627. proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl,
  628. codegenDecl: "CLANG_NO_SANITIZE_ADDRESS N_LIB_PRIVATE $# $#$#".} =
  629. forEachStackSlot(gch, gcMark)
  630. proc collectZCT(gch: var GcHeap): bool =
  631. # Note: Freeing may add child objects to the ZCT! So essentially we do
  632. # deep freeing, which is bad for incremental operation. In order to
  633. # avoid a deep stack, we move objects to keep the ZCT small.
  634. # This is performance critical!
  635. const workPackage = 100
  636. var L = addr(gch.zct.len)
  637. when withRealTime:
  638. var steps = workPackage
  639. var t0: Ticks
  640. if gch.maxPause > 0: t0 = getticks()
  641. while L[] > 0:
  642. var c = gch.zct.d[0]
  643. sysAssert(isAllocatedPtr(gch.region, c), "CollectZCT: isAllocatedPtr")
  644. # remove from ZCT:
  645. gcAssert((c.refcount and ZctFlag) == ZctFlag, "collectZCT")
  646. c.refcount = c.refcount and not ZctFlag
  647. gch.zct.d[0] = gch.zct.d[L[] - 1]
  648. dec(L[])
  649. when withRealTime: dec steps
  650. if c.refcount <% rcIncrement:
  651. # It may have a RC > 0, if it is in the hardware stack or
  652. # it has not been removed yet from the ZCT. This is because
  653. # ``incref`` does not bother to remove the cell from the ZCT
  654. # as this might be too slow.
  655. # In any case, it should be removed from the ZCT. But not
  656. # freed. **KEEP THIS IN MIND WHEN MAKING THIS INCREMENTAL!**
  657. logCell("zct dealloc cell", c)
  658. track("zct dealloc cell", c, 0)
  659. gcTrace(c, csZctFreed)
  660. # We are about to free the object, call the finalizer BEFORE its
  661. # children are deleted as well, because otherwise the finalizer may
  662. # access invalid memory. This is done by prepareDealloc():
  663. prepareDealloc(c)
  664. forAllChildren(c, waZctDecRef)
  665. when reallyDealloc:
  666. sysAssert(allocInv(gch.region), "collectZCT: rawDealloc")
  667. beforeDealloc(gch, c, "collectZCT: stack trash")
  668. rawDealloc(gch.region, c)
  669. else:
  670. sysAssert(c.typ != nil, "collectZCT 2")
  671. zeroMem(c, sizeof(Cell))
  672. when withRealTime:
  673. if steps == 0:
  674. steps = workPackage
  675. if gch.maxPause > 0:
  676. let duration = getticks() - t0
  677. # the GC's measuring is not accurate and needs some cleanup actions
  678. # (stack unmarking), so subtract some short amount of time in
  679. # order to miss deadlines less often:
  680. if duration >= gch.maxPause - 50_000:
  681. return false
  682. result = true
  683. proc unmarkStackAndRegisters(gch: var GcHeap) =
  684. var d = gch.decStack.d
  685. for i in 0..gch.decStack.len-1:
  686. sysAssert isAllocatedPtr(gch.region, d[i]), "unmarkStackAndRegisters"
  687. decRef(d[i])
  688. gch.decStack.len = 0
  689. proc collectCTBody(gch: var GcHeap) {.raises: [].} =
  690. when withRealTime:
  691. let t0 = getticks()
  692. sysAssert(allocInv(gch.region), "collectCT: begin")
  693. when nimCoroutines:
  694. for stack in gch.stack.items():
  695. gch.stat.maxStackSize = max(gch.stat.maxStackSize, stack.stackSize())
  696. else:
  697. gch.stat.maxStackSize = max(gch.stat.maxStackSize, stackSize())
  698. sysAssert(gch.decStack.len == 0, "collectCT")
  699. prepareForInteriorPointerChecking(gch.region)
  700. markStackAndRegisters(gch)
  701. gch.stat.maxStackCells = max(gch.stat.maxStackCells, gch.decStack.len)
  702. inc(gch.stat.stackScans)
  703. if collectZCT(gch):
  704. when cycleGC:
  705. if getOccupiedMem(gch.region) >= gch.cycleThreshold or alwaysCycleGC:
  706. collectCycles(gch)
  707. #discard collectZCT(gch)
  708. inc(gch.stat.cycleCollections)
  709. gch.cycleThreshold = max(InitialCycleThreshold, getOccupiedMem() *
  710. CycleIncrease)
  711. gch.stat.maxThreshold = max(gch.stat.maxThreshold, gch.cycleThreshold)
  712. unmarkStackAndRegisters(gch)
  713. sysAssert(allocInv(gch.region), "collectCT: end")
  714. when withRealTime:
  715. let duration = getticks() - t0
  716. gch.stat.maxPause = max(gch.stat.maxPause, duration)
  717. when defined(reportMissedDeadlines):
  718. if gch.maxPause > 0 and duration > gch.maxPause:
  719. c_printf("[GC] missed deadline: %ld\n", duration)
  720. proc collectCT(gch: var GcHeap) =
  721. if (gch.zct.len >= gch.zctThreshold or (cycleGC and
  722. getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and
  723. gch.recGcLock == 0:
  724. when false:
  725. prepareForInteriorPointerChecking(gch.region)
  726. cellsetReset(gch.marked)
  727. markForDebug(gch)
  728. collectCTBody(gch)
  729. gch.zctThreshold = max(InitialZctThreshold, gch.zct.len * CycleIncrease)
  730. proc GC_collectZct*() =
  731. ## Collect the ZCT (zero count table). Unstable, experimental API for
  732. ## testing purposes.
  733. ## DO NOT USE!
  734. collectCTBody(gch)
  735. when withRealTime:
  736. proc toNano(x: int): Nanos {.inline.} =
  737. result = x * 1000
  738. proc GC_setMaxPause*(MaxPauseInUs: int) =
  739. gch.maxPause = MaxPauseInUs.toNano
  740. proc GC_step(gch: var GcHeap, us: int, strongAdvice: bool) =
  741. gch.maxPause = us.toNano
  742. if (gch.zct.len >= gch.zctThreshold or (cycleGC and
  743. getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) or
  744. strongAdvice:
  745. collectCTBody(gch)
  746. gch.zctThreshold = max(InitialZctThreshold, gch.zct.len * CycleIncrease)
  747. proc GC_step*(us: int, strongAdvice = false, stackSize = -1) {.noinline.} =
  748. if stackSize >= 0:
  749. var stackTop {.volatile.}: pointer
  750. gch.getActiveStack().pos = addr(stackTop)
  751. for stack in gch.stack.items():
  752. stack.bottomSaved = stack.bottom
  753. when stackIncreases:
  754. stack.bottom = cast[pointer](
  755. cast[int](stack.pos) - sizeof(pointer) * 6 - stackSize)
  756. else:
  757. stack.bottom = cast[pointer](
  758. cast[int](stack.pos) + sizeof(pointer) * 6 + stackSize)
  759. GC_step(gch, us, strongAdvice)
  760. if stackSize >= 0:
  761. for stack in gch.stack.items():
  762. stack.bottom = stack.bottomSaved
  763. when not defined(useNimRtl):
  764. proc GC_disable() =
  765. inc(gch.recGcLock)
  766. proc GC_enable() =
  767. when defined(nimDoesntTrackDefects):
  768. if gch.recGcLock <= 0:
  769. raise newException(AssertionDefect,
  770. "API usage error: GC_enable called but GC is already enabled")
  771. dec(gch.recGcLock)
  772. proc GC_setStrategy(strategy: GC_Strategy) =
  773. discard
  774. proc GC_enableMarkAndSweep() =
  775. gch.cycleThreshold = InitialCycleThreshold
  776. proc GC_disableMarkAndSweep() =
  777. gch.cycleThreshold = high(typeof(gch.cycleThreshold))-1
  778. # set to the max value to suppress the cycle detector
  779. proc GC_fullCollect() =
  780. var oldThreshold = gch.cycleThreshold
  781. gch.cycleThreshold = 0 # forces cycle collection
  782. collectCT(gch)
  783. gch.cycleThreshold = oldThreshold
  784. proc GC_getStatistics(): string =
  785. result = "[GC] total memory: " & $(getTotalMem()) & "\n" &
  786. "[GC] occupied memory: " & $(getOccupiedMem()) & "\n" &
  787. "[GC] stack scans: " & $gch.stat.stackScans & "\n" &
  788. "[GC] stack cells: " & $gch.stat.maxStackCells & "\n" &
  789. "[GC] cycle collections: " & $gch.stat.cycleCollections & "\n" &
  790. "[GC] max threshold: " & $gch.stat.maxThreshold & "\n" &
  791. "[GC] zct capacity: " & $gch.zct.cap & "\n" &
  792. "[GC] max cycle table size: " & $gch.stat.cycleTableSize & "\n" &
  793. "[GC] max pause time [ms]: " & $(gch.stat.maxPause div 1000_000) & "\n"
  794. when nimCoroutines:
  795. result.add "[GC] number of stacks: " & $gch.stack.len & "\n"
  796. for stack in items(gch.stack):
  797. result.add "[GC] stack " & stack.bottom.repr & "[GC] max stack size " & cast[pointer](stack.maxStackSize).repr & "\n"
  798. else:
  799. # this caused memory leaks, see #10488 ; find a way without `repr`
  800. # maybe using a local copy of strutils.toHex or snprintf
  801. when defined(logGC):
  802. result.add "[GC] stack bottom: " & gch.stack.bottom.repr
  803. result.add "[GC] max stack size: " & $gch.stat.maxStackSize & "\n"
  804. {.pop.} # profiler: off, stackTrace: off