From 95579f5f19e524ea313b780a97bb28318d7c4f62 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <slouken@libsdl.org>
Date: Mon, 1 Oct 2018 09:40:58 -0700
Subject: [PATCH] Fixed bug 4220 - SDL_GL_CONTEXT_DEBUG_FLAG can fail silently
 on some Android devices

---
 src/video/SDL_egl.c   | 21 +++++++++++++++++++++
 src/video/SDL_egl_c.h |  1 +
 2 files changed, 22 insertions(+)

diff --git a/src/video/SDL_egl.c b/src/video/SDL_egl.c
index c3b437608..78abc030e 100644
--- a/src/video/SDL_egl.c
+++ b/src/video/SDL_egl.c
@@ -406,6 +406,9 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
         }
     }
 
+    _this->egl_data->egl_version_major = egl_version_major;
+    _this->egl_data->egl_version_minor = egl_version_minor;
+
     if (egl_version_major == 1 && egl_version_minor == 5) {
         LOAD_FUNC(eglGetPlatformDisplay);
     }
@@ -658,6 +661,24 @@ SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface)
         share_context = (EGLContext)SDL_GL_GetCurrentContext();
     }
 
+#if SDL_VIDEO_DRIVER_ANDROID
+    if ((_this->gl_config.flags & SDL_GL_CONTEXT_DEBUG_FLAG) != 0) {
+        /* If SDL_GL_CONTEXT_DEBUG_FLAG is set but EGL_KHR_debug unsupported, unset.
+         * This is required because some Android devices like to complain about it
+         * by "silently" failing, logging a hint which could be easily overlooked:
+         * E/libEGL  (26984): validate_display:255 error 3008 (EGL_BAD_DISPLAY)
+         * The following explicitly checks for EGL_KHR_debug before EGL 1.5
+         */
+        int egl_version_major = _this->egl_data->egl_version_major;
+        int egl_version_minor = _this->egl_data->egl_version_minor;
+        if (((egl_version_major < 1) || (egl_version_major == 1 && egl_version_minor < 5)) &&
+            !SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_debug")) {
+            /* SDL profile bits match EGL profile bits. */
+            _this->gl_config.flags &= ~SDL_GL_CONTEXT_DEBUG_FLAG;
+        }
+    }
+#endif
+
     /* Set the context version and other attributes. */
     if ((major_version < 3 || (minor_version == 0 && profile_es)) &&
         _this->gl_config.flags == 0 &&
diff --git a/src/video/SDL_egl_c.h b/src/video/SDL_egl_c.h
index 80b13192e..d1c41297c 100644
--- a/src/video/SDL_egl_c.h
+++ b/src/video/SDL_egl_c.h
@@ -36,6 +36,7 @@ typedef struct SDL_EGL_VideoData
     EGLConfig egl_config;
     int egl_swapinterval;
     int egl_surfacetype;
+    int egl_version_major, egl_version_minor;
     
     EGLDisplay(EGLAPIENTRY *eglGetDisplay) (NativeDisplayType display);
     EGLDisplay(EGLAPIENTRY *eglGetPlatformDisplay) (EGLenum platform,