gc.lua 17 KB

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