Skip to content

Free the non-blocking error array before a raise - #613

Open
navidemad wants to merge 2 commits into
rails-sqlserver:masterfrom
navidemad:fix-nonblocking-errors-leak
Open

navidemad wants to merge 2 commits into
rails-sqlserver:masterfrom
navidemad:fix-nonblocking-errors-leak

Conversation

@navidemad

@navidemad navidemad commented Oct 15, 2026 •

Copy link
Copy Markdown

Problem

nogvl_cleanup raises the first SQL Server error with rb_exc_raise. A raise from C is a longjmp: it leaves the function at once. Thus the free(userdata->nonblocking_errors) call after the loop does not run.

nogvl_setup allocates this array with malloc for ERRORS_STACK_INIT_SIZE errors. The array is 4,136 bytes on 64-bit Linux. Each query that fails leaks one array, because the next nogvl_setup call replaces the pointer.

Fix

  1. Copy the collected errors into a buffer that Ruby manages (RB_ALLOCV_N).
  2. Free the malloc array and reset its fields.
  3. Process the copy as before: call the message handler for info messages, then raise the first error.

RB_ALLOCV_N registers the copy with the GC. If the message handler or the raise leaves the function before RB_ALLOCV_END, the GC frees the copy. The order of the messages does not change. The raised exception does not change.

Measurements

The tool is ruby_memcheck 3.0.1. It runs Ruby under Valgrind and removes the false positives that Ruby causes. A "definitely lost" block is a block with no pointer to it at exit.

Failing queries master This PR