Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixing race condition in PyFunctionObject.func_code
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should be less precise in terms of implementation and rather mention __func__.__code__ directly.

10 changes: 7 additions & 3 deletions Objects/funcobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -631,7 +631,8 @@ func_get_code(PyObject *self, void *Py_UNUSED(ignored))
return NULL;
}

return Py_NewRef(op->func_code);
PyCodeObject *code = _Py_atomic_load_ptr(&op->func_code);
Comment thread
Krishna-web-hub marked this conversation as resolved.
return Py_NewRef(code);
Comment on lines +634 to +635
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't right.

code might have been deallocated by the time you do Py_NewRef

}

static int
Expand Down Expand Up @@ -664,7 +665,7 @@ func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
return -1;
}

PyObject *func_code = PyFunction_GET_CODE(op);
PyCodeObject *func_code = _Py_atomic_load_ptr(&op->func_code);
Comment thread
Krishna-web-hub marked this conversation as resolved.
Outdated
int old_flags = ((PyCodeObject *)func_code)->co_flags;
int new_flags = ((PyCodeObject *)value)->co_flags;
int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
Expand All @@ -679,7 +680,10 @@ func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))

handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_code, Py_NewRef(value));
PyCodeObject *new = (PyCodeObject *)Py_NewRef(value);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be GIL_DISABLED-guarded

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, don't we have a FT-helper alterantive to Py_XSETREF?

PyCodeObject *old =
(PyCodeObject *)_Py_atomic_exchange_ptr(&op->func_code, new);
Py_XDECREF(old);
return 0;
}

Expand Down
Loading