From 4dce42e458d2a0691b64905e43964bec08240bb2 Mon Sep 17 00:00:00 2001 From: James R Date: Mon, 28 Aug 2023 01:55:34 -0700 Subject: [PATCH] R_GenerateBlendTables: allocate copy of palette for use in thread The palette can be freed while this thread is still running, which means the thread would end up reading from freed memory. --- src/r_draw.cpp | 42 +++++++++++++++++++++++++++++++----------- src/r_draw.h | 1 + 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/r_draw.cpp b/src/r_draw.cpp index d7261b230..7064424f3 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -111,14 +111,23 @@ static UINT8 **localtranslationtablecache[MAXLOCALSKINS] = {NULL}; CV_PossibleValue_t Color_cons_t[MAXSKINCOLORS+1]; -static void R_GenerateBlendTables(void); +struct GenerateBlendTables_State +{ + RGBA_t *LocalPalette; +}; + +static void R_GenerateBlendTables_Core(struct GenerateBlendTables_State *state); static void R_AllocateBlendTables(void); #ifdef HAVE_THREADS static void R_GenerateBlendTables_Thread(void *userdata) { - (void)userdata; - R_GenerateBlendTables(); + struct GenerateBlendTables_State *state = static_cast(userdata); + + R_GenerateBlendTables_Core(state); + + free(state->LocalPalette); + free(state); } #endif @@ -142,13 +151,7 @@ void R_InitTranslucencyTables(void) W_ReadLump(W_GetNumForName("TRANS90"), transtables+0x80000); R_AllocateBlendTables(); - -#ifdef HAVE_THREADS - I_spawn_thread("blend-tables", - R_GenerateBlendTables_Thread, NULL); -#else R_GenerateBlendTables(); -#endif } static colorlookup_t transtab_lut; @@ -268,9 +271,26 @@ static void R_AllocateBlendTables(void) } } -static void R_GenerateBlendTables(void) +void R_GenerateBlendTables(void) { - InitColorLUT(&transtab_lut, pLocalPalette, false); +#ifdef HAVE_THREADS + // Allocate copies for the worker thread since the originals can be freed in the main thread. + struct GenerateBlendTables_State *state = static_cast(malloc(sizeof *state)); + size_t palsize = 256 * sizeof(RGBA_t); + + state->LocalPalette = static_cast(memcpy(malloc(palsize), pLocalPalette, palsize)); + + I_spawn_thread("blend-tables", + R_GenerateBlendTables_Thread, state); +#else + struct GenerateBlendTables_State state = {pLocalPalette, pGammaCorrectedPalette}; + R_GenerateBlendTables_Core(&state); +#endif +} + +static void R_GenerateBlendTables_Core(struct GenerateBlendTables_State *state) +{ + InitColorLUT(&transtab_lut, state->LocalPalette, false); // Additive BlendTab_GenerateMaps(blendtab_add, AST_ADD, BlendTab_Translucent); diff --git a/src/r_draw.h b/src/r_draw.h index 763375709..bcd734e50 100644 --- a/src/r_draw.h +++ b/src/r_draw.h @@ -212,6 +212,7 @@ enum extern UINT8 *blendtables[NUMBLENDMAPS]; void R_InitTranslucencyTables(void); +void R_GenerateBlendTables(void); UINT8 *R_GetTranslucencyTable(INT32 alphalevel); UINT8 *R_GetBlendTable(int style, INT32 alphalevel);