From 731d9bac76b5719efc1619b48b9f861439f81804 Mon Sep 17 00:00:00 2001 From: Mateusz Jablonski Date: Tue, 11 Apr 2023 14:17:21 +0200 Subject: [PATCH] Fix memory leaks related to layers and vendor icds fixes: https://github.com/KhronosGroup/OpenCL-ICD-Loader/issues/157 Signed-off-by: Mateusz Jablonski --- loader/icd.c | 18 ++++++++++++++++++ loader/icd.h | 6 ++++++ loader/linux/icd_linux.c | 5 +++++ loader/windows/icd_windows.c | 8 ++++++++ 4 files changed, 37 insertions(+) diff --git a/loader/icd.c b/loader/icd.c index bbd6ec3a..10db07b0 100644 --- a/loader/icd.c +++ b/loader/icd.c @@ -210,6 +210,15 @@ void khrIcdVendorAdd(const char *libraryName) } } +void khrIcdVendorCleanup() { + KHRicdVendor* nextVendor = NULL; + while (khrIcdVendors) { + nextVendor = khrIcdVendors->next; + free(khrIcdVendors); + khrIcdVendors = nextVendor; + } +} + #if defined(CL_ENABLE_LAYERS) void khrIcdLayerAdd(const char *libraryName) { @@ -345,6 +354,15 @@ void khrIcdLayerAdd(const char *libraryName) free(layer); } } + +void khrIcdLayerCleanup() { + struct KHRLayer* nextLayer = NULL; + while (khrFirstLayer) { + nextLayer = khrFirstLayer->next; + free(khrFirstLayer); + khrFirstLayer = nextLayer; + } +} #endif // defined(CL_ENABLE_LAYERS) // Get next file or dirname given a string list or registry key path. diff --git a/loader/icd.h b/loader/icd.h index 93723aaf..d1d767eb 100644 --- a/loader/icd.h +++ b/loader/icd.h @@ -152,12 +152,18 @@ void khrIcdVendorsEnumerateEnv(void); // add a vendor's implementation to the list of libraries void khrIcdVendorAdd(const char *libraryName); +// cleanup a list of vendor icds +void khrIcdVendorCleanup(); + // read layers from environment variables void khrIcdLayersEnumerateEnv(void); // add a layer to the layer chain void khrIcdLayerAdd(const char *libraryName); +// cleanup a layer chain +void khrIcdLayerCleanup(); + // dynamically load a library. returns NULL on failure // n.b, this call is OS-specific void *khrIcdOsLibraryLoad(const char *libraryName); diff --git a/loader/linux/icd_linux.c b/loader/linux/icd_linux.c index 6dd24983..e2bd39b3 100644 --- a/loader/linux/icd_linux.c +++ b/loader/linux/icd_linux.c @@ -260,3 +260,8 @@ void khrIcdOsLibraryUnload(void *library) { dlclose(library); } + +void __attribute__((destructor)) khrIcdGlobalDestructor() { + khrIcdVendorCleanup(); + khrIcdLayerCleanup(); +} \ No newline at end of file diff --git a/loader/windows/icd_windows.c b/loader/windows/icd_windows.c index 75128a93..353e2128 100644 --- a/loader/windows/icd_windows.c +++ b/loader/windows/icd_windows.c @@ -443,3 +443,11 @@ void khrIcdOsLibraryUnload(void *library) { FreeLibrary( (HMODULE)library); } + +BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { + if (fdwReason == DLL_PROCESS_DETACH) { + khrIcdVendorCleanup(); + khrIcdLayerCleanup(); + } + return TRUE; +} \ No newline at end of file