lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Jun 25, 2019 at 3:15 PM Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:

> Problem solved?

Not, I am afraid. The block of questions that you quoted and apparently intended to answer was about solving the problem within the library code.

> Too hard?

Given your response, I am tempted to say that it is. Why, indeed, are you suggesting a workaround in the user code rather than a fix in the library?

My personal take is that it is too hard, too. Conceptually, the cleanup required by the C library before a userdatum is freed is its internal implementation detail. However, the requirement to use the metatable mechanism for this leaks the implementation detail out, where it becomes a vulnerability. At this point the fact may not even be understood by the library's author, or found easier to ignore because it seems surprisingly nasty to deal with properly.

Note that the other methods that are defined in a metatable are not exactly in the same league. Unlike __gc, which is an implementation detail, they are usually a public interface, tampering with which is more likely to make the userdatum unusable (for the user) than to break the implementation.

With this in mind, the following extension might be considered: introduce C API to get/set/reset a "cleanup" callback for a userdatum, which is a C function accepting a pointer to the userdatum. The callback is called immediately before the userdatum is freed (after the (optional) __gc finalizer runs), so no complications related to marking userdata for finalziation and resurrection. This is fully compatible with the existing code (__gc still works), and it seems that many C libraries will only need this callback rather than __gc, this callback is not leaked through the public interface, it even seems simpler in use for a C programmer, and the C library's author is freed from having to think about protecting it from the user code, and from having to come up with excuses for not doing so.

Cheers,
V.