gc.lua 17 KB

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