[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Why is "gc" tag method restricted to userdata?
- From: Roberto Ierusalimschy <roberto@...>
- Date: Mon, 09 Oct 2000 10:31:02 -0200
> For example, this is what is in the manual about the foreach construct :
> "The behavior of foreach is undefined if you change the table _t during the
> traversal." Similar wording is enough to warn programmers of the potential
> dangers.
One of our "golden rules" about Lua is that the language should be
"secure"; more specifically, it should not be possible to crash a program
from Lua, no matter what you do. The undefined behavior in a traversal is
not insecure; it is only undefined. A mistake (or a misuse) in a garbage
collection function, on the other hand, can crash the whole program.
Maybe worse, the old conditions (that is, Lua 3.2) for "correct use" of a
garbage collection function were quite subtle. As you said, it is quite
obvious that you want access to the fields of the table when the table is
being collected. However, when the table is being collected, both value and
key fields may be being collected too. Suppose this weird situation: a
table has a field called "foof", and this string does not appear in any
part of your Lua program (for instance, the field was created by C code).
Then, when the table is collected, the string "foof" will also be
collected. But, at the garbage-collection function (also written in C), you
have a lua_pushstring("foof") (to access the field). Because Lua unifies
identical strings, there are two options: this new foof is a string
different from the one being collected (and therefore you will not be able
to access that field), or this new foof is the same string being collected
(and therefore there is a mess, because a string marked to "die" goes back
to the active pool).
I agree that this is a rather uncommon situation (mainly because usually a
field name such as "foof" would appear as a literal in some part of your
program, and therefore it wouldn't be collected), but it is not
intentional, and it can lead to some very subtle bugs in your program.
We did try to prevent such events until Lua 3.2: the gargabe collection
algorithm ran in three phases: first it collected the garbage, then it
called all tag methods, and finally it released the garbage. But we always
found some situations that would break it.
-- Roberto