Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@

### Fixed

- Closing a re-import session after a call timed out could wait behind the
Python code that was still running. After five seconds the session and its
linked owner were killed. Closing now returns without waiting for Python,
and its state is freed after the running call finishes.
- Shared dictionaries could deadlock the node when Erlang and Python used
one at the same time, or when pickling a value accessed the same dictionary.
Their stored values are now independent of any Python interpreter, so they
also work safely from `owngil` contexts. Native buffers, channels and event
loops now clean up safely when construction stops partway through instead
of freeing or destroying the same resource state twice. Oversized buffers,
callback frames and internal tables now fail instead of wrapping their
lengths or growing forever.
- On an owngil context, the process-local environment of an Erlang process
(`py:call/eval/exec` on the context) was kept until the context stopped:
300 short-lived processes each leaving 1 MB grew the node by 300 MB. The
Expand Down
26 changes: 21 additions & 5 deletions c_src/py_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,14 @@ void py_buffer_resource_dtor(ErlNifEnv *env, void *obj) {
(void)env;
py_buffer_resource_t *buf = (py_buffer_resource_t *)obj;

pthread_mutex_destroy(&buf->mutex);
pthread_cond_destroy(&buf->data_ready);
if (buf->cond_initialized) {
pthread_cond_destroy(&buf->data_ready);
buf->cond_initialized = false;
}
if (buf->mutex_initialized) {
pthread_mutex_destroy(&buf->mutex);
buf->mutex_initialized = false;
}

if (buf->data != NULL) {
enif_free(buf->data);
Expand All @@ -94,6 +100,7 @@ py_buffer_resource_t *py_buffer_alloc(ssize_t content_length) {
if (resource == NULL) {
return NULL;
}
memset(resource, 0, sizeof(*resource));

/* Determine initial capacity */
size_t capacity;
Expand All @@ -118,17 +125,16 @@ py_buffer_resource_t *py_buffer_alloc(ssize_t content_length) {
resource->view_count = 0;

if (pthread_mutex_init(&resource->mutex, NULL) != 0) {
enif_free(resource->data);
enif_release_resource(resource);
return NULL;
}
resource->mutex_initialized = true;

if (pthread_cond_init(&resource->data_ready, NULL) != 0) {
pthread_mutex_destroy(&resource->mutex);
enif_free(resource->data);
enif_release_resource(resource);
return NULL;
}
resource->cond_initialized = true;

return resource;
}
Expand Down Expand Up @@ -163,6 +169,10 @@ int py_buffer_write(py_buffer_resource_t *buf, const unsigned char *data, size_t
/* Calculate new capacity */
size_t new_capacity = buf->capacity;
while (new_capacity < required) {
if (new_capacity > SIZE_MAX / PY_BUFFER_GROW_FACTOR) {
pthread_mutex_unlock(&buf->mutex);
return -1;
}
new_capacity *= PY_BUFFER_GROW_FACTOR;
}

Expand Down Expand Up @@ -601,6 +611,12 @@ static PyObject *PyBuffer_readlines(PyBufferObject *self, PyObject *args) {
}
Py_DECREF(line);

if (line_len > PY_SSIZE_T_MAX - total_size) {
Py_DECREF(empty_args);
Py_DECREF(lines);
PyErr_SetString(PyExc_OverflowError, "readlines result is too large");
return NULL;
}
total_size += line_len;

/* Check hint */
Expand Down
2 changes: 2 additions & 0 deletions c_src/py_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ typedef struct {
ssize_t content_length; /**< Expected total size, -1 for chunked */
pthread_mutex_t mutex; /**< Mutex for thread-safe access */
pthread_cond_t data_ready; /**< Condition for blocking reads */
bool mutex_initialized; /**< Partial-construction guard */
bool cond_initialized; /**< Partial-construction guard */
bool eof; /**< End of data flag (close called) */
bool closed; /**< Buffer closed flag */
int view_count; /**< Active Python buffer view count */
Expand Down
72 changes: 44 additions & 28 deletions c_src/py_callback.c
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,15 @@ static void cleanup_callback_registry(void) {
* @param kwargs_term Original kwargs term
* @return suspended_context_state_t* or NULL on error
*/
static void release_failed_suspended_context_state(
suspended_context_state_t *state) {
/* Constructors run with the owning interpreter's GIL. Clear the Python
* reference here because the resource destructor may run on a scheduler
* thread whose current thread state belongs to another interpreter. */
Py_CLEAR(state->callback_args);
enif_release_resource(state);
}

static suspended_context_state_t *create_suspended_context_state_for_call(
ErlNifEnv *env,
py_context_t *ctx,
Expand All @@ -377,6 +386,7 @@ static suspended_context_state_t *create_suspended_context_state_for_call(

/* Initialize to zero */
memset(state, 0, sizeof(suspended_context_state_t));
atomic_fetch_add(&g_counters.suspended_created, 1);

state->ctx = ctx;
enif_keep_resource(ctx); /* Keep ctx alive while suspended state exists */
Expand All @@ -390,7 +400,7 @@ static suspended_context_state_t *create_suspended_context_state_for_call(
/* Copy callback function name */
state->callback_func_name = enif_alloc(tl_pending_func_name_len + 1);
if (state->callback_func_name == NULL) {
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}
memcpy(state->callback_func_name, tl_pending_func_name, tl_pending_func_name_len);
Expand All @@ -404,29 +414,20 @@ static suspended_context_state_t *create_suspended_context_state_for_call(
/* Create environment to hold copied terms */
state->orig_env = enif_alloc_env();
if (state->orig_env == NULL) {
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}

/* Copy module binary */
if (!enif_alloc_binary(module_bin->size, &state->orig_module)) {
enif_free_env(state->orig_env);
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}
memcpy(state->orig_module.data, module_bin->data, module_bin->size);

/* Copy function binary */
if (!enif_alloc_binary(func_bin->size, &state->orig_func)) {
enif_release_binary(&state->orig_module);
enif_free_env(state->orig_env);
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}
memcpy(state->orig_func.data, func_bin->data, func_bin->size);
Expand All @@ -435,7 +436,6 @@ static suspended_context_state_t *create_suspended_context_state_for_call(
state->orig_args = enif_make_copy(state->orig_env, args_term);
state->orig_kwargs = enif_make_copy(state->orig_env, kwargs_term);

atomic_fetch_add(&g_counters.suspended_created, 1);
return state;
}

Expand Down Expand Up @@ -469,6 +469,7 @@ static suspended_context_state_t *create_suspended_context_state_for_eval(

/* Initialize to zero */
memset(state, 0, sizeof(suspended_context_state_t));
atomic_fetch_add(&g_counters.suspended_created, 1);

state->ctx = ctx;
enif_keep_resource(ctx); /* Keep ctx alive while suspended state exists */
Expand All @@ -482,7 +483,7 @@ static suspended_context_state_t *create_suspended_context_state_for_eval(
/* Copy callback function name */
state->callback_func_name = enif_alloc(tl_pending_func_name_len + 1);
if (state->callback_func_name == NULL) {
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}
memcpy(state->callback_func_name, tl_pending_func_name, tl_pending_func_name_len);
Expand All @@ -496,26 +497,20 @@ static suspended_context_state_t *create_suspended_context_state_for_eval(
/* Create environment to hold copied terms */
state->orig_env = enif_alloc_env();
if (state->orig_env == NULL) {
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}

/* Copy code binary */
if (!enif_alloc_binary(code_bin->size, &state->orig_code)) {
enif_free_env(state->orig_env);
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
release_failed_suspended_context_state(state);
return NULL;
}
memcpy(state->orig_code.data, code_bin->data, code_bin->size);

/* Copy locals to our environment */
state->orig_locals = enif_make_copy(state->orig_env, locals_term);

atomic_fetch_add(&g_counters.suspended_created, 1);
return state;
}

Expand All @@ -535,7 +530,12 @@ static ERL_NIF_TERM build_suspended_context_result(ErlNifEnv *env, suspended_con

ERL_NIF_TERM func_name_term;
unsigned char *fn_buf = enif_make_new_binary(env, tl_pending_func_name_len, &func_name_term);
memcpy(fn_buf, tl_pending_func_name, tl_pending_func_name_len);
if (fn_buf == NULL && tl_pending_func_name_len > 0) {
return make_error(env, "alloc_failed");
}
if (tl_pending_func_name_len > 0) {
memcpy(fn_buf, tl_pending_func_name, tl_pending_func_name_len);
}

ERL_NIF_TERM args_term = py_to_term(env, tl_pending_args);

Expand Down Expand Up @@ -1801,7 +1801,13 @@ static PyObject *erlang_call_impl(PyObject *self, PyObject *args) {
ERL_NIF_TERM func_term;
{
unsigned char *buf = enif_make_new_binary(msg_env, func_name_len, &func_term);
memcpy(buf, func_name, func_name_len);
if (buf == NULL && func_name_len > 0) {
enif_free_env(msg_env);
Py_DECREF(call_args);
PyErr_SetString(PyExc_MemoryError, "Failed to allocate callback name");
return NULL;
}
if (func_name_len > 0) memcpy(buf, func_name, func_name_len);
}

ERL_NIF_TERM args_term = py_to_term(msg_env, call_args);
Expand Down Expand Up @@ -2043,6 +2049,7 @@ typedef struct {
* insert under the lock.
*/
pthread_mutex_t async_futures_mutex;
bool async_futures_mutex_initialized;
bool pipe_initialized;

/* Set on hard read error (EIO/EBADF/EOF mid-frame). New
Expand Down Expand Up @@ -3438,8 +3445,10 @@ static void erlang_module_free(void *module) {
Py_XDECREF(state->async_pending_futures);
state->async_pending_futures = NULL;

/* Always destroy mutex - it was always initialized in create_erlang_module */
pthread_mutex_destroy(&state->async_futures_mutex);
if (state->async_futures_mutex_initialized) {
pthread_mutex_destroy(&state->async_futures_mutex);
state->async_futures_mutex_initialized = false;
}
state->pipe_initialized = false;
}

Expand Down Expand Up @@ -3518,7 +3527,14 @@ static int create_erlang_module(void) {
state->async_callback_pipe[0] = -1;
state->async_callback_pipe[1] = -1;
state->async_pending_futures = NULL;
pthread_mutex_init(&state->async_futures_mutex, NULL);
state->async_futures_mutex_initialized = false;
if (pthread_mutex_init(&state->async_futures_mutex, NULL) != 0) {
Py_DECREF(module);
PyErr_SetString(PyExc_RuntimeError,
"failed to initialize async callback mutex");
return -1;
}
state->async_futures_mutex_initialized = true;
state->pipe_initialized = false;
}

Expand Down
26 changes: 18 additions & 8 deletions c_src/py_channel.c
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,15 @@ void channel_resource_dtor(ErlNifEnv *env, void *obj) {
}

/* Wake any threads waiting on the condition before destroying */
pthread_cond_broadcast(&channel->data_cond);
pthread_cond_destroy(&channel->data_cond);
pthread_mutex_destroy(&channel->mutex);
if (channel->cond_initialized) {
pthread_cond_broadcast(&channel->data_cond);
pthread_cond_destroy(&channel->data_cond);
channel->cond_initialized = false;
}
if (channel->mutex_initialized) {
pthread_mutex_destroy(&channel->mutex);
channel->mutex_initialized = false;
}
}

py_channel_t *channel_alloc(size_t max_size) {
Expand All @@ -85,6 +91,7 @@ py_channel_t *channel_alloc(size_t max_size) {
if (channel == NULL) {
return NULL;
}
memset(channel, 0, sizeof(*channel));

channel->queue = enif_ioq_create(ERL_NIF_IOQ_NORMAL);
if (channel->queue == NULL) {
Expand All @@ -103,17 +110,16 @@ py_channel_t *channel_alloc(size_t max_size) {
channel->channel_id = atomic_fetch_add(&g_channel_id_counter, 1);

if (pthread_mutex_init(&channel->mutex, NULL) != 0) {
enif_ioq_destroy(channel->queue);
enif_release_resource(channel);
return NULL;
}
channel->mutex_initialized = true;

if (pthread_cond_init(&channel->data_cond, NULL) != 0) {
pthread_mutex_destroy(&channel->mutex);
enif_ioq_destroy(channel->queue);
enif_release_resource(channel);
return NULL;
}
channel->cond_initialized = true;

return channel;
}
Expand All @@ -127,7 +133,9 @@ int channel_send(py_channel_t *channel, const unsigned char *data, size_t size)
}

/* Check backpressure */
if (channel->max_size > 0 && channel->current_size + size > channel->max_size) {
if (size > SIZE_MAX - channel->current_size ||
(channel->max_size > 0 &&
channel->current_size + size > channel->max_size)) {
pthread_mutex_unlock(&channel->mutex);
return 1; /* Busy - backpressure */
}
Expand Down Expand Up @@ -211,7 +219,9 @@ int channel_send_owned_binary(py_channel_t *channel, ErlNifBinary *bin) {
}

/* Check backpressure */
if (channel->max_size > 0 && channel->current_size + bin->size > channel->max_size) {
if (bin->size > SIZE_MAX - channel->current_size ||
(channel->max_size > 0 &&
channel->current_size + bin->size > channel->max_size)) {
enif_release_binary(bin);
pthread_mutex_unlock(&channel->mutex);
return 1; /* Busy - backpressure */
Expand Down
4 changes: 4 additions & 0 deletions c_src/py_channel.h
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ typedef struct {
/** @brief Condition variable for blocking receives */
pthread_cond_t data_cond;

/** @brief Partial-construction guards for synchronization objects */
bool mutex_initialized;
bool cond_initialized;

/** @brief Event loop for async waiter (ref-counted via enif_keep_resource) */
struct erlang_event_loop *waiter_loop;

Expand Down
Loading
Loading