Subject: Re: bug#60237: 30.0.50; tree sitter core dumps when I edebug view a node

From: Yuan Fu <[email-masked]>
Date: Sat, 25 Feb 2023 18:01:07 -0800

> GC has historically never called xmalloc, so the profiler will likely
> crash upon growing the mark stack as well.  I guess another important
> question is why ts_delete_parser is calling xmalloc.
> 

> As you see, when we call ts_tree_delete, it calls ts_subtree_release,
> which in turn calls malloc (redirected into our xmalloc).  Is this
> expected?  Can you look in the tree-sitter sources and verify that
> this is OK?

I had a look, and it seems legit. In tree-sitter, a TSTree (or more precisely, a Subtree) is just some inlined data plus a refcounted pointer to the complete data. This way multiple trees share common subtrees/nodes. Eg, when incrementally parsing, you pass in an old tree and get a new tree, these two trees will share the unchanged part of the tree. 

Therefore, deleting a tree is not simply free(). Instead, you decrement the refcount of the subtree, and if the count == 0, free the data and traverse the subtree and decrementing each children’s refcount, and delete them if the count == 0, and so on. To traverse the tree, the function uses an array as a stack, which calls array_push to push new elements, which may call malloc.

Yuan