Refactor Freeing CCtxes / CDicts Inside Workspaces

This commit is contained in:
W. Felix Handte 2019-09-16 17:43:05 -04:00
parent 143b296cf6
commit ef0b5707c5
2 changed files with 16 additions and 11 deletions

View File

@ -130,24 +130,23 @@ static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
{ {
assert(cctx != NULL); assert(cctx != NULL);
assert(cctx->staticSize == 0); assert(cctx->staticSize == 0);
/* Only free workspace if cctx not in workspace, otherwise the workspace
* will be freed when the cctx itself is freed. */
if ((void*)cctx->workspace.workspace != (void*)cctx) {
ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
}
ZSTD_clearAllDicts(cctx); ZSTD_clearAllDicts(cctx);
#ifdef ZSTD_MULTITHREAD #ifdef ZSTD_MULTITHREAD
ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL; ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
#endif #endif
ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
} }
size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx) size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
{ {
int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
if (cctx==NULL) return 0; /* support free on NULL */ if (cctx==NULL) return 0; /* support free on NULL */
RETURN_ERROR_IF(cctx->staticSize, memory_allocation, RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
"not compatible with static CCtx"); "not compatible with static CCtx");
ZSTD_freeCCtxContent(cctx); ZSTD_freeCCtxContent(cctx);
ZSTD_free(cctx, cctx->customMem); if (!cctxInWorkspace) {
ZSTD_free(cctx, cctx->customMem);
}
return 0; return 0;
} }
@ -3204,12 +3203,11 @@ size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
{ {
if (cdict==NULL) return 0; /* support free on NULL */ if (cdict==NULL) return 0; /* support free on NULL */
{ ZSTD_customMem const cMem = cdict->customMem; { ZSTD_customMem const cMem = cdict->customMem;
/* Only free workspace if cdict not in workspace, otherwise the int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
* workspace will be freed when the cdict itself is freed. */ ZSTD_cwksp_free(&cdict->workspace, cMem);
if ((void*)cdict->workspace.workspace != (void*)cdict) { if (!cdictInWorkspace) {
ZSTD_cwksp_free(&cdict->workspace, cMem); ZSTD_free(cdict, cMem);
} }
ZSTD_free(cdict, cMem);
return 0; return 0;
} }
} }

View File

@ -217,6 +217,13 @@ MEM_STATIC void ZSTD_cwksp_internal_advance_phase(
} }
} }
/**
* Returns whether this object/buffer/etc was allocated in this workspace.
*/
MEM_STATIC int ZSTD_cwksp_owns_buffer(const ZSTD_cwksp* ws, const void* ptr) {
return (ptr != NULL) && (ws->workspace <= ptr) && (ptr <= ws->workspaceEnd);
}
/** /**
* Internal function. Do not use directly. * Internal function. Do not use directly.
*/ */