Skip to content

Commit

Permalink
Merge pull request #2255 from yunline/font-render-segfault
Browse files Browse the repository at this point in the history
Fix segfault when rendering fonts
  • Loading branch information
Starbuck5 authored Jun 18, 2023
2 parents 7ae1480 + edd3323 commit 8805b16
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/reST/ref/font.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ solves no longer exists, it will likely be removed in the future.

It is safe to call this function even if font is currently not initialized.

Previously created font objects will be invalid after the font module is quit.

.. ## pygame.font.quit ##
.. function:: get_init
Expand Down
19 changes: 19 additions & 0 deletions src_c/font.c
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ PyFont_New(TTF_Font *);
#define PyFont_Check(x) ((x)->ob_type == &PyFont_Type)

static unsigned int current_ttf_generation = 0;

#define PgFont_GenerationCheck(x) \
(((PyFontObject *)(x))->ttf_init_generation == current_ttf_generation)

#if defined(BUILD_STATIC)
// SDL_Init + TTF_Init() are made in main before CPython process the module
// inittab so the emscripten handler knows it will use SDL2 next cycle.
Expand Down Expand Up @@ -486,6 +490,11 @@ font_render(PyObject *self, PyObject *args, PyObject *kwds)
const char *astring = "";
int wraplength = 0;

if (!PgFont_GenerationCheck(self)) {
return RAISE(pgExc_SDLError,
"Invalid font (font module quit since font created)");
}

static char *kwlist[] = {"text", "antialias", "color",
"bgcolor", "wraplength", NULL};

Expand Down Expand Up @@ -610,6 +619,11 @@ font_size(PyObject *self, PyObject *text)
int w, h;
const char *string;

if (!PgFont_GenerationCheck(self)) {
return RAISE(pgExc_SDLError,
"Invalid font (font module quit since font created)");
}

if (PyUnicode_Check(text)) {
PyObject *bytes = PyUnicode_AsEncodedString(text, "utf-8", "strict");
int ecode;
Expand Down Expand Up @@ -664,6 +678,11 @@ font_metrics(PyObject *self, PyObject *textobj)
PyObject *temp;
int surrogate;

if (!PgFont_GenerationCheck(self)) {
return RAISE(pgExc_SDLError,
"Invalid font (font module quit since font created)");
}

if (PyUnicode_Check(textobj)) {
obj = textobj;
Py_INCREF(obj);
Expand Down

0 comments on commit 8805b16

Please sign in to comment.