Factored out C stack querying/checking framework

Adds control of recursion limit, to avoid segfaults.