Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/lua/blob/master/testes/gc.lua # lua [Ported from github.com/lua/lua] Cast in 'rl_readline_name' Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers 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 4 print('testing incremental garbage collection') 5 6 local debug = require"debug" 7 8 assert(collectgarbage("isrunning")) 9 10 collectgarbage() 11 12 local oldmode = collectgarbage("incremental") 13 14 -- changing modes should return previous mode 15 assert(collectgarbage("generational") == "incremental") 16 assert(collectgarbage("generational") == "generational") 17 assert(collectgarbage("incremental") == "generational") 18 assert(collectgarbage("incremental") == "incremental") 19 20 21 local function nop () end 22 23 local function gcinfo () 24 return collectgarbage"count" * 1024 25 end 26 27 28 -- test weird parameters to 'collectgarbage' 29 do 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() 47 end 48 49 50 -- 51 -- test the "size" of basic GC steps (whatever they mean...) 52 -- 53 do 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 75 end 76 77 78 _G["while"] = 234 79 80 81 -- 82 -- tests for GC activation when creating different kinds of objects 83 -- 84 local 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 102 end 103 104 local 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 121 end 122 123 local function GC() GC1(); GC2() end 124 125 126 do 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 156 end 157 158 159 -- collection of functions without locals, globals, etc. 160 do local f = function () end end 161 162 163 print("functions with errors") 164 local prog = [[ 165 do 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 172 end 173 ]] 174 do 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 182 end 183 rawset(_G, "a", nil) 184 _G.x = nil 185 186 do 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 201 end 202 203 204 if 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 217 end 218 219 220 print("clearing tables") 221 local lim = 15 222 local a = {} 223 -- fill a with `collectable' indices 224 for i=1,lim do a[{}] = i end 225 b = {} 226 for k,v in pairs(a) do b[k]=v end 227 -- remove all indices and collect them 228 for n in pairs(b) do 229 a[n] = undef 230 assert(type(n) == 'table' and next(n) == nil) 231 collectgarbage() 232 end 233 b = nil 234 collectgarbage() 235 for n in pairs(a) do error'cannot be here' end 236 for i=1,lim do a[i] = i end 237 for i=1,lim do assert(a[i] == i) end 238 239 240 print('weak tables') 241 a = {}; setmetatable(a, {__mode = 'k'}); 242 -- fill a with some `collectable' indices 243 for i=1,lim do a[{}] = i end 244 -- and some non-collectable ones 245 for i=1,lim do a[i] = i end 246 for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end 247 collectgarbage() 248 local i = 0 249 for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end 250 assert(i == 2*lim) 251 252 a = {}; setmetatable(a, {__mode = 'v'}); 253 a[1] = string.rep('b', 21) 254 collectgarbage() 255 assert(a[1]) -- strings are *values* 256 a[1] = undef 257 -- fill a with some `collectable' values (in both parts of the table) 258 for i=1,lim do a[i] = {} end 259 for i=1,lim do a[i..'x'] = {} end 260 -- and some non-collectable ones 261 for i=1,lim do local t={}; a[t]=t end 262 for i=1,lim do a[i+lim]=i..'x' end 263 collectgarbage() 264 local i = 0 265 for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end 266 assert(i == 2*lim) 267 268 a = {}; setmetatable(a, {__mode = 'kv'}); 269 local x, y, z = {}, {}, {} 270 -- keep only some items 271 a[1], a[2], a[3] = x, y, z 272 a[string.rep('$', 11)] = string.rep('$', 11) 273 -- fill a with some `collectable' values 274 for i=4,lim do a[i] = {} end 275 for i=1,lim do a[{}] = i end 276 for i=1,lim do local t={}; a[t]=t end 277 collectgarbage() 278 assert(next(a) ~= nil) 279 local i = 0 280 for 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 285 end 286 assert(i == 4) 287 x,y,z=nil 288 collectgarbage() 289 assert(next(a) == string.rep('$', 11)) 290 291 do -- invalid mode 292 local a = setmetatable({}, {__mode = 34}) 293 collectgarbage() 294 end 295 296 297 if 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") 304 end 305 306 307 -- 'bug' in 5.1 308 a = {} 309 local t = {x = 10} 310 local C = setmetatable({key = t}, {__mode = 'v'}) 311 local C1 = setmetatable({[t] = 1}, {__mode = 'k'}) 312 a.x = t -- this should not prevent 't' from being removed from 313 -- weak table 'C' by the time 'a' is finalized 314 315 setmetatable(a, {__gc = function (u) 316 assert(C.key == nil) 317 assert(type(next(C1)) == 'table') 318 end}) 319 320 a, t = nil 321 collectgarbage() 322 collectgarbage() 323 assert(next(C) == nil and next(C1) == nil) 324 C, C1 = nil 325 326 327 -- ephemerons 328 local mt = {__mode = 'k'} 329 a = {{10},{20},{30},{40}}; setmetatable(a, mt) 330 x = nil 331 for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end 332 GC() 333 local n = x 334 local i = 0 335 while n do n = a[n].k[1]; i = i + 1 end 336 assert(i == 100) 337 x = nil 338 GC() 339 for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = undef end 340 assert(next(a) == nil) 341 342 local K = {} 343 a[K] = {} 344 for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end 345 x = nil 346 local k = 1 347 for 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 350 end 351 GC() 352 local n = x 353 local i = 0 354 while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end 355 assert(i == 100) 356 K = nil 357 GC() 358 -- assert(next(a) == nil) 359 360 361 -- testing errors during GC 362 if 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 395 end 396 print '+' 397 398 399 -- testing userdata 400 if T==nil then 401 (Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n') 402 403 else 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 437 end 438 439 440 -- __gc x weak tables 441 local u = setmetatable({}, {__gc = true}) 442 -- __gc metamethod should be collected before running 443 setmetatable(getmetatable(u), {__mode = "v"}) 444 getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen 445 u = nil 446 collectgarbage() 447 448 local u = setmetatable({}, {__gc = true}) 449 local m = getmetatable(u) 450 m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"}); 451 m.__gc = function (o) 452 assert(next(getmetatable(o).x) == nil) 453 m = 10 454 end 455 u, m = nil 456 collectgarbage() 457 assert(m==10) 458 459 do -- 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 478 end 479 480 481 -- errors during collection 482 if 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") 489 end 490 491 492 if 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() 500 end 501 502 -- create many threads with self-references and open upvalues 503 print("self-referenced threads") 504 local thread_id = 0 505 local threads = {} 506 507 local function fn (thread) 508 local x = {} 509 threads[thread_id] = function() 510 thread = x 511 end 512 coroutine.yield() 513 end 514 515 while thread_id < 1000 do 516 local thread = coroutine.create(fn) 517 coroutine.resume(thread, thread) 518 thread_id = thread_id + 1 519 end 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. 527 do 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") 546 end 547 548 549 do 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 559 end 560 561 562 if 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"+" 602 end 603 604 605 if 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") 615 end 616 617 618 if 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") 630 end 631 632 633 if 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) 650 end 651 652 653 -- create an object to be collected when state is closed 654 do 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 668 end 669 670 -- create several objects to raise errors when collected while closing state 671 if 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 693 end 694 695 -- just to make sure 696 assert(collectgarbage'isrunning') 697 698 do -- 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) 705 end 706 707 708 collectgarbage(oldmode) 709 710 711 if 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) 749 end 750 751 752 print('OK')