interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / testes / gc.lua

752 lines · 19650 bytes Raw Blame History
1-- $Id: testes/gc.lua $
2-- See Copyright Notice in file lua.h
3
4print('testing incremental garbage collection')
5
6local debug = require"debug"
7
8assert(collectgarbage("isrunning"))
9
10collectgarbage()
11
12local oldmode = collectgarbage("incremental")
13
14-- changing modes should return previous mode
15assert(collectgarbage("generational") == "incremental")
16assert(collectgarbage("generational") == "generational")
17assert(collectgarbage("incremental") == "generational")
18assert(collectgarbage("incremental") == "incremental")
19
20
21local function nop () end
22
23local function gcinfo ()
24 return collectgarbage"count" * 1024
25end
26
27
28-- test weird parameters to 'collectgarbage'
29do
30 collectgarbage("incremental")
31 local opause = collectgarbage("param", "pause", 100)
32 local ostepmul = collectgarbage("param", "stepmul", 100)
33 assert(collectgarbage("param", "pause") == 100)
34 assert(collectgarbage("param", "stepmul") == 100)
35 local t = {0, 2, 10, 90, 500, 5000, 30000, 0x7ffffffe}
36 for i = 1, #t do
37 collectgarbage("param", "pause", t[i])
38 for j = 1, #t do
39 collectgarbage("param", "stepmul", t[j])
40 collectgarbage("step", t[j])
41 end
42 end
43 -- restore original parameters
44 collectgarbage("param", "pause", opause)
45 collectgarbage("param", "stepmul", ostepmul)
46 collectgarbage()
47end
48
49
50--
51-- test the "size" of basic GC steps (whatever they mean...)
52--
53do print("steps")
54
55 local function dosteps (siz)
56 collectgarbage()
57 local a = {}
58 for i=1,100 do a[i] = {{}}; local b = {} end
59 local x = gcinfo()
60 local i = 0
61 repeat -- do steps until it completes a collection cycle
62 i = i+1
63 until collectgarbage("step", siz)
64 assert(gcinfo() < x)
65 return i -- number of steps
66 end
67
68
69 if not _port then
70 collectgarbage"stop"
71 assert(dosteps(10) < dosteps(2))
72 collectgarbage"restart"
73 end
74
75end
76
77
78_G["while"] = 234
79
80
81--
82-- tests for GC activation when creating different kinds of objects
83--
84local function GC1 ()
85 local u
86 local b -- (above 'u' it in the stack)
87 local finish = false
88 u = setmetatable({}, {__gc = function () finish = true end})
89 b = {34}
90 repeat u = {} until finish
91 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
92
93 finish = false; local i = 1
94 u = setmetatable({}, {__gc = function () finish = true end})
95 repeat i = i + 1; u = tostring(i) .. tostring(i) until finish
96 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
97
98 finish = false
99 u = setmetatable({}, {__gc = function () finish = true end})
100 repeat local i; u = function () return i end until finish
101 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
102end
103
104local function GC2 ()
105 local u
106 local finish = false
107 u = {setmetatable({}, {__gc = function () finish = true end})}
108 local b = {34}
109 repeat u = {{}} until finish
110 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
111
112 finish = false; local i = 1
113 u = {setmetatable({}, {__gc = function () finish = true end})}
114 repeat i = i + 1; u = {tostring(i) .. tostring(i)} until finish
115 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
116
117 finish = false
118 u = {setmetatable({}, {__gc = function () finish = true end})}
119 repeat local i; u = {function () return i end} until finish
120 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
121end
122
123local function GC() GC1(); GC2() end
124
125
126do
127 print("creating many objects")
128
129 local limit = 5000
130
131 for i = 1, limit do
132 local a = {}; a = nil
133 end
134
135 local a = "a"
136
137 for i = 1, limit do
138 a = i .. "b";
139 a = string.gsub(a, '(%d%d*)', "%1 %1")
140 a = "a"
141 end
142
143
144
145 a = {}
146
147 function a:test ()
148 for i = 1, limit do
149 load(string.format("function temp(a) return 'a%d' end", i), "")()
150 assert(temp() == string.format('a%d', i))
151 end
152 end
153
154 a:test()
155 _G.temp = nil
156end
157
158
159-- collection of functions without locals, globals, etc.
160do local f = function () end end
161
162
163print("functions with errors")
164local prog = [[
165do
166 a = 10;
167 function foo(x,y)
168 a = sin(a+0.456-0.23e-12);
169 return function (z) return sin(%x+z) end
170 end
171 local x = function (w) a=a+w; end
172end
173]]
174do
175 local step = 1
176 if _soft then step = 13 end
177 for i=1, string.len(prog), step do
178 for j=i, string.len(prog), step do
179 pcall(load(string.sub(prog, i, j), ""))
180 end
181 end
182end
183rawset(_G, "a", nil)
184_G.x = nil
185
186do
187 foo = nil
188 print('long strings')
189 local x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
190 assert(string.len(x)==80)
191 local s = ''
192 local k = math.min(300, (math.maxinteger // 80) // 2)
193 for n = 1, k do s = s..x; local j=tostring(n) end
194 assert(string.len(s) == k*80)
195 s = string.sub(s, 1, 10000)
196 local s, i = string.gsub(s, '(%d%d%d%d)', '')
197 assert(i==10000 // 4)
198
199 assert(_G["while"] == 234)
200 _G["while"] = nil
201end
202
203
204if not _port then
205 -- test the pace of the collector
206 collectgarbage(); collectgarbage()
207 local x = gcinfo()
208 collectgarbage"stop"
209 repeat
210 local a = {}
211 until gcinfo() > 3 * x
212 collectgarbage"restart"
213 assert(collectgarbage("isrunning"))
214 repeat
215 local a = {}
216 until gcinfo() <= x * 2
217end
218
219
220print("clearing tables")
221local lim = 15
222local a = {}
223-- fill a with `collectable' indices
224for i=1,lim do a[{}] = i end
225b = {}
226for k,v in pairs(a) do b[k]=v end
227-- remove all indices and collect them
228for n in pairs(b) do
229 a[n] = undef
230 assert(type(n) == 'table' and next(n) == nil)
231 collectgarbage()
232end
233b = nil
234collectgarbage()
235for n in pairs(a) do error'cannot be here' end
236for i=1,lim do a[i] = i end
237for i=1,lim do assert(a[i] == i) end
238
239
240print('weak tables')
241a = {}; setmetatable(a, {__mode = 'k'});
242-- fill a with some `collectable' indices
243for i=1,lim do a[{}] = i end
244-- and some non-collectable ones
245for i=1,lim do a[i] = i end
246for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end
247collectgarbage()
248local i = 0
249for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end
250assert(i == 2*lim)
251
252a = {}; setmetatable(a, {__mode = 'v'});
253a[1] = string.rep('b', 21)
254collectgarbage()
255assert(a[1]) -- strings are *values*
256a[1] = undef
257-- fill a with some `collectable' values (in both parts of the table)
258for i=1,lim do a[i] = {} end
259for i=1,lim do a[i..'x'] = {} end
260-- and some non-collectable ones
261for i=1,lim do local t={}; a[t]=t end
262for i=1,lim do a[i+lim]=i..'x' end
263collectgarbage()
264local i = 0
265for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end
266assert(i == 2*lim)
267
268a = {}; setmetatable(a, {__mode = 'kv'});
269local x, y, z = {}, {}, {}
270-- keep only some items
271a[1], a[2], a[3] = x, y, z
272a[string.rep('$', 11)] = string.rep('$', 11)
273-- fill a with some `collectable' values
274for i=4,lim do a[i] = {} end
275for i=1,lim do a[{}] = i end
276for i=1,lim do local t={}; a[t]=t end
277collectgarbage()
278assert(next(a) ~= nil)
279local i = 0
280for k,v in pairs(a) do
281 assert((k == 1 and v == x) or
282 (k == 2 and v == y) or
283 (k == 3 and v == z) or k==v);
284 i = i+1
285end
286assert(i == 4)
287x,y,z=nil
288collectgarbage()
289assert(next(a) == string.rep('$', 11))
290
291do -- invalid mode
292 local a = setmetatable({}, {__mode = 34})
293 collectgarbage()
294end
295
296
297if T then -- bug since 5.3: all-weak tables are not being revisited
298 T.gcstate("propagate")
299 local t = setmetatable({}, {__mode = "kv"})
300 T.gcstate("enteratomic") -- 't' was visited
301 setmetatable(t, {__mode = "kv"})
302 T.gcstate("pause") -- its new metatable is not being visited
303 assert(getmetatable(t).__mode == "kv")
304end
305
306
307-- 'bug' in 5.1
308a = {}
309local t = {x = 10}
310local C = setmetatable({key = t}, {__mode = 'v'})
311local C1 = setmetatable({[t] = 1}, {__mode = 'k'})
312a.x = t -- this should not prevent 't' from being removed from
313 -- weak table 'C' by the time 'a' is finalized
314
315setmetatable(a, {__gc = function (u)
316 assert(C.key == nil)
317 assert(type(next(C1)) == 'table')
318 end})
319
320a, t = nil
321collectgarbage()
322collectgarbage()
323assert(next(C) == nil and next(C1) == nil)
324C, C1 = nil
325
326
327-- ephemerons
328local mt = {__mode = 'k'}
329a = {{10},{20},{30},{40}}; setmetatable(a, mt)
330x = nil
331for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end
332GC()
333local n = x
334local i = 0
335while n do n = a[n].k[1]; i = i + 1 end
336assert(i == 100)
337x = nil
338GC()
339for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = undef end
340assert(next(a) == nil)
341
342local K = {}
343a[K] = {}
344for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end
345x = nil
346local k = 1
347for j = 1,100 do
348 local n = {}; local nk = k%10 + 1
349 a[a[K][nk]][n] = {x, k = k}; x = n; k = nk
350end
351GC()
352local n = x
353local i = 0
354while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end
355assert(i == 100)
356K = nil
357GC()
358-- assert(next(a) == nil)
359
360
361-- testing errors during GC
362if T then
363 collectgarbage("stop") -- stop collection
364 local u = {}
365 local s = {}; setmetatable(s, {__mode = 'k'})
366 setmetatable(u, {__gc = function (o)
367 local i = s[o]
368 s[i] = true
369 assert(not s[i - 1]) -- check proper finalization order
370 if i == 8 then error("@expected@") end -- error during GC
371 end})
372
373 for i = 6, 10 do
374 local n = setmetatable({}, getmetatable(u))
375 s[n] = i
376 end
377
378 warn("@on"); warn("@store")
379 collectgarbage()
380 assert(string.find(_WARN, "error in __gc"))
381 assert(string.match(_WARN, "@(.-)@") == "expected"); _WARN = false
382 for i = 8, 10 do assert(s[i]) end
383
384 for i = 1, 5 do
385 local n = setmetatable({}, getmetatable(u))
386 s[n] = i
387 end
388
389 collectgarbage()
390 for i = 1, 10 do assert(s[i]) end
391
392 getmetatable(u).__gc = nil
393 warn("@normal")
394
395end
396print '+'
397
398
399-- testing userdata
400if T==nil then
401 (Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n')
402
403else
404
405 local function newproxy(u)
406 return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u))
407 end
408
409 collectgarbage("stop") -- stop collection
410 local u = newproxy(nil)
411 debug.setmetatable(u, {__gc = true})
412 local s = 0
413 local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'})
414 for i=1,10 do a[newproxy(u)] = i end
415 for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end
416 local a1 = {}; for k,v in pairs(a) do a1[k] = v end
417 for k,v in pairs(a1) do a[v] = k end
418 for i =1,10 do assert(a[i]) end
419 getmetatable(u).a = a1
420 getmetatable(u).u = u
421 do
422 local u = u
423 getmetatable(u).__gc = function (o)
424 assert(a[o] == 10-s)
425 assert(a[10-s] == undef) -- udata already removed from weak table
426 assert(getmetatable(o) == getmetatable(u))
427 assert(getmetatable(o).a[o] == 10-s)
428 s=s+1
429 end
430 end
431 a1, u = nil
432 assert(next(a) ~= nil)
433 collectgarbage()
434 assert(s==11)
435 collectgarbage()
436 assert(next(a) == nil) -- finalized keys are removed in two cycles
437end
438
439
440-- __gc x weak tables
441local u = setmetatable({}, {__gc = true})
442-- __gc metamethod should be collected before running
443setmetatable(getmetatable(u), {__mode = "v"})
444getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen
445u = nil
446collectgarbage()
447
448local u = setmetatable({}, {__gc = true})
449local m = getmetatable(u)
450m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"});
451m.__gc = function (o)
452 assert(next(getmetatable(o).x) == nil)
453 m = 10
454end
455u, m = nil
456collectgarbage()
457assert(m==10)
458
459do -- tests for string keys in weak tables
460 collectgarbage(); collectgarbage()
461 local m = collectgarbage("count") -- current memory
462 local a = setmetatable({}, {__mode = "kv"})
463 a[string.rep("a", 2^22)] = 25 -- long string key -> number value
464 a[string.rep("b", 2^22)] = {} -- long string key -> collectable value
465 a[{}] = 14 -- collectable key
466 collectgarbage()
467 local k, v = next(a) -- string key with number value preserved
468 assert(k == string.rep("a", 2^22) and v == 25)
469 assert(next(a, k) == nil) -- everything else cleared
470 assert(a[string.rep("b", 2^22)] == undef)
471 a[k] = undef -- erase this last entry
472 k = nil
473 collectgarbage()
474 assert(next(a) == nil)
475 -- make sure will not try to compare with dead key
476 assert(a[string.rep("b", 100)] == undef)
477 assert(collectgarbage("count") <= m + 1) -- everything collected
478end
479
480
481-- errors during collection
482if T then
483 warn("@store")
484 u = setmetatable({}, {__gc = function () error "@expected error" end})
485 u = nil
486 collectgarbage()
487 assert(string.find(_WARN, "@expected error")); _WARN = false
488 warn("@normal")
489end
490
491
492if not _soft then
493 print("long list")
494 local a = {}
495 for i = 1,200000 do
496 a = {next = a}
497 end
498 a = nil
499 collectgarbage()
500end
501
502-- create many threads with self-references and open upvalues
503print("self-referenced threads")
504local thread_id = 0
505local threads = {}
506
507local function fn (thread)
508 local x = {}
509 threads[thread_id] = function()
510 thread = x
511 end
512 coroutine.yield()
513end
514
515while thread_id < 1000 do
516 local thread = coroutine.create(fn)
517 coroutine.resume(thread, thread)
518 thread_id = thread_id + 1
519end
520
521
522-- Create a closure (function inside 'f') with an upvalue ('param') that
523-- points (through a table) to the closure itself and to the thread
524-- ('co' and the initial value of 'param') where closure is running.
525-- Then, assert that table (and therefore everything else) will be
526-- collected.
527do
528 local collected = false -- to detect collection
529 collectgarbage(); collectgarbage("stop")
530 do
531 local function f (param)
532 ;(function ()
533 assert(type(f) == 'function' and type(param) == 'thread')
534 param = {param, f}
535 setmetatable(param, {__gc = function () collected = true end})
536 coroutine.yield(100)
537 end)()
538 end
539 local co = coroutine.create(f)
540 assert(coroutine.resume(co, co))
541 end
542 -- Now, thread and closure are not reachable any more.
543 collectgarbage()
544 assert(collected)
545 collectgarbage("restart")
546end
547
548
549do
550 collectgarbage()
551 collectgarbage"stop"
552 collectgarbage("step") -- steps should not unblock the collector
553 local x = gcinfo()
554 repeat
555 for i=1,1000 do _ENV.a = {} end -- no collection during the loop
556 until gcinfo() > 2 * x
557 collectgarbage"restart"
558 _ENV.a = nil
559end
560
561
562if T then -- tests for weird cases collecting upvalues
563
564 local function foo ()
565 local a = {x = 20}
566 coroutine.yield(function () return a.x end) -- will run collector
567 assert(a.x == 20) -- 'a' is 'ok'
568 a = {x = 30} -- create a new object
569 assert(T.gccolor(a) == "white") -- of course it is new...
570 coroutine.yield(100) -- 'a' is still local to this thread
571 end
572
573 local t = setmetatable({}, {__mode = "kv"})
574 collectgarbage(); collectgarbage('stop')
575 -- create coroutine in a weak table, so it will never be marked
576 t.co = coroutine.wrap(foo)
577 local f = t.co() -- create function to access local 'a'
578 T.gcstate("enteratomic") -- ensure all objects are traversed
579 assert(T.gcstate() == "enteratomic")
580 assert(t.co() == 100) -- resume coroutine, creating new table for 'a'
581 assert(T.gccolor(t.co) == "white") -- thread was not traversed
582 T.gcstate("pause") -- collect thread, but should mark 'a' before that
583 assert(t.co == nil and f() == 30) -- ensure correct access to 'a'
584
585 collectgarbage("restart")
586
587 -- test barrier in sweep phase (backing userdata to gray)
588 local u = T.newuserdata(0, 1) -- create a userdata
589 collectgarbage()
590 collectgarbage"stop"
591 local a = {} -- avoid 'u' as first element in 'allgc'
592 T.gcstate"enteratomic"
593 T.gcstate"sweepallgc"
594 local x = {}
595 assert(T.gccolor(u) == "black") -- userdata is "old" (black)
596 assert(T.gccolor(x) == "white") -- table is "new" (white)
597 debug.setuservalue(u, x) -- trigger barrier
598 assert(T.gccolor(u) == "gray") -- userdata changed back to gray
599 collectgarbage"restart"
600
601 print"+"
602end
603
604
605if T then
606 local debug = require "debug"
607 collectgarbage("stop")
608 local x = T.newuserdata(0)
609 local y = T.newuserdata(0)
610 debug.setmetatable(y, {__gc = nop}) -- bless the new udata before...
611 debug.setmetatable(x, {__gc = nop}) -- ...the old one
612 assert(T.gccolor(y) == "white")
613 T.checkmemory()
614 collectgarbage("restart")
615end
616
617
618if T then
619 collectgarbage("stop")
620 T.gcstate("pause")
621 local sup = {x = 0}
622 local a = setmetatable({}, {__newindex = sup})
623 T.gcstate("enteratomic")
624 assert(T.gccolor(sup) == "black")
625 a.x = {} -- should not break the invariant
626 assert(not (T.gccolor(sup) == "black" and T.gccolor(sup.x) == "white"))
627 T.gcstate("pause") -- complete the GC cycle
628 sup.x.y = 10
629 collectgarbage("restart")
630end
631
632
633if T then
634 print("emergency collections")
635 collectgarbage()
636 collectgarbage()
637 T.totalmem(T.totalmem() + 200)
638 for i=1,200 do local a = {} end
639 T.totalmem(0)
640 collectgarbage()
641 local t = T.totalmem("table")
642 local a = {{}, {}, {}} -- create 4 new tables
643 assert(T.totalmem("table") == t + 4)
644 t = T.totalmem("function")
645 a = function () end -- create 1 new closure
646 assert(T.totalmem("function") == t + 1)
647 t = T.totalmem("thread")
648 a = coroutine.create(function () end) -- create 1 new coroutine
649 assert(T.totalmem("thread") == t + 1)
650end
651
652
653-- create an object to be collected when state is closed
654do
655 local setmetatable,assert,type,print,getmetatable =
656 setmetatable,assert,type,print,getmetatable
657 local tt = {}
658 tt.__gc = function (o)
659 assert(getmetatable(o) == tt)
660 -- create new objects during GC
661 local a = 'xuxu'..(10+3)..'joao', {}
662 ___Glob = o -- resurrect object!
663 setmetatable({}, tt) -- creates a new one with same metatable
664 print(">>> closing state " .. "<<<\n")
665 end
666 local u = setmetatable({}, tt)
667 ___Glob = {u} -- avoid object being collected before program end
668end
669
670-- create several objects to raise errors when collected while closing state
671if T then
672 local error, assert, find, warn = error, assert, string.find, warn
673 local n = 0
674 local lastmsg
675 local mt = {__gc = function (o)
676 n = n + 1
677 assert(n == o[1])
678 if n == 1 then
679 _WARN = false
680 elseif n == 2 then
681 assert(find(_WARN, "@expected warning"))
682 lastmsg = _WARN -- get message from previous error (first 'o')
683 else
684 assert(lastmsg == _WARN) -- subsequent error messages are equal
685 end
686 warn("@store"); _WARN = false
687 error"@expected warning"
688 end}
689 for i = 10, 1, -1 do
690 -- create object and preserve it until the end
691 table.insert(___Glob, setmetatable({i}, mt))
692 end
693end
694
695-- just to make sure
696assert(collectgarbage'isrunning')
697
698do -- check that the collector is not reentrant in incremental mode
699 local res = true
700 setmetatable({}, {__gc = function ()
701 res = collectgarbage()
702 end})
703 collectgarbage()
704 assert(not res)
705end
706
707
708collectgarbage(oldmode)
709
710
711if T then
712 print("testing stack issues when calling finalizers")
713
714 local X
715 local obj
716
717 local function initobj ()
718 X = false
719 obj = setmetatable({}, {__gc = function () X = true end})
720 end
721
722 local function loop (n)
723 if n > 0 then loop(n - 1) end
724 end
725
726 -- should not try to call finalizer without a CallInfo available
727 initobj()
728 loop(20) -- ensure stack space
729 T.resetCI() -- remove extra CallInfos
730 T.alloccount(0) -- cannot allocate more CallInfos
731 obj = nil
732 collectgarbage() -- will not call finalizer
733 T.alloccount()
734 assert(X == false)
735 collectgarbage() -- now will call finalizer (it was still pending)
736 assert(X == true)
737
738 -- should not try to call finalizer without stack space available
739 initobj()
740 loop(5) -- ensure enough CallInfos
741 T.reallocstack(0) -- remove extra stack slots
742 T.alloccount(0) -- cannot reallocate stack
743 obj = nil
744 collectgarbage() -- will not call finalizer
745 T.alloccount()
746 assert(X == false)
747 collectgarbage() -- now will call finalizer (it was still pending)
748 assert(X == true)
749end
750
751
752print('OK')