Subject: Re: bug#75322: SAFE_ALLOCA assumed to root Lisp_Objects/SSDATA(string)

From: Daniel Colascione <[email-masked]>
Date: Mon, 06 Jan 2025 10:08:49 -0500

On January 6, 2025 8:26:15 AM EST, Eli Zaretskii <[email-masked]> wrote:
>> From: Daniel Colascione <[email-masked]>
>> Cc: [email-masked],  [email-masked],  [email-masked]
>> Date: Sun, 05 Jan 2025 18:28:59 -0500
>> 
>> Daniel Colascione <[email-masked]> writes:
>> 
>> Here's a demonstration of the problem.  Run ./emacs -batch -Q --eval
>> '(acos 0)'.  If you leave demo_crash to true, Emacs will abort quickly
>> after we detect a use-after-free.  If you set demo_crash to false, Emacs
>> will run the loop all day.
>
>It is a well-known fact that inserting Fgarbage_collect in various
>random places can cause bugs. 

It's not a "random place". It's demonstrating an unsafe pattern.

> But expecting every Emacs C-level
>hacker to write code that will endure such testing is impractical.  

If someone can't write safe Emacs C code, he shouldn't be writing Emacs C code at all. It is  reasonable to expect people to follow the rules.

Most new features should be in Lisp and changes to C code should be in service of making it possible to put more logic in Lisp.

> We
>routinely let much more easily-spotted blunders slip though.  The
>sheer number of subtleties and factoids you need to keep in mind when
>writing safe code in Emacs is already inhumanly large.

Yes. It's hard enough to write C code as it is. That's why people need to write C code with clear and simple bright-line rules on memory safety. For example, instead of thinking about whether this or that function scope Lisp_Object is safe, just ban function scope Lisp_Object static variables generally. Much lower cognitive burden this way.

>We only get away because there are many places where GC cannot happen.

We also get away with a lot because the old GC is non-moving. The things we get away with are fragile whether or not the old GC being forgiving makes them technically safe.

>Admittedly, with the proliferation of calls into Lisp, there's less
>and less of these places each year.

Yes, which is why it's best to make code GC safe in general. Just like we don't have to sprinkle the register keyword around anymore, we don't have to try to get clever and avoid having to gcpro this or that thing. Protect all the things. Simple and robust.