gc.lua 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. -- $Id: testes/gc.lua $
  2. -- See Copyright Notice in file all.lua
  3. print('testing incremental garbage collection')
  4. local debug = require"debug"
  5. assert(collectgarbage("isrunning"))
  6. collectgarbage()
  7. local oldmode = collectgarbage("incremental")
  8. -- changing modes should return previous mode
  9. assert(collectgarbage("generational") == "incremental")
  10. assert(collectgarbage("generational") == "generational")
  11. assert(collectgarbage("incremental") == "generational")
  12. assert(collectgarbage("incremental") == "incremental")
  13. local function gcinfo ()
  14. return collectgarbage"count" * 1024
  15. end
  16. -- test weird parameters to 'collectgarbage'
  17. do
  18. -- save original parameters
  19. local a = collectgarbage("setpause", 200)
  20. local b = collectgarbage("setstepmul", 200)
  21. local t = {0, 2, 10, 90, 500, 5000, 30000, 0x7ffffffe}
  22. for i = 1, #t do
  23. local p = t[i]
  24. for j = 1, #t do
  25. local m = t[j]
  26. collectgarbage("setpause", p)
  27. collectgarbage("setstepmul", m)
  28. collectgarbage("step", 0)
  29. collectgarbage("step", 10000)
  30. end
  31. end
  32. -- restore original parameters
  33. collectgarbage("setpause", a)
  34. collectgarbage("setstepmul", b)
  35. collectgarbage()
  36. end
  37. _G["while"] = 234
  38. --
  39. -- tests for GC activation when creating different kinds of objects
  40. --
  41. local function GC1 ()
  42. local u
  43. local b -- (above 'u' it in the stack)
  44. local finish = false
  45. u = setmetatable({}, {__gc = function () finish = true end})
  46. b = {34}
  47. repeat u = {} until finish
  48. assert(b[1] == 34) -- 'u' was collected, but 'b' was not
  49. finish = false; local i = 1
  50. u = setmetatable({}, {__gc = function () finish = true end})
  51. repeat i = i + 1; u = tostring(i) .. tostring(i) until finish
  52. assert(b[1] == 34) -- 'u' was collected, but 'b' was not
  53. finish = false
  54. u = setmetatable({}, {__gc = function () finish = true end})
  55. repeat local i; u = function () return i end until finish
  56. assert(b[1] == 34) -- 'u' was collected, but 'b' was not
  57. end
  58. local function GC2 ()
  59. local u
  60. local finish = false
  61. u = {setmetatable({}, {__gc = function () finish = true end})}
  62. local b = {34}
  63. repeat u = {{}} until finish
  64. assert(b[1] == 34) -- 'u' was collected, but 'b' was not
  65. finish = false; local i = 1
  66. u = {setmetatable({}, {__gc = function () finish = true end})}
  67. repeat i = i + 1; u = {tostring(i) .. tostring(i)} until finish
  68. assert(b[1] == 34) -- 'u' was collected, but 'b' was not
  69. finish = false
  70. u = {setmetatable({}, {__gc = function () finish = true end})}
  71. repeat local i; u = {function () return i end} until finish
  72. assert(b[1] == 34) -- 'u' was collected, but 'b' was not
  73. end
  74. local function GC() GC1(); GC2() end
  75. do
  76. print("creating many objects")
  77. local contCreate = 0
  78. local limit = 5000
  79. while contCreate <= limit do
  80. local a = {}; a = nil
  81. contCreate = contCreate+1
  82. end
  83. local a = "a"
  84. contCreate = 0
  85. while contCreate <= limit do
  86. a = contCreate .. "b";
  87. a = string.gsub(a, '(%d%d*)', string.upper)
  88. a = "a"
  89. contCreate = contCreate+1
  90. end
  91. contCreate = 0
  92. a = {}
  93. function a:test ()
  94. while contCreate <= limit do
  95. load(string.format("function temp(a) return 'a%d' end", contCreate), "")()
  96. assert(temp() == string.format('a%d', contCreate))
  97. contCreate = contCreate+1
  98. end
  99. end
  100. a:test()
  101. end
  102. -- collection of functions without locals, globals, etc.
  103. do local f = function () end end
  104. print("functions with errors")
  105. prog = [[
  106. do
  107. a = 10;
  108. function foo(x,y)
  109. a = sin(a+0.456-0.23e-12);
  110. return function (z) return sin(%x+z) end
  111. end
  112. local x = function (w) a=a+w; end
  113. end
  114. ]]
  115. do
  116. local step = 1
  117. if _soft then step = 13 end
  118. for i=1, string.len(prog), step do
  119. for j=i, string.len(prog), step do
  120. pcall(load(string.sub(prog, i, j), ""))
  121. end
  122. end
  123. end
  124. foo = nil
  125. print('long strings')
  126. x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
  127. assert(string.len(x)==80)
  128. s = ''
  129. n = 0
  130. k = math.min(300, (math.maxinteger // 80) // 2)
  131. while n < k do s = s..x; n=n+1; j=tostring(n) end
  132. assert(string.len(s) == k*80)
  133. s = string.sub(s, 1, 10000)
  134. s, i = string.gsub(s, '(%d%d%d%d)', '')
  135. assert(i==10000 // 4)
  136. s = nil
  137. x = nil
  138. assert(_G["while"] == 234)
  139. --
  140. -- test the "size" of basic GC steps (whatever they mean...)
  141. --
  142. do
  143. print("steps")
  144. print("steps (2)")
  145. local function dosteps (siz)
  146. collectgarbage()
  147. local a = {}
  148. for i=1,100 do a[i] = {{}}; local b = {} end
  149. local x = gcinfo()
  150. local i = 0
  151. repeat -- do steps until it completes a collection cycle
  152. i = i+1
  153. until collectgarbage("step", siz)
  154. assert(gcinfo() < x)
  155. return i -- number of steps
  156. end
  157. collectgarbage"stop"
  158. if not _port then
  159. assert(dosteps(10) < dosteps(2))
  160. end
  161. -- collector should do a full collection with so many steps
  162. assert(dosteps(20000) == 1)
  163. assert(collectgarbage("step", 20000) == true)
  164. assert(collectgarbage("step", 20000) == true)
  165. assert(not collectgarbage("isrunning"))
  166. collectgarbage"restart"
  167. assert(collectgarbage("isrunning"))
  168. end
  169. if not _port then
  170. -- test the pace of the collector
  171. collectgarbage(); collectgarbage()
  172. local x = gcinfo()
  173. collectgarbage"stop"
  174. repeat
  175. local a = {}
  176. until gcinfo() > 3 * x
  177. collectgarbage"restart"
  178. assert(collectgarbage("isrunning"))
  179. repeat
  180. local a = {}
  181. until gcinfo() <= x * 2
  182. end
  183. print("clearing tables")
  184. lim = 15
  185. a = {}
  186. -- fill a with `collectable' indices
  187. for i=1,lim do a[{}] = i end
  188. b = {}
  189. for k,v in pairs(a) do b[k]=v end
  190. -- remove all indices and collect them
  191. for n in pairs(b) do
  192. a[n] = undef
  193. assert(type(n) == 'table' and next(n) == nil)
  194. collectgarbage()
  195. end
  196. b = nil
  197. collectgarbage()
  198. for n in pairs(a) do error'cannot be here' end
  199. for i=1,lim do a[i] = i end
  200. for i=1,lim do assert(a[i] == i) end
  201. print('weak tables')
  202. a = {}; setmetatable(a, {__mode = 'k'});
  203. -- fill a with some `collectable' indices
  204. for i=1,lim do a[{}] = i end
  205. -- and some non-collectable ones
  206. for i=1,lim do a[i] = i end
  207. for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end
  208. collectgarbage()
  209. local i = 0
  210. for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end
  211. assert(i == 2*lim)
  212. a = {}; setmetatable(a, {__mode = 'v'});
  213. a[1] = string.rep('b', 21)
  214. collectgarbage()
  215. assert(a[1]) -- strings are *values*
  216. a[1] = undef
  217. -- fill a with some `collectable' values (in both parts of the table)
  218. for i=1,lim do a[i] = {} end
  219. for i=1,lim do a[i..'x'] = {} end
  220. -- and some non-collectable ones
  221. for i=1,lim do local t={}; a[t]=t end
  222. for i=1,lim do a[i+lim]=i..'x' end
  223. collectgarbage()
  224. local i = 0
  225. for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end
  226. assert(i == 2*lim)
  227. a = {}; setmetatable(a, {__mode = 'kv'});
  228. local x, y, z = {}, {}, {}
  229. -- keep only some items
  230. a[1], a[2], a[3] = x, y, z
  231. a[string.rep('$', 11)] = string.rep('$', 11)
  232. -- fill a with some `collectable' values
  233. for i=4,lim do a[i] = {} end
  234. for i=1,lim do a[{}] = i end
  235. for i=1,lim do local t={}; a[t]=t end
  236. collectgarbage()
  237. assert(next(a) ~= nil)
  238. local i = 0
  239. for k,v in pairs(a) do
  240. assert((k == 1 and v == x) or
  241. (k == 2 and v == y) or
  242. (k == 3 and v == z) or k==v);
  243. i = i+1
  244. end
  245. assert(i == 4)
  246. x,y,z=nil
  247. collectgarbage()
  248. assert(next(a) == string.rep('$', 11))
  249. -- 'bug' in 5.1
  250. a = {}
  251. local t = {x = 10}
  252. local C = setmetatable({key = t}, {__mode = 'v'})
  253. local C1 = setmetatable({[t] = 1}, {__mode = 'k'})
  254. a.x = t -- this should not prevent 't' from being removed from
  255. -- weak table 'C' by the time 'a' is finalized
  256. setmetatable(a, {__gc = function (u)
  257. assert(C.key == nil)
  258. assert(type(next(C1)) == 'table')
  259. end})
  260. a, t = nil
  261. collectgarbage()
  262. collectgarbage()
  263. assert(next(C) == nil and next(C1) == nil)
  264. C, C1 = nil
  265. -- ephemerons
  266. local mt = {__mode = 'k'}
  267. a = {{10},{20},{30},{40}}; setmetatable(a, mt)
  268. x = nil
  269. for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end
  270. GC()
  271. local n = x
  272. local i = 0
  273. while n do n = a[n].k[1]; i = i + 1 end
  274. assert(i == 100)
  275. x = nil
  276. GC()
  277. for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = undef end
  278. assert(next(a) == nil)
  279. local K = {}
  280. a[K] = {}
  281. for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end
  282. x = nil
  283. local k = 1
  284. for j = 1,100 do
  285. local n = {}; local nk = k%10 + 1
  286. a[a[K][nk]][n] = {x, k = k}; x = n; k = nk
  287. end
  288. GC()
  289. local n = x
  290. local i = 0
  291. while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end
  292. assert(i == 100)
  293. K = nil
  294. GC()
  295. -- assert(next(a) == nil)
  296. -- testing errors during GC
  297. if T then
  298. collectgarbage("stop") -- stop collection
  299. local u = {}
  300. local s = {}; setmetatable(s, {__mode = 'k'})
  301. setmetatable(u, {__gc = function (o)
  302. local i = s[o]
  303. s[i] = true
  304. assert(not s[i - 1]) -- check proper finalization order
  305. if i == 8 then error("@expected@") end -- error during GC
  306. end})
  307. for i = 6, 10 do
  308. local n = setmetatable({}, getmetatable(u))
  309. s[n] = i
  310. end
  311. collectgarbage()
  312. assert(string.find(_WARN, "error in __gc metamethod"))
  313. assert(string.match(_WARN, "@(.-)@") == "expected")
  314. for i = 8, 10 do assert(s[i]) end
  315. for i = 1, 5 do
  316. local n = setmetatable({}, getmetatable(u))
  317. s[n] = i
  318. end
  319. collectgarbage()
  320. for i = 1, 10 do assert(s[i]) end
  321. getmetatable(u).__gc = false
  322. end
  323. print '+'
  324. -- testing userdata
  325. if T==nil then
  326. (Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n')
  327. else
  328. local function newproxy(u)
  329. return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u))
  330. end
  331. collectgarbage("stop") -- stop collection
  332. local u = newproxy(nil)
  333. debug.setmetatable(u, {__gc = true})
  334. local s = 0
  335. local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'})
  336. for i=1,10 do a[newproxy(u)] = i end
  337. for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end
  338. local a1 = {}; for k,v in pairs(a) do a1[k] = v end
  339. for k,v in pairs(a1) do a[v] = k end
  340. for i =1,10 do assert(a[i]) end
  341. getmetatable(u).a = a1
  342. getmetatable(u).u = u
  343. do
  344. local u = u
  345. getmetatable(u).__gc = function (o)
  346. assert(a[o] == 10-s)
  347. assert(a[10-s] == undef) -- udata already removed from weak table
  348. assert(getmetatable(o) == getmetatable(u))
  349. assert(getmetatable(o).a[o] == 10-s)
  350. s=s+1
  351. end
  352. end
  353. a1, u = nil
  354. assert(next(a) ~= nil)
  355. collectgarbage()
  356. assert(s==11)
  357. collectgarbage()
  358. assert(next(a) == nil) -- finalized keys are removed in two cycles
  359. end
  360. -- __gc x weak tables
  361. local u = setmetatable({}, {__gc = true})
  362. -- __gc metamethod should be collected before running
  363. setmetatable(getmetatable(u), {__mode = "v"})
  364. getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen
  365. u = nil
  366. collectgarbage()
  367. local u = setmetatable({}, {__gc = true})
  368. local m = getmetatable(u)
  369. m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"});
  370. m.__gc = function (o)
  371. assert(next(getmetatable(o).x) == nil)
  372. m = 10
  373. end
  374. u, m = nil
  375. collectgarbage()
  376. assert(m==10)
  377. do -- tests for string keys in weak tables
  378. collectgarbage(); collectgarbage()
  379. local m = collectgarbage("count") -- current memory
  380. local a = setmetatable({}, {__mode = "kv"})
  381. a[string.rep("a", 2^22)] = 25 -- long string key -> number value
  382. a[string.rep("b", 2^22)] = {} -- long string key -> colectable value
  383. a[{}] = 14 -- colectable key
  384. assert(collectgarbage("count") > m + 2^13) -- 2^13 == 2 * 2^22 in KB
  385. collectgarbage()
  386. assert(collectgarbage("count") >= m + 2^12 and
  387. collectgarbage("count") < m + 2^13) -- one key was collected
  388. local k, v = next(a) -- string key with number value preserved
  389. assert(k == string.rep("a", 2^22) and v == 25)
  390. assert(next(a, k) == nil) -- everything else cleared
  391. assert(a[string.rep("b", 2^22)] == undef)
  392. a[k] = undef -- erase this last entry
  393. k = nil
  394. collectgarbage()
  395. assert(next(a) == nil)
  396. -- make sure will not try to compare with dead key
  397. assert(a[string.rep("b", 100)] == undef)
  398. assert(collectgarbage("count") <= m + 1) -- eveything collected
  399. end
  400. -- errors during collection
  401. if T then
  402. u = setmetatable({}, {__gc = function () error "@expected error" end})
  403. u = nil
  404. collectgarbage()
  405. end
  406. if not _soft then
  407. print("long list")
  408. local a = {}
  409. for i = 1,200000 do
  410. a = {next = a}
  411. end
  412. a = nil
  413. collectgarbage()
  414. end
  415. -- create many threads with self-references and open upvalues
  416. print("self-referenced threads")
  417. local thread_id = 0
  418. local threads = {}
  419. local function fn (thread)
  420. local x = {}
  421. threads[thread_id] = function()
  422. thread = x
  423. end
  424. coroutine.yield()
  425. end
  426. while thread_id < 1000 do
  427. local thread = coroutine.create(fn)
  428. coroutine.resume(thread, thread)
  429. thread_id = thread_id + 1
  430. end
  431. -- Create a closure (function inside 'f') with an upvalue ('param') that
  432. -- points (through a table) to the closure itself and to the thread
  433. -- ('co' and the initial value of 'param') where closure is running.
  434. -- Then, assert that table (and therefore everything else) will be
  435. -- collected.
  436. do
  437. local collected = false -- to detect collection
  438. collectgarbage(); collectgarbage("stop")
  439. do
  440. local function f (param)
  441. ;(function ()
  442. assert(type(f) == 'function' and type(param) == 'thread')
  443. param = {param, f}
  444. setmetatable(param, {__gc = function () collected = true end})
  445. coroutine.yield(100)
  446. end)()
  447. end
  448. local co = coroutine.create(f)
  449. assert(coroutine.resume(co, co))
  450. end
  451. -- Now, thread and closure are not reacheable any more.
  452. collectgarbage()
  453. assert(collected)
  454. collectgarbage("restart")
  455. end
  456. do
  457. collectgarbage()
  458. collectgarbage"stop"
  459. collectgarbage("step", 0) -- steps should not unblock the collector
  460. local x = gcinfo()
  461. repeat
  462. for i=1,1000 do _ENV.a = {} end -- no collection during the loop
  463. until gcinfo() > 2 * x
  464. collectgarbage"restart"
  465. end
  466. if T then -- tests for weird cases collecting upvalues
  467. local function foo ()
  468. local a = {x = 20}
  469. coroutine.yield(function () return a.x end) -- will run collector
  470. assert(a.x == 20) -- 'a' is 'ok'
  471. a = {x = 30} -- create a new object
  472. assert(T.gccolor(a) == "white") -- of course it is new...
  473. coroutine.yield(100) -- 'a' is still local to this thread
  474. end
  475. local t = setmetatable({}, {__mode = "kv"})
  476. collectgarbage(); collectgarbage('stop')
  477. -- create coroutine in a weak table, so it will never be marked
  478. t.co = coroutine.wrap(foo)
  479. local f = t.co() -- create function to access local 'a'
  480. T.gcstate("atomic") -- ensure all objects are traversed
  481. assert(T.gcstate() == "atomic")
  482. assert(t.co() == 100) -- resume coroutine, creating new table for 'a'
  483. assert(T.gccolor(t.co) == "white") -- thread was not traversed
  484. T.gcstate("pause") -- collect thread, but should mark 'a' before that
  485. assert(t.co == nil and f() == 30) -- ensure correct access to 'a'
  486. collectgarbage("restart")
  487. -- test barrier in sweep phase (backing userdata to gray)
  488. local u = T.newuserdata(0, 1) -- create a userdata
  489. collectgarbage()
  490. collectgarbage"stop"
  491. local a = {} -- avoid 'u' as first element in 'allgc'
  492. T.gcstate"atomic"
  493. T.gcstate"sweepallgc"
  494. local x = {}
  495. assert(T.gccolor(u) == "black") -- userdata is "old" (black)
  496. assert(T.gccolor(x) == "white") -- table is "new" (white)
  497. debug.setuservalue(u, x) -- trigger barrier
  498. assert(T.gccolor(u) == "gray") -- userdata changed back to gray
  499. collectgarbage"restart"
  500. print"+"
  501. end
  502. if T then
  503. local debug = require "debug"
  504. collectgarbage("stop")
  505. local x = T.newuserdata(0)
  506. local y = T.newuserdata(0)
  507. debug.setmetatable(y, {__gc = true}) -- bless the new udata before...
  508. debug.setmetatable(x, {__gc = true}) -- ...the old one
  509. assert(T.gccolor(y) == "white")
  510. T.checkmemory()
  511. collectgarbage("restart")
  512. end
  513. if T then
  514. print("emergency collections")
  515. collectgarbage()
  516. collectgarbage()
  517. T.totalmem(T.totalmem() + 200)
  518. for i=1,200 do local a = {} end
  519. T.totalmem(0)
  520. collectgarbage()
  521. local t = T.totalmem("table")
  522. local a = {{}, {}, {}} -- create 4 new tables
  523. assert(T.totalmem("table") == t + 4)
  524. t = T.totalmem("function")
  525. a = function () end -- create 1 new closure
  526. assert(T.totalmem("function") == t + 1)
  527. t = T.totalmem("thread")
  528. a = coroutine.create(function () end) -- create 1 new coroutine
  529. assert(T.totalmem("thread") == t + 1)
  530. end
  531. -- create an object to be collected when state is closed
  532. do
  533. local setmetatable,assert,type,print,getmetatable =
  534. setmetatable,assert,type,print,getmetatable
  535. local tt = {}
  536. tt.__gc = function (o)
  537. assert(getmetatable(o) == tt)
  538. -- create new objects during GC
  539. local a = 'xuxu'..(10+3)..'joao', {}
  540. ___Glob = o -- ressurect object!
  541. setmetatable({}, tt) -- creates a new one with same metatable
  542. print(">>> closing state " .. "<<<\n")
  543. end
  544. local u = setmetatable({}, tt)
  545. ___Glob = {u} -- avoid object being collected before program end
  546. end
  547. -- create several objects to raise errors when collected while closing state
  548. if T then
  549. local error, assert, warn, find = error, assert, warn, string.find
  550. local n = 0
  551. local lastmsg
  552. local mt = {__gc = function (o)
  553. n = n + 1
  554. assert(n == o[1])
  555. if n == 1 then
  556. _WARN = nil
  557. elseif n == 2 then
  558. assert(find(_WARN, "@expected warning"))
  559. lastmsg = _WARN -- get message from previous error (first 'o')
  560. else
  561. assert(lastmsg == _WARN) -- subsequent error messages are equal
  562. end
  563. error"@expected warning"
  564. end}
  565. for i = 10, 1, -1 do
  566. -- create object and preserve it until the end
  567. table.insert(___Glob, setmetatable({i}, mt))
  568. end
  569. end
  570. -- just to make sure
  571. assert(collectgarbage'isrunning')
  572. collectgarbage(oldmode)
  573. print('OK')