Skip to content

sqlite3: set_trace_callback/set_progress_handler/set_authorizer race conditions free-threaded build #162299

Open

Description

@johng

Bug report

The three mentioned callback contexts have no syncronisation such that on free threading builds we can see double decref or a use after free.

// Modules/_sqlite/connection.c
static void
set_callback_context(callback_context **ctx_pp, callback_context *ctx)
{
    callback_context *tmp = *ctx_pp;
    *ctx_pp = ctx;
    if (tmp != NULL) {
        decref_callback_context(tmp);
    }
}

This small reproduction reliably crashes even on standard free-threaded build

import sqlite3
import sys
import threading

cx = sqlite3.connect(":memory:", check_same_thread=False)
cb = lambda *args: 0

setters = {
    "trace": lambda: cx.set_trace_callback(cb),
    "progress": lambda: cx.set_progress_handler(cb, 1),
    "authorizer": lambda: cx.set_authorizer(cb),
}
set_callback = setters[sys.argv[1] if len(sys.argv) > 1 else "trace"]

def setter():
    for _ in range(20000):
        set_callback()

def user():
    for _ in range(2000):
        cx.execute("select 1").fetchall()

threads = [threading.Thread(target=setter) for _ in range(4)]
threads.append(threading.Thread(target=user))
for t in threads:
    t.start()
for t in threads:
    t.join()
print("no crash")

From what I could see there's no an open issue for this!

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions