Skip to content

Commit

Permalink
Merge pull request python-pillow#8496 from lysnikolaou/fix-font-face-…
Browse files Browse the repository at this point in the history
…threading-crash

Fix SEGFAULT from calling FT_New_Face/FT_Done_Face in multiple threads
  • Loading branch information
radarhere authored Oct 26, 2024
2 parents 29cdbce + bb3515d commit 9a4b3e0
Show file tree
Hide file tree
Showing 2 changed files with 349 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/_imagingft.c
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ struct {
/* font objects */

static FT_Library library;
#ifdef Py_GIL_DISABLED
static PyMutex ft_library_mutex;
#endif

typedef struct {
PyObject_HEAD FT_Face face;
Expand Down Expand Up @@ -187,7 +190,9 @@ getfont(PyObject *self_, PyObject *args, PyObject *kw) {

if (filename && font_bytes_size <= 0) {
self->font_bytes = NULL;
MUTEX_LOCK(&ft_library_mutex);
error = FT_New_Face(library, filename, index, &self->face);
MUTEX_UNLOCK(&ft_library_mutex);
} else {
/* need to have allocated storage for font_bytes for the life of the object.*/
/* Don't free this before FT_Done_Face */
Expand All @@ -197,13 +202,15 @@ getfont(PyObject *self_, PyObject *args, PyObject *kw) {
}
if (!error) {
memcpy(self->font_bytes, font_bytes, (size_t)font_bytes_size);
MUTEX_LOCK(&ft_library_mutex);
error = FT_New_Memory_Face(
library,
(FT_Byte *)self->font_bytes,
font_bytes_size,
index,
&self->face
);
MUTEX_UNLOCK(&ft_library_mutex);
}
}

Expand Down Expand Up @@ -1433,7 +1440,9 @@ font_setvaraxes(FontObject *self, PyObject *args) {
static void
font_dealloc(FontObject *self) {
if (self->face) {
MUTEX_LOCK(&ft_library_mutex);
FT_Done_Face(self->face);
MUTEX_UNLOCK(&ft_library_mutex);
}
if (self->font_bytes) {
PyMem_Free(self->font_bytes);
Expand Down
Loading

0 comments on commit 9a4b3e0

Please sign in to comment.