554a7c42e9282ed31d39c89306b878aade1b1529
[openwrt.git] / package / lua / patches / 600-refcounting.patch
1 --- a/src/lapi.c
2 +++ b/src/lapi.c
3 @@ -27,8 +27,8 @@
4  #include "ltable.h"
5  #include "ltm.h"
6  #include "lundump.h"
7 -#include "lvm.h"
8  #include "lnum.h"
9 +#include "lvm.h"
10  
11  
12  const char lua_ident[] =
13 @@ -117,6 +117,7 @@ LUA_API void lua_xmove (lua_State *from,
14    from->top -= n;
15    for (i = 0; i < n; i++) {
16      setobj2s(to, to->top++, from->top + i);
17 +    setnilvalue(from, from->top + i);
18    }
19    lua_unlock(to);
20  }
21 @@ -166,12 +167,14 @@ LUA_API void lua_settop (lua_State *L, i
22    if (idx >= 0) {
23      api_check(L, idx <= L->stack_last - L->base);
24      while (L->top < L->base + idx)
25 -      setnilvalue(L->top++);
26 +      setnilvalue(L, L->top++);
27      L->top = L->base + idx;
28 +    setnilvalue(L, L->top);
29    }
30    else {
31 +    int i;
32      api_check(L, -(idx+1) <= (L->top - L->base));
33 -    L->top += idx+1;  /* `subtract' index (index is negative) */
34 +       setlvmtop(L, L->top + idx + 1); /* `subtract' index (index is negative) */
35    }
36    lua_unlock(L);
37  }
38 @@ -183,7 +186,7 @@ LUA_API void lua_remove (lua_State *L, i
39    p = index2adr(L, idx);
40    api_checkvalidindex(L, p);
41    while (++p < L->top) setobjs2s(L, p-1, p);
42 -  L->top--;
43 +  setlvmtop(L, L->top - 1);
44    lua_unlock(L);
45  }
46  
47 @@ -196,6 +199,7 @@ LUA_API void lua_insert (lua_State *L, i
48    api_checkvalidindex(L, p);
49    for (q = L->top; q>p; q--) setobjs2s(L, q, q-1);
50    setobjs2s(L, p, L->top);
51 +  setnilvalue(L, L->top);
52    lua_unlock(L);
53  }
54  
55 @@ -220,7 +224,7 @@ LUA_API void lua_replace (lua_State *L, 
56      if (idx < LUA_GLOBALSINDEX)  /* function upvalue? */
57        luaC_barrier(L, curr_func(L), L->top - 1);
58    }
59 -  L->top--;
60 +  setlvmtop(L, L->top - 1);
61    lua_unlock(L);
62  }
63  
64 @@ -259,14 +263,14 @@ LUA_API int lua_iscfunction (lua_State *
65  
66  
67  LUA_API int lua_isnumber (lua_State *L, int idx) {
68 -  TValue n;
69 +  TValue n = tvinit();
70    const TValue *o = index2adr(L, idx);
71    return tonumber(o, &n);
72  }
73  
74  
75  LUA_API int lua_isinteger (lua_State *L, int idx) {
76 -  TValue tmp;
77 +  TValue tmp = tvinit();
78    lua_Integer dum;
79    const TValue *o = index2adr(L, idx);
80    return tonumber(o,&tmp) && (ttisint(o) || tt_integer_valued(o,&dum));
81 @@ -319,7 +323,7 @@ LUA_API int lua_lessthan (lua_State *L, 
82  
83  
84  LUA_API lua_Number lua_tonumber (lua_State *L, int idx) {
85 -  TValue n;
86 +  TValue n = tvinit();
87    const TValue *o = index2adr(L, idx);
88    if (tonumber(o, &n)) {
89  #ifdef LNUM_COMPLEX
90 @@ -333,7 +337,7 @@ LUA_API lua_Number lua_tonumber (lua_Sta
91  
92  
93  LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
94 -  TValue n;
95 +  TValue n = tvinit();
96      /* Lua 5.1 documented behaviour is to return nonzero for non-integer:
97       * "If the number is not an integer, it is truncated in some non-specified way." 
98       * I would suggest to change this, to return 0 for anything that would
99 @@ -369,7 +373,7 @@ LUA_API lua_Integer lua_tointeger (lua_S
100  
101  #ifdef LNUM_COMPLEX
102  LUA_API lua_Complex lua_tocomplex (lua_State *L, int idx) {
103 -  TValue tmp;
104 +  TValue tmp = tvinit();
105    const TValue *o = index2adr(L, idx);
106    if (tonumber(o, &tmp))
107      return nvalue_complex(o);
108 @@ -465,7 +469,7 @@ LUA_API const void *lua_topointer (lua_S
109  
110  LUA_API void lua_pushnil (lua_State *L) {
111    lua_lock(L);
112 -  setnilvalue(L->top);
113 +  setnilvalue(L, L->top);
114    api_incr_top(L);
115    lua_unlock(L);
116  }
117 @@ -548,8 +552,10 @@ LUA_API void lua_pushcclosure (lua_State
118    cl = luaF_newCclosure(L, n, getcurrenv(L));
119    cl->c.f = fn;
120    L->top -= n;
121 -  while (n--)
122 +  while (n--) {
123      setobj2n(L, &cl->c.upvalue[n], L->top+n);
124 +    setnilvalue(L, L->top + n);
125 +  }
126    setclvalue(L, L->top, cl);
127    lua_assert(iswhite(obj2gco(cl)));
128    api_incr_top(L);
129 @@ -600,7 +606,7 @@ LUA_API void lua_gettable (lua_State *L,
130  
131  LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
132    StkId t;
133 -  TValue key;
134 +  TValue key = tvinit();
135    lua_lock(L);
136    t = index2adr(L, idx);
137    api_checkvalidindex(L, t);
138 @@ -689,7 +695,7 @@ LUA_API void lua_getfenv (lua_State *L, 
139        setobj2s(L, L->top,  gt(thvalue(o)));
140        break;
141      default:
142 -      setnilvalue(L->top);
143 +      setnilvalue(L, L->top);
144        break;
145    }
146    api_incr_top(L);
147 @@ -709,21 +715,21 @@ LUA_API void lua_settable (lua_State *L,
148    t = index2adr(L, idx);
149    api_checkvalidindex(L, t);
150    luaV_settable(L, t, L->top - 2, L->top - 1);
151 -  L->top -= 2;  /* pop index and value */
152 +  setlvmtop(L, L->top - 2);  /* pop index and value */
153    lua_unlock(L);
154  }
155  
156  
157  LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
158    StkId t;
159 -  TValue key;
160 +  TValue key = tvinit();
161    lua_lock(L);
162    api_checknelems(L, 1);
163    t = index2adr(L, idx);
164    api_checkvalidindex(L, t);
165    setsvalue(L, &key, luaS_new(L, k));
166    luaV_settable(L, t, &key, L->top - 1);
167 -  L->top--;  /* pop value */
168 +  setlvmtop(L, L->top - 1);  /* pop value */
169    lua_unlock(L);
170  }
171  
172 @@ -736,7 +742,7 @@ LUA_API void lua_rawset (lua_State *L, i
173    api_check(L, ttistable(t));
174    setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
175    luaC_barriert(L, hvalue(t), L->top-1);
176 -  L->top -= 2;
177 +  setlvmtop(L, L->top - 2);
178    lua_unlock(L);
179  }
180  
181 @@ -749,7 +755,7 @@ LUA_API void lua_rawseti (lua_State *L, 
182    api_check(L, ttistable(o));
183    setobj2t(L, luaH_setint(L, hvalue(o), n), L->top-1);
184    luaC_barriert(L, hvalue(o), L->top-1);
185 -  L->top--;
186 +  setlvmtop(L, L->top - 1);
187    lua_unlock(L);
188  }
189  
190 @@ -785,7 +791,7 @@ LUA_API int lua_setmetatable (lua_State 
191        break;
192      }
193    }
194 -  L->top--;
195 +  setlvmtop(L, L->top - 1);
196    lua_unlock(L);
197    return 1;
198  }
199 @@ -814,7 +820,7 @@ LUA_API int lua_setfenv (lua_State *L, i
200        break;
201    }
202    if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
203 -  L->top--;
204 +  setlvmtop(L, L->top - 1);
205    lua_unlock(L);
206    return res;
207  }
208 @@ -1040,8 +1046,9 @@ LUA_API int lua_next (lua_State *L, int 
209    if (more) {
210      api_incr_top(L);
211    }
212 -  else  /* no more elements */
213 -    L->top -= 1;  /* remove key */
214 +  else {  /* no more elements */
215 +    setlvmtop(L, L->top - 1);  /* remove key */
216 +  }
217    lua_unlock(L);
218    return more;
219  }
220 @@ -1053,7 +1060,7 @@ LUA_API void lua_concat (lua_State *L, i
221    if (n >= 2) {
222      luaC_checkGC(L);
223      luaV_concat(L, n, cast_int(L->top - L->base) - 1);
224 -    L->top -= (n-1);
225 +    setlvmtop(L, L->top - (n-1));
226    }
227    else if (n == 0) {  /* push empty string */
228      setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
229 @@ -1139,6 +1146,7 @@ LUA_API const char *lua_setupvalue (lua_
230    if (name) {
231      L->top--;
232      setobj(L, val, L->top);
233 +    setnilvalue(L, L->top);
234      luaC_barrier(L, clvalue(fi), L->top);
235    }
236    lua_unlock(L);
237 @@ -1160,7 +1168,7 @@ LUA_API const char *lua_setupvalue (lua_
238  int lua_pushvalue_as_number (lua_State *L, int idx)
239  {
240    const TValue *o = index2adr(L, idx);
241 -  TValue tmp;
242 +  TValue tmp = tvinit();
243    lua_Integer i;
244    if (ttisnumber(o)) {
245      if ( (!ttisint(o)) && tt_integer_valued(o,&i)) {
246 --- a/src/lcode.c
247 +++ b/src/lcode.c
248 @@ -23,6 +23,7 @@
249  #include "lparser.h"
250  #include "ltable.h"
251  #include "lnum.h"
252 +#include "lvm.h"
253  
254  
255  #define hasjumps(e)    ((e)->t != (e)->f)
256 @@ -248,7 +249,7 @@ static int addk (FuncState *fs, TValue *
257      setivalue(idx, fs->nk);
258      luaM_growvector(L, f->k, fs->nk, f->sizek, TValue,
259                      MAXARG_Bx, "constant table overflow");
260 -    while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
261 +    while (oldsize < f->sizek) setnilvalue(L, &f->k[oldsize++]);
262      setobj(L, &f->k[fs->nk], v);
263      luaC_barrier(L, f, v);
264      return fs->nk++;
265 @@ -257,21 +258,24 @@ static int addk (FuncState *fs, TValue *
266  
267  
268  int luaK_stringK (FuncState *fs, TString *s) {
269 -  TValue o;
270 +  TValue o = tvinit();
271    setsvalue(fs->L, &o, s);
272 +  luaV_unref(fs->L, &o);
273    return addk(fs, &o, &o);
274  }
275  
276  
277  int luaK_numberK (FuncState *fs, lua_Number r) {
278 -  TValue o;
279 +  lua_State *L = fs->L;
280 +  TValue o = tvinit();
281    setnvalue(&o, r);
282    return addk(fs, &o, &o);
283  }
284  
285  
286  int luaK_integerK (FuncState *fs, lua_Integer r) {
287 -  TValue o;
288 +  lua_State *L = fs->L;
289 +  TValue o = tvinit();
290    setivalue(&o, r);
291    return addk(fs, &o, &o);
292  }
293 @@ -279,22 +283,24 @@ int luaK_integerK (FuncState *fs, lua_In
294  
295  #ifdef LNUM_COMPLEX
296  static int luaK_imagK (FuncState *fs, lua_Number r) {
297 -  TValue o;
298 +  lua_State *L = fs->L;
299 +  TValue o = tvinit();
300    setnvalue_complex(&o, r*I);
301    return addk(fs, &o, &o);
302  }
303  #endif
304  
305  static int boolK (FuncState *fs, int b) {
306 -  TValue o;
307 +  lua_State *L = fs->L;
308 +  TValue o = tvinit();
309    setbvalue(&o, b);
310    return addk(fs, &o, &o);
311  }
312  
313  
314  static int nilK (FuncState *fs) {
315 -  TValue k, v;
316 -  setnilvalue(&v);
317 +  TValue k = tvinit(), v = tvinit();
318 +  setnilvalue(fs->L, &v);
319    /* cannot use nil as key; instead use table itself to represent nil */
320    sethvalue(fs->L, &k, fs->h);
321    return addk(fs, &k, &v);
322 --- a/src/ldebug.c
323 +++ b/src/ldebug.c
324 @@ -142,6 +142,7 @@ LUA_API const char *lua_setlocal (lua_St
325    if (name)
326        setobjs2s(L, ci->base + (n - 1), L->top - 1);
327    L->top--;  /* pop value */
328 +  setnilvalue(L, L->top);
329    lua_unlock(L);
330    return name;
331  }
332 @@ -176,7 +177,7 @@ static void info_tailcall (lua_Debug *ar
333  
334  static void collectvalidlines (lua_State *L, Closure *f) {
335    if (f == NULL || f->c.isC) {
336 -    setnilvalue(L->top);
337 +    setnilvalue(L, L->top);
338    }
339    else {
340      Table *t = luaH_new(L, 0, 0);
341 @@ -248,7 +249,7 @@ LUA_API int lua_getinfo (lua_State *L, c
342    }
343    status = auxgetinfo(L, what, ar, f, ci);
344    if (strchr(what, 'f')) {
345 -    if (f == NULL) setnilvalue(L->top);
346 +    if (f == NULL) setnilvalue(L, L->top);
347      else setclvalue(L, L->top, f);
348      incr_top(L);
349    }
350 @@ -586,7 +587,7 @@ void luaG_concaterror (lua_State *L, Stk
351  
352  
353  void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
354 -  TValue temp;
355 +  TValue temp = tvinit();
356    if (luaV_tonumber(p1, &temp) == NULL)
357      p2 = p1;  /* first operand is wrong */
358    luaG_typeerror(L, p2, "perform arithmetic on");
359 --- a/src/ldo.c
360 +++ b/src/ldo.c
361 @@ -211,7 +211,7 @@ static StkId adjust_varargs (lua_State *
362    Table *htab = NULL;
363    StkId base, fixed;
364    for (; actual < nfixargs; ++actual)
365 -    setnilvalue(L->top++);
366 +    setnilvalue(L, L->top++);
367  #if defined(LUA_COMPAT_VARARG)
368    if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */
369      int nvar = actual - nfixargs;  /* number of extra arguments */
370 @@ -229,7 +229,7 @@ static StkId adjust_varargs (lua_State *
371    base = L->top;  /* final position of first argument */
372    for (i=0; i<nfixargs; i++) {
373      setobjs2s(L, L->top++, fixed+i);
374 -    setnilvalue(fixed+i);
375 +    setnilvalue(L, fixed+i);
376    }
377    /* add `arg' parameter */
378    if (htab) {
379 @@ -294,7 +294,7 @@ int luaD_precall (lua_State *L, StkId fu
380      ci->tailcalls = 0;
381      ci->nresults = nresults;
382      for (st = L->top; st < ci->top; st++)
383 -      setnilvalue(st);
384 +      setnilvalue(L, st);
385      L->top = ci->top;
386      if (L->hookmask & LUA_MASKCALL) {
387        L->savedpc++;  /* hooks assume 'pc' is already incremented */
388 @@ -354,8 +354,8 @@ int luaD_poscall (lua_State *L, StkId fi
389    for (i = wanted; i != 0 && firstResult < L->top; i--)
390      setobjs2s(L, res++, firstResult++);
391    while (i-- > 0)
392 -    setnilvalue(res++);
393 -  L->top = res;
394 +    setnilvalue(L, res++);
395 +  setlvmtop(L, res);
396    return (wanted - LUA_MULTRET);  /* 0 iff wanted == LUA_MULTRET */
397  }
398  
399 @@ -463,8 +463,12 @@ int luaD_pcall (lua_State *L, Pfunc func
400    status = luaD_rawrunprotected(L, func, u);
401    if (status != 0) {  /* an error occurred? */
402      StkId oldtop = restorestack(L, old_top);
403 +       StkId curtop = L->top;
404 +    int i;
405      luaF_close(L, oldtop);  /* close eventual pending closures */
406      luaD_seterrorobj(L, status, oldtop);
407 +    for (i = (curtop - L->top); i-- > 0;)
408 +      setnilvalue(L, L->top + i);
409      L->nCcalls = oldnCcalls;
410      L->ci = restoreci(L, old_ci);
411      L->base = L->ci->base;
412 --- a/src/lfunc.c
413 +++ b/src/lfunc.c
414 @@ -17,7 +17,7 @@
415  #include "lmem.h"
416  #include "lobject.h"
417  #include "lstate.h"
418 -
419 +#include "lvm.h"
420  
421  
422  Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e) {
423 @@ -45,7 +45,7 @@ UpVal *luaF_newupval (lua_State *L) {
424    UpVal *uv = luaM_new(L, UpVal);
425    luaC_link(L, obj2gco(uv), LUA_TUPVAL);
426    uv->v = &uv->u.value;
427 -  setnilvalue(uv->v);
428 +  setnilvalue(L, uv->v);
429    return uv;
430  }
431  
432 @@ -67,8 +67,14 @@ UpVal *luaF_findupval (lua_State *L, Stk
433    uv = luaM_new(L, UpVal);  /* not found: create a new one */
434    uv->tt = LUA_TUPVAL;
435    uv->marked = luaC_white(g);
436 -  uv->v = level;  /* current value lives in the stack */
437 +  uv->v = luaV_ref(level);  /* current value lives in the stack */
438    uv->next = *pp;  /* chain it in the proper position */
439 +  if (uv->next) {
440 +       uv->prev = uv->next->gch.prev;
441 +    uv->next->gch.prev = (GCObject *)uv;
442 +  } else {
443 +    uv->prev = NULL;
444 +  }
445    *pp = obj2gco(uv);
446    uv->u.l.prev = &g->uvhead;  /* double link it in `uvhead' list */
447    uv->u.l.next = g->uvhead.u.l.next;
448 --- a/src/lgc.c
449 +++ b/src/lgc.c
450 @@ -21,6 +21,7 @@
451  #include "lstring.h"
452  #include "ltable.h"
453  #include "ltm.h"
454 +#include "lvm.h"
455  
456  
457  #define GCSTEPSIZE     1024u
458 @@ -265,7 +266,7 @@ static void traversestack (global_State 
459    for (o = l->stack; o < l->top; o++)
460      markvalue(g, o);
461    for (; o <= lim; o++)
462 -    setnilvalue(o);
463 +    setnilvalue(l, o);
464    checkstacksizes(l, lim);
465  }
466  
467 @@ -348,7 +349,7 @@ static int iscleared (const TValue *o, i
468  /*
469  ** clear collected entries from weaktables
470  */
471 -static void cleartable (GCObject *l) {
472 +static void cleartable (lua_State *L, GCObject *l) {
473    while (l) {
474      Table *h = gco2h(l);
475      int i = h->sizearray;
476 @@ -358,7 +359,7 @@ static void cleartable (GCObject *l) {
477        while (i--) {
478          TValue *o = &h->array[i];
479          if (iscleared(o, 0))  /* value was collected? */
480 -          setnilvalue(o);  /* remove value */
481 +          setnilvalue(L, o);  /* remove value */
482        }
483      }
484      i = sizenode(h);
485 @@ -366,7 +367,7 @@ static void cleartable (GCObject *l) {
486        Node *n = gnode(h, i);
487        if (!ttisnil(gval(n)) &&  /* non-empty entry? */
488            (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) {
489 -        setnilvalue(gval(n));  /* remove value ... */
490 +        setnilvalue(L, gval(n));  /* remove value ... */
491          removeentry(n);  /* remove entry from table */
492        }
493      }
494 @@ -375,7 +376,7 @@ static void cleartable (GCObject *l) {
495  }
496  
497  
498 -static void freeobj (lua_State *L, GCObject *o) {
499 +void luaC_freeobj (lua_State *L, GCObject *o) {
500    switch (o->gch.tt) {
501      case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
502      case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break;
503 @@ -418,10 +419,12 @@ static GCObject **sweeplist (lua_State *
504      }
505      else {  /* must erase `curr' */
506        lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT));
507 +      if (curr->gch.next)
508 +        curr->gch.next->gch.prev = curr->gch.prev;
509        *p = curr->gch.next;
510        if (curr == g->rootgc)  /* is the first element of the list? */
511          g->rootgc = curr->gch.next;  /* adjust first */
512 -      freeobj(L, curr);
513 +      luaC_freeobj(L, curr);
514      }
515    }
516    return p;
517 @@ -543,7 +546,7 @@ static void atomic (lua_State *L) {
518    udsize = luaC_separateudata(L, 0);  /* separate userdata to be finalized */
519    marktmu(g);  /* mark `preserved' userdata */
520    udsize += propagateall(g);  /* remark, to propagate `preserveness' */
521 -  cleartable(g->weak);  /* remove collected objects from weak tables */
522 +  cleartable(L, g->weak);  /* remove collected objects from weak tables */
523    /* flip current white */
524    g->currentwhite = cast_byte(otherwhite(g));
525    g->sweepstrgc = 0;
526 @@ -685,8 +688,11 @@ void luaC_barrierback (lua_State *L, Tab
527  
528  void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
529    global_State *g = G(L);
530 +  o->gch.prev = (GCObject*)&g->rootgc;
531    o->gch.next = g->rootgc;
532    g->rootgc = o;
533 +  if (o->gch.next)
534 +    o->gch.next->gch.prev = o;
535    o->gch.marked = luaC_white(g);
536    o->gch.tt = tt;
537  }
538 --- a/src/lgc.h
539 +++ b/src/lgc.h
540 @@ -105,6 +105,6 @@ LUAI_FUNC void luaC_link (lua_State *L, 
541  LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv);
542  LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v);
543  LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t);
544 -
545 +LUAI_FUNC void luaC_freeobj (lua_State *L, GCObject *o);
546  
547  #endif
548 --- a/src/lmem.c
549 +++ b/src/lmem.c
550 @@ -6,6 +6,7 @@
551  
552  
553  #include <stddef.h>
554 +#include <string.h>
555  
556  #define lmem_c
557  #define LUA_CORE
558 @@ -80,6 +81,8 @@ void *luaM_realloc_ (lua_State *L, void 
559    if (block == NULL && nsize > 0)
560      luaD_throw(L, LUA_ERRMEM);
561    lua_assert((nsize == 0) == (block == NULL));
562 +  if (nsize > osize)
563 +    memset((char *)block + osize, 0, nsize - osize);
564    g->totalbytes = (g->totalbytes - osize) + nsize;
565    return block;
566  }
567 --- a/src/lobject.h
568 +++ b/src/lobject.h
569 @@ -44,7 +44,7 @@ typedef union GCObject GCObject;
570  ** Common Header for all collectable objects (in macro form, to be
571  ** included in other objects)
572  */
573 -#define CommonHeader   GCObject *next; lu_byte tt; lu_byte marked
574 +#define CommonHeader   GCObject *next; GCObject *prev; lu_byte tt; lu_byte marked
575  
576  
577  /*
578 @@ -83,6 +83,7 @@ typedef struct lua_TValue {
579    TValuefields;
580  } TValue;
581  
582 +#define tvinit() { .value.b = 0, .tt = 0 }
583  
584  /* Macros to test type */
585  #define ttisnil(o)     (ttype(o) == LUA_TNIL)
586 @@ -145,15 +146,15 @@ typedef struct lua_TValue {
587  
588  
589  /* Macros to set values */
590 -#define setnilvalue(obj) ((obj)->tt=LUA_TNIL)
591 +#define setnilvalue(L, obj) (luaV_unref(L, (obj))->tt=LUA_TNIL)
592  
593  /* Must not have side effects, 'x' may be expression.
594  */
595  #define setivalue(obj,x) \
596 -    { TValue *i_o=(obj); i_o->value.i=(x); i_o->tt=LUA_TINT; }
597 +    { TValue *i_o=luaV_unref(L, (obj)); i_o->value.i=(x); i_o->tt=LUA_TINT; }
598  
599  # define setnvalue(obj,x) \
600 -    { TValue *i_o=(obj); i_o->value.n= (x); i_o->tt=LUA_TNUMBER; }
601 +    { TValue *i_o=luaV_unref(L, (obj)); i_o->value.n= (x); i_o->tt=LUA_TNUMBER; }
602  
603  /* Note: Complex always has "inline", both are C99.
604  */
605 @@ -170,45 +171,45 @@ typedef struct lua_TValue {
606  
607  
608  #define setpvalue(obj,x) \
609 -  { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; }
610 +  { TValue *i_o=luaV_unref(L, (obj)); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; }
611  
612  #define setbvalue(obj,x) \
613 -  { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; }
614 +  { TValue *i_o=luaV_unref(L, (obj)); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; }
615  
616  #define setsvalue(L,obj,x) \
617 -  { TValue *i_o=(obj); \
618 -    i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \
619 +  { TValue *i_o=(obj); TString *val=(x); luaS_ref(val); luaV_unref(L, obj); \
620 +    i_o->value.gc=cast(GCObject *, (val)); i_o->tt=LUA_TSTRING; \
621      checkliveness(G(L),i_o); }
622  
623  #define setuvalue(L,obj,x) \
624 -  { TValue *i_o=(obj); \
625 +  { TValue *i_o=luaV_unref(L, (obj)); \
626      i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \
627      checkliveness(G(L),i_o); }
628  
629  #define setthvalue(L,obj,x) \
630 -  { TValue *i_o=(obj); \
631 +  { TValue *i_o=luaV_unref(L, (obj)); \
632      i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \
633      checkliveness(G(L),i_o); }
634  
635  #define setclvalue(L,obj,x) \
636 -  { TValue *i_o=(obj); \
637 +  { TValue *i_o=luaV_unref(L, (obj)); \
638      i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \
639      checkliveness(G(L),i_o); }
640  
641  #define sethvalue(L,obj,x) \
642 -  { TValue *i_o=(obj); \
643 +  { TValue *i_o=luaV_unref(L, (obj)); \
644      i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \
645      checkliveness(G(L),i_o); }
646  
647  #define setptvalue(L,obj,x) \
648 -  { TValue *i_o=(obj); \
649 +  { TValue *i_o=luaV_unref(L, (obj)); \
650      i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \
651      checkliveness(G(L),i_o); }
652  
653  #define setobj(L,obj1,obj2) \
654 -  { const TValue *o2=(obj2); TValue *o1=(obj1); \
655 +  do { const TValue *o2=luaV_ref((TValue *)(obj2)); TValue *o1=luaV_unref(L, (obj1)); \
656      o1->value = o2->value; o1->tt=o2->tt; \
657 -    checkliveness(G(L),o1); }
658 +    checkliveness(G(L),o1); } while(0)
659  
660  
661  /*
662 @@ -253,6 +254,7 @@ typedef union TString {
663      lu_byte reserved;
664      unsigned int hash;
665      size_t len;
666 +    int refcount;
667    } tsv;
668  } TString;
669  
670 @@ -409,6 +411,7 @@ typedef struct Table {
671  #define twoto(x)       (1<<(x))
672  #define sizenode(t)    (twoto((t)->lsizenode))
673  
674 +#include "lstring.h"
675  
676  #define luaO_nilobject         (&luaO_nilobject_)
677  
678 --- a/src/lparser.c
679 +++ b/src/lparser.c
680 @@ -24,6 +24,7 @@
681  #include "lstate.h"
682  #include "lstring.h"
683  #include "ltable.h"
684 +#include "lvm.h"
685  
686  
687  
688 @@ -146,7 +147,7 @@ static int registerlocalvar (LexState *l
689    luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
690                    LocVar, SHRT_MAX, "too many local variables");
691    while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
692 -  f->locvars[fs->nlocvars].varname = varname;
693 +  f->locvars[fs->nlocvars].varname = luaS_ref(varname);
694    luaC_objbarrier(ls->L, f, varname);
695    return fs->nlocvars++;
696  }
697 @@ -194,7 +195,7 @@ static int indexupvalue (FuncState *fs, 
698    luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
699                    TString *, MAX_INT, "");
700    while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
701 -  f->upvalues[f->nups] = name;
702 +  f->upvalues[f->nups] = luaS_ref(name);
703    luaC_objbarrier(fs->L, f, name);
704    lua_assert(v->k == VLOCAL || v->k == VUPVAL);
705    fs->upvalues[f->nups].k = cast_byte(v->k);
706 @@ -341,7 +342,7 @@ static void open_func (LexState *ls, Fun
707    fs->nlocvars = 0;
708    fs->nactvar = 0;
709    fs->bl = NULL;
710 -  f->source = ls->source;
711 +  f->source = luaS_ref(ls->source);
712    f->maxstacksize = 2;  /* registers 0/1 are always valid */
713    fs->h = luaH_new(L, 0, 0);
714    /* anchor table of constants and prototype (to avoid being collected) */
715 --- a/src/lstate.c
716 +++ b/src/lstate.c
717 @@ -22,6 +22,7 @@
718  #include "lstring.h"
719  #include "ltable.h"
720  #include "ltm.h"
721 +#include "lvm.h"
722  
723  
724  #define state_size(x)  (sizeof(x) + LUAI_EXTRASPACE)
725 @@ -52,7 +53,7 @@ static void stack_init (lua_State *L1, l
726    L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1;
727    /* initialize first ci */
728    L1->ci->func = L1->top;
729 -  setnilvalue(L1->top++);  /* `function' entry for this `ci' */
730 +  setnilvalue(L1, L1->top++);  /* `function' entry for this `ci' */
731    L1->base = L1->ci->base = L1->top;
732    L1->ci->top = L1->top + LUA_MINSTACK;
733  }
734 @@ -98,7 +99,7 @@ static void preinit_state (lua_State *L,
735    L->base_ci = L->ci = NULL;
736    L->savedpc = NULL;
737    L->errfunc = 0;
738 -  setnilvalue(gt(L));
739 +  setnilvalue(L, gt(L));
740  }
741  
742  
743 @@ -163,7 +164,7 @@ LUA_API lua_State *lua_newstate (lua_All
744    g->strt.size = 0;
745    g->strt.nuse = 0;
746    g->strt.hash = NULL;
747 -  setnilvalue(registry(L));
748 +  setnilvalue(L, registry(L));
749    luaZ_initbuffer(L, &g->buff);
750    g->panic = NULL;
751    g->gcstate = GCSpause;
752 --- a/src/lstring.c
753 +++ b/src/lstring.c
754 @@ -37,6 +37,9 @@ void luaS_resize (lua_State *L, int news
755        int h1 = lmod(h, newsize);  /* new position */
756        lua_assert(cast_int(h%newsize) == lmod(h, newsize));
757        p->gch.next = newhash[h1];  /* chain it */
758 +      if (p->gch.next)
759 +        p->gch.next->gch.prev = p;
760 +      p->gch.prev = NULL;
761        newhash[h1] = p;
762        p = next;
763      }
764 @@ -59,11 +62,15 @@ static TString *newlstr (lua_State *L, c
765    ts->tsv.marked = luaC_white(G(L));
766    ts->tsv.tt = LUA_TSTRING;
767    ts->tsv.reserved = 0;
768 +  ts->tsv.refcount = 0;
769    memcpy(ts+1, str, l*sizeof(char));
770    ((char *)(ts+1))[l] = '\0';  /* ending 0 */
771    tb = &G(L)->strt;
772    h = lmod(h, tb->size);
773    ts->tsv.next = tb->hash[h];  /* chain new entry */
774 +  if (ts->tsv.next)
775 +    ts->tsv.next->gch.prev = (GCObject *)ts;
776 +  ts->tsv.prev = NULL;
777    tb->hash[h] = obj2gco(ts);
778    tb->nuse++;
779    if (tb->nuse > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
780 @@ -109,3 +116,29 @@ Udata *luaS_newudata (lua_State *L, size
781    return u;
782  }
783  
784 +void luaS_unref(lua_State *L, TString *ts) {
785 +  if (!L || !ts)
786 +    return;
787 +  if (testbit(ts->tsv.marked, FIXEDBIT))
788 +    return;
789 +  ts->tsv.refcount--;
790 +  if (ts->tsv.refcount < 0) {
791 +    fprintf(stderr, "REFCOUNT BUG, COUNT=%d, str=%s, len=%d\n", ts->tsv.refcount, (char *) (ts + 1), (int) ts->tsv.len);
792 +  } else if (ts->tsv.refcount)
793 +    return;
794 +
795 +  if (ts->tsv.prev) {
796 +    ts->tsv.prev->gch.next = ts->tsv.next;
797 +  } else {
798 +    unsigned int idx = lmod(ts->tsv.hash, G(L)->strt.size);
799 +    lua_assert(G(L)->strt.hash[index] == (GCObject*)ts);
800 +    G(L)->strt.hash[idx] = ts->tsv.next;
801 +  }
802 +
803 +  if (ts->tsv.next)
804 +    ts->tsv.next->gch.prev = ts->tsv.prev;
805 +
806 +  luaC_freeobj(L, (GCObject *) ts);
807 +}
808 +
809 +
810 --- a/src/lstring.h
811 +++ b/src/lstring.h
812 @@ -7,7 +7,7 @@
813  #ifndef lstring_h
814  #define lstring_h
815  
816 -
817 +#include <stdio.h>
818  #include "lgc.h"
819  #include "lobject.h"
820  #include "lstate.h"
821 @@ -23,6 +23,12 @@
822  
823  #define luaS_fix(s)    l_setbit((s)->tsv.marked, FIXEDBIT)
824  
825 +static inline TString *luaS_ref(TString *ts) {
826 +  ts->tsv.refcount++;
827 +  return ts;
828 +}
829 +
830 +LUA_API void luaS_unref(lua_State *L, TString *ts);
831  LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
832  LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
833  LUA_API TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
834 --- a/src/ltable.c
835 +++ b/src/ltable.c
836 @@ -34,6 +34,7 @@
837  #include "lstate.h"
838  #include "ltable.h"
839  #include "lnum.h"
840 +#include "lvm.h"
841  
842  
843  /*
844 @@ -278,7 +279,7 @@ static void setarrayvector (lua_State *L
845    int i;
846    luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
847    for (i=t->sizearray; i<size; i++)
848 -     setnilvalue(&t->array[i]);
849 +     setnilvalue(L, &t->array[i]);
850    t->sizearray = size;
851  }
852  
853 @@ -299,8 +300,8 @@ static void setnodevector (lua_State *L,
854      for (i=0; i<size; i++) {
855        Node *n = gnode(t, i);
856        gnext(n) = NULL;
857 -      setnilvalue(gkey(n));
858 -      setnilvalue(gval(n));
859 +      setnilvalue(L, gkey(n));
860 +      setnilvalue(L, gval(n));
861      }
862    }
863    t->lsizenode = cast_byte(lsize);
864 @@ -427,9 +428,11 @@ static TValue *newkey (lua_State *L, Tab
865          othern = gnext(othern);  /* find previous */
866        }
867        gnext(othern) = n;  /* redo the chain with `n' in place of `mp' */
868 +      luaV_ref((TValue *) gkey(mp));
869 +      luaV_ref(gval(mp));
870        *n = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
871        gnext(mp) = NULL;  /* now `mp' is free */
872 -      setnilvalue(gval(mp));
873 +      setnilvalue(L, gval(mp));
874      }
875      else {  /* colliding node is in its own main position */
876        /* new node will go into free position */
877 @@ -438,6 +441,7 @@ static TValue *newkey (lua_State *L, Tab
878        mp = n;
879      }
880    }
881 +  luaV_ref((TValue *) key);
882    gkey(mp)->value = key->value; gkey(mp)->tt = key->tt;
883    luaC_barriert(L, t, key);
884    lua_assert(ttisnil(gval(mp)));
885 @@ -530,7 +534,7 @@ TValue *luaH_setint (lua_State *L, Table
886    if (p != luaO_nilobject)
887      return cast(TValue *, p);
888    else {
889 -    TValue k;
890 +    TValue k = tvinit();
891      setivalue(&k, key);
892      return newkey(L, t, &k);
893    }
894 @@ -542,7 +546,7 @@ TValue *luaH_setstr (lua_State *L, Table
895    if (p != luaO_nilobject)
896      return cast(TValue *, p);
897    else {
898 -    TValue k;
899 +    TValue k = tvinit();
900      setsvalue(L, &k, key);
901      return newkey(L, t, &k);
902    }
903 --- a/src/luac.c
904 +++ b/src/luac.c
905 @@ -20,8 +20,9 @@
906  #include "lmem.h"
907  #include "lobject.h"
908  #include "lopcodes.h"
909 -#include "lstring.h"
910  #include "lundump.h"
911 +#include "lvm.h"
912 +#include "lstring.h"
913  
914  #define PROGNAME       "luac"          /* default program name */
915  #define        OUTPUT          PROGNAME ".out" /* default output file */
916 --- a/src/lundump.c
917 +++ b/src/lundump.c
918 @@ -19,6 +19,7 @@
919  #include "lstring.h"
920  #include "lundump.h"
921  #include "lzio.h"
922 +#include "lvm.h"
923  
924  typedef struct {
925   lua_State* L;
926 @@ -133,7 +134,7 @@ static TString* LoadString(LoadState* S)
927   {
928    char* s=luaZ_openspace(S->L,S->b,size);
929    LoadBlock(S,s,size);
930 -  return luaS_newlstr(S->L,s,size-1);          /* remove trailing '\0' */
931 +  return luaS_ref(luaS_newlstr(S->L,s,size-1));                /* remove trailing '\0' */
932   }
933  }
934  
935 @@ -149,11 +150,12 @@ static Proto* LoadFunction(LoadState* S,
936  
937  static void LoadConstants(LoadState* S, Proto* f)
938  {
939 + lua_State *L = S->L;
940   int i,n;
941   n=LoadInt(S);
942   f->k=luaM_newvector(S->L,n,TValue);
943   f->sizek=n;
944 - for (i=0; i<n; i++) setnilvalue(&f->k[i]);
945 + for (i=0; i<n; i++) setnilvalue(L, &f->k[i]);
946   for (i=0; i<n; i++)
947   {
948    TValue* o=&f->k[i];
949 @@ -161,7 +163,7 @@ static void LoadConstants(LoadState* S, 
950    switch (t)
951    {
952     case LUA_TNIL:
953 -       setnilvalue(o);
954 +       setnilvalue(L, o);
955         break;
956     case LUA_TBOOLEAN:
957         setbvalue(o,LoadChar(S)!=0);
958 @@ -229,6 +231,7 @@ static Proto* LoadFunction(LoadState* S,
959   LoadDebug(S,f);
960   IF (!luaG_checkcode(f), "bad code");
961   S->L->top--;
962 + setnilvalue(S->L, S->L->top);
963   S->L->nCcalls--;
964   return f;
965  }
966 --- a/src/lvm.c
967 +++ b/src/lvm.c
968 @@ -39,6 +39,7 @@
969   * If 'obj' is a string, it is tried to be interpreted as a number.
970   */
971  const TValue *luaV_tonumber ( const TValue *obj, TValue *n) {
972 +  lua_State *L = NULL; /* FIXME */
973    lua_Number d;
974    lua_Integer i;
975    
976 @@ -384,6 +385,7 @@ void luaV_concat (lua_State *L, int tota
977          size_t l = tsvalue(top-i)->len;
978          memcpy(buffer+tl, svalue(top-i), l);
979          tl += l;
980 +               setnilvalue(L, top - i);
981        }
982        setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
983      }
984 @@ -420,7 +422,7 @@ void luaV_concat (lua_State *L, int tota
985   */
986  static void Arith (lua_State *L, StkId ra, const TValue *rb,
987                     const TValue *rc, TMS op) {
988 -  TValue tempb, tempc;
989 +  TValue tempb = tvinit(), tempc = tvinit();
990    const TValue *b, *c;
991    lua_Number nb,nc;
992  
993 @@ -663,7 +665,7 @@ void luaV_execute (lua_State *L, int nex
994        OPCODE_TARGET(LOADNIL) {
995          TValue *rb = RB(i);
996          do {
997 -          setnilvalue(rb--);
998 +          setnilvalue(L, rb--);
999          } while (rb >= ra);
1000          continue;
1001        }
1002 @@ -673,7 +675,7 @@ void luaV_execute (lua_State *L, int nex
1003          continue;
1004        }
1005        OPCODE_TARGET(GETGLOBAL) {
1006 -        TValue g;
1007 +        TValue g = tvinit();
1008          TValue *rb = KBx(i);
1009          sethvalue(L, &g, cl->env);
1010          lua_assert(ttisstring(rb));
1011 @@ -685,7 +687,7 @@ void luaV_execute (lua_State *L, int nex
1012          continue;
1013        }
1014        OPCODE_TARGET(SETGLOBAL) {
1015 -        TValue g;
1016 +        TValue g = tvinit();
1017          sethvalue(L, &g, cl->env);
1018          lua_assert(ttisstring(KBx(i)));
1019          Protect(luaV_settable(L, &g, KBx(i), ra));
1020 @@ -895,7 +897,7 @@ void luaV_execute (lua_State *L, int nex
1021          if (--nexeccalls == 0)  /* was previous function running `here'? */
1022            return;  /* no: return */
1023          else {  /* yes: continue its execution */
1024 -          if (b) L->top = L->ci->top;
1025 +          if (b) setlvmtop(L, L->ci->top);
1026            lua_assert(isLua(L->ci));
1027            lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL);
1028            goto reentry;
1029 @@ -986,6 +988,7 @@ void luaV_execute (lua_State *L, int nex
1030          for (; n > 0; n--) {
1031            TValue *val = ra+n;
1032            setobj2t(L, luaH_setint(L, h, last--), val);
1033 +          setnilvalue(L, val);
1034            luaC_barriert(L, h, val);
1035          }
1036          continue;
1037 @@ -1030,7 +1033,7 @@ void luaV_execute (lua_State *L, int nex
1038              setobjs2s(L, ra + j, ci->base - n + j);
1039            }
1040            else {
1041 -            setnilvalue(ra + j);
1042 +            setnilvalue(L, ra + j);
1043            }
1044          }
1045          continue;
1046 --- a/src/lvm.h
1047 +++ b/src/lvm.h
1048 @@ -11,6 +11,7 @@
1049  #include "ldo.h"
1050  #include "lobject.h"
1051  #include "ltm.h"
1052 +#include "lstring.h"
1053  
1054  
1055  #define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o)))
1056 @@ -19,6 +20,19 @@
1057  
1058  #define equalobj(L,o1,o2) (ttype_ext_same(o1,o2) && luaV_equalval(L, o1, o2))
1059  
1060 +static inline TValue *luaV_ref(TValue *tv)
1061 +{
1062 +  if (ttisstring(tv))
1063 +    luaS_ref(rawtsvalue(tv));
1064 +  return tv;
1065 +}
1066 +
1067 +static inline TValue *luaV_unref(lua_State *L, TValue *tv)
1068 +{
1069 +  if (ttisstring(tv))
1070 +    luaS_unref(L, rawtsvalue(tv));
1071 +  return tv;
1072 +}
1073  
1074  LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
1075  LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2);
1076 --- a/src/llex.c
1077 +++ b/src/llex.c
1078 @@ -23,6 +23,7 @@
1079  #include "ltable.h"
1080  #include "lzio.h"
1081  #include "lnum.h"
1082 +#include "lvm.h"
1083  
1084  
1085  
1086 @@ -69,7 +70,7 @@ static void save (LexState *ls, int c) {
1087  void luaX_init (lua_State *L) {
1088    int i;
1089    for (i=0; i<NUM_RESERVED; i++) {
1090 -    TString *ts = luaS_new(L, luaX_tokens[i]);
1091 +    TString *ts = luaS_ref(luaS_new(L, luaX_tokens[i]));
1092      luaS_fix(ts);  /* reserved words are never collected */
1093      lua_assert(strlen(luaX_tokens[i])+1 <= TOKEN_LEN);
1094      ts->tsv.reserved = cast_byte(i+1);  /* reserved word */
1095 @@ -125,7 +126,7 @@ void luaX_syntaxerror (LexState *ls, con
1096  
1097  TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
1098    lua_State *L = ls->L;
1099 -  TString *ts = luaS_newlstr(L, str, l);
1100 +  TString *ts = luaS_ref(luaS_newlstr(L, str, l));
1101    TValue *o = luaH_setstr(L, ls->fs->h, ts);  /* entry for `str' */
1102    if (ttisnil(o))
1103      setbvalue(o, 1);  /* make sure `str' will not be collected */
1104 @@ -152,7 +153,7 @@ void luaX_setinput (lua_State *L, LexSta
1105    ls->fs = NULL;
1106    ls->linenumber = 1;
1107    ls->lastline = 1;
1108 -  ls->source = source;
1109 +  ls->source = luaS_ref(source);
1110    luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);  /* initialize buffer */
1111    next(ls);  /* read first char */
1112  }
1113 --- a/src/lstate.h
1114 +++ b/src/lstate.h
1115 @@ -144,6 +144,13 @@ union GCObject {
1116    struct lua_State th;  /* thread */
1117  };
1118  
1119 +#define setlvmtop(L, val) do { \
1120 +       int __i; \
1121 +       for (__i = L->top - val; __i-- > 0;) \
1122 +               setnilvalue(L, val + __i); \
1123 +       L->top = val; \
1124 +} while (0)
1125 +
1126  
1127  /* macros to convert a GCObject into a specific value */
1128  #define rawgco2ts(o)   check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts))