SDL: cmake: use check_symbol_exists to check dlopen + need for dl library (a1026)

From a1026d6368c6c0138530741b9236c5e580463d10 Mon Sep 17 00:00:00 2001
From: Anonymous Maarten <[EMAIL REDACTED]>
Date: Tue, 27 Sep 2022 01:08:04 +0200
Subject: [PATCH] cmake: use check_symbol_exists to check dlopen + need for dl
 library

(cherry-picked from commit bfecd78159436d89c88788e09ef2e84f709a1855)
---
 CMakeLists.txt        |  1 +
 cmake/sdlchecks.cmake | 27 +++++++++------------------
 2 files changed, 10 insertions(+), 18 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 232486d2b721..98d6f892e0f3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -65,6 +65,7 @@ include(CheckCCompilerFlag)
 include(CheckCXXCompilerFlag)
 include(CheckStructHasMember)
 include(CMakeDependentOption)
+include(CMakePushCheckState)
 include(FindPkgConfig)
 include(GNUInstallDirs)
 set(CMAKE_MODULE_PATH "${SDL2_SOURCE_DIR}/cmake")
diff --git a/cmake/sdlchecks.cmake b/cmake/sdlchecks.cmake
index 80f31c7d7977..e062043c934f 100644
--- a/cmake/sdlchecks.cmake
+++ b/cmake/sdlchecks.cmake
@@ -30,28 +30,19 @@ macro(FindLibraryAndSONAME _LIB)
 endmacro()
 
 macro(CheckDLOPEN)
-  check_symbol_exists(dlopen "dlfcn.h" HAVE_DLOPEN)
-  if(NOT HAVE_DLOPEN)
-    check_library_exists(dl dlopen "" DLOPEN_LIB)
-    if(DLOPEN_LIB)
+  cmake_push_check_state(RESET)
+  check_symbol_exists(dlopen "dlfcn.h" HAVE_DLOPEN_IN_LIBC)
+  if(NOT HAVE_DLOPEN_IN_LIBC)
+    set(CMAKE_REQUIRED_LIBRARIES dl)
+    check_symbol_exists(dlopen "dlfcn.h" HAVE_DLOPEN_IN_LIBDL)
+    if(HAVE_DLOPEN_IN_LIBDL)
       list(APPEND EXTRA_LIBS dl)
-      set(_DLLIB dl)
-      set(HAVE_DLOPEN TRUE)
     endif()
   endif()
-  if(HAVE_DLOPEN)
-    if(_DLLIB)
-      set(CMAKE_REQUIRED_LIBRARIES ${_DLLIB})
-    endif()
-    check_c_source_compiles("
-       #include <dlfcn.h>
-       int main(int argc, char **argv) {
-         void *handle = dlopen(\"\", RTLD_NOW);
-         const char *loaderror = (char *) dlerror();
-         return 0;
-       }" HAVE_DLOPEN)
-    set(CMAKE_REQUIRED_LIBRARIES)
+  if(HAVE_DLOPEN_IN_LIBC OR HAVE_DLOPEN_IN_LIBDL)
+    set(HAVE_DLOPEN TRUE)
   endif()
+  cmake_pop_check_state()
 endmacro()
 
 macro(CheckO_CLOEXEC)