Skip to content

Commit 9a4b3e0

Browse files
authored
Merge pull request #8496 from lysnikolaou/fix-font-face-threading-crash
Fix SEGFAULT from calling FT_New_Face/FT_Done_Face in multiple threads
2 parents 29cdbce + bb3515d commit 9a4b3e0

File tree

2 files changed

+349
-1
lines changed

2 files changed

+349
-1
lines changed

src/_imagingft.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,9 @@ struct {
8282
/* font objects */
8383

8484
static FT_Library library;
85+
#ifdef Py_GIL_DISABLED
86+
static PyMutex ft_library_mutex;
87+
#endif
8588

8689
typedef struct {
8790
PyObject_HEAD FT_Face face;
@@ -187,7 +190,9 @@ getfont(PyObject *self_, PyObject *args, PyObject *kw) {
187190

188191
if (filename && font_bytes_size <= 0) {
189192
self->font_bytes = NULL;
193+
MUTEX_LOCK(&ft_library_mutex);
190194
error = FT_New_Face(library, filename, index, &self->face);
195+
MUTEX_UNLOCK(&ft_library_mutex);
191196
} else {
192197
/* need to have allocated storage for font_bytes for the life of the object.*/
193198
/* Don't free this before FT_Done_Face */
@@ -197,13 +202,15 @@ getfont(PyObject *self_, PyObject *args, PyObject *kw) {
197202
}
198203
if (!error) {
199204
memcpy(self->font_bytes, font_bytes, (size_t)font_bytes_size);
205+
MUTEX_LOCK(&ft_library_mutex);
200206
error = FT_New_Memory_Face(
201207
library,
202208
(FT_Byte *)self->font_bytes,
203209
font_bytes_size,
204210
index,
205211
&self->face
206212
);
213+
MUTEX_UNLOCK(&ft_library_mutex);
207214
}
208215
}
209216

@@ -1433,7 +1440,9 @@ font_setvaraxes(FontObject *self, PyObject *args) {
14331440
static void
14341441
font_dealloc(FontObject *self) {
14351442
if (self->face) {
1443+
MUTEX_LOCK(&ft_library_mutex);
14361444
FT_Done_Face(self->face);
1445+
MUTEX_UNLOCK(&ft_library_mutex);
14371446
}
14381447
if (self->font_bytes) {
14391448
PyMem_Free(self->font_bytes);

0 commit comments

Comments
 (0)