从应用程序的角度看 OpenGL 图形系统的接口,主要包括两大部分,一部分是 EGL,它为 OpenGL 渲染准备环境;另一部分是 OpenGL,它执行图形渲染。通过这些接口构造渲染环境,并执行渲染的过程,可以参考 在 Android 中使用 OpenGL。
对于 Android OpenGL 图形系统的实现的分析,从 EGL context 的创建开始。先来看一下获取 Display 的过程。首先来看 EGLContext.getEGL():
1public abstract class EGLContext 2{ 3 private static final EGL EGL_INSTANCE = new com.google.android.gles_jni.EGLImpl(); 4 5 public static EGL getEGL() { 6 return EGL_INSTANCE; 7 } 8 9 public abstract GL getGL(); 10}
返回的 EGL 实例为 EGLImpl,即我们在应用中使用的 EGL 实际为 com.google.android.gles_jni.EGLImpl。
获取 Display
然后来看 eglGetDisplay()。EGLImpl 的定义位于 frameworks/base/opengl/java/com/google/android/gles_jni/EGLImpl.java,其中 eglGetDisplay() 定义如下:
1 public synchronized EGLDisplay eglGetDisplay(Object native_display) { 2 long value = _eglGetDisplay(native_display); 3 if (value == 0) { 4 return EGL10.EGL_NO_DISPLAY; 5 } 6 if (mDisplay.mEGLDisplay != value) 7 mDisplay = new EGLDisplayImpl(value); 8 return mDisplay; 9 } 10. . . . . . 11 private native long _eglGetDisplay(Object native_display);
这里主要通过调用本地层方法 _eglGetDisplay() 得到 Display,然后创建 EGLDisplayImpl。_eglGetDisplay() 返回底层的 Display 对象句柄。
EGLDisplayImpl 的实现很简单:
1package com.google.android.gles_jni; 2 3import javax.microedition.khronos.egl.*; 4 5public class EGLDisplayImpl extends EGLDisplay { 6 long mEGLDisplay; 7 8 public EGLDisplayImpl(long dpy) { 9 mEGLDisplay = dpy; 10 } 11 12 @Override 13 public boolean equals(Object o) { 14 if (this == o) return true; 15 if (o == null || getClass() != o.getClass()) return false; 16 17 EGLDisplayImpl that = (EGLDisplayImpl) o; 18 19 return mEGLDisplay == that.mEGLDisplay; 20 21 } 22 23 @Override 24 public int hashCode() { 25 /* 26 * Based on the algorithm suggested in 27 * http://developer.android.com/reference/java/lang/Object.html 28 */ 29 int result = 17; 30 result = 31 * result + (int) (mEGLDisplay ^ (mEGLDisplay >>> 32)); 31 return result; 32 } 33}
EGLDispaly 实际是一个标记接口:
1package javax.microedition.khronos.egl; 2 3public abstract class EGLDisplay 4{ 5}
可见 EGLDisplayImpl 仅仅包装了本地层返回的 Display 对象句柄。
本地层 _eglGetDisplay() 的实现位于 frameworks/base/core/jni/com_google_android_gles_jni_EGLImpl.cpp:
1static jlong jni_eglGetDisplay(JNIEnv *_env, jobject _this, jobject native_display) { 2 return reinterpret_cast<jlong>(eglGetDisplay(EGL_DEFAULT_DISPLAY)); 3} 4. . . . . . 5{"_eglGetDisplay", "(" OBJECT ")J", (void*)jni_eglGetDisplay },
这里通过调用 EGL 库的 eglGetDisplay() 获得 Display。eglGetDisplay() 的定义位于 frameworks/native/opengl/libs/EGL/eglApi.cpp :
1EGLDisplay eglGetDisplay(EGLNativeDisplayType display) 2{ 3 clearError(); 4 5 uintptr_t index = reinterpret_cast<uintptr_t>(display); 6 if (index >= NUM_DISPLAYS) { 7 return setError(EGL_BAD_PARAMETER, EGL_NO_DISPLAY); 8 } 9 10 if (egl_init_drivers() == EGL_FALSE) { 11 return setError(EGL_BAD_PARAMETER, EGL_NO_DISPLAY); 12 } 13 14 EGLDisplay dpy = egl_display_t::getFromNativeDisplay(display); 15 return dpy; 16}
在这个函数中,首先根据需要执行 egl_init_drivers() 初始化驱动库。然后通过 egl_display_t::getFromNativeDisplay(display) 获得 Dispaly。
egl_display_t::getFromNativeDisplay(display) 的定义(位于 frameworks/native/opengl/libs/EGL/egl_display.cpp)如下:
1EGLDisplay egl_display_t::getDisplay(EGLNativeDisplayType display) { 2 3 Mutex::Autolock _l(lock); 4 5 // get our driver loader 6 Loader& loader(Loader::getInstance()); 7 8 egl_connection_t* const cnx = &gEGLImpl; 9 if (cnx->dso && disp.dpy == EGL_NO_DISPLAY) { 10 EGLDisplay dpy = cnx->egl.eglGetDisplay(display); 11 disp.dpy = dpy; 12 if (dpy == EGL_NO_DISPLAY) { 13 loader.close(cnx->dso); 14 cnx->dso = NULL; 15 } 16 } 17 18 return EGLDisplay(uintptr_t(display) + 1U); 19}
在这个函数中,最为关键的就是,在 disp.dpy 为 EGL_NO_DISPLAY 时,通过 cnx->egl.eglGetDisplay() 初始化它了。
EGLDisplay 的定义如下:
typedef void *EGLDisplay;
它仅是 void 指针的 typedef。
总结一下获取 Display 的整个过程
- 通过
frameworks/native/opengl/libs/EGL初始化图形驱动; - 通过厂商提供的设备特有的 EGL 库接口初始化 Display。
Android 图形驱动初始化
接下来更详细地看一下图形驱动初始化。这通过 egl_init_drivers() 完成,该函数定义 (位于frameworks/native/opengl/libs/EGL/egl.cpp) 如下:
1egl_connection_t gEGLImpl; 2gl_hooks_t gHooks[2]; 3. . . . . . 4static EGLBoolean egl_init_drivers_locked() { 5 if (sEarlyInitState) { 6 // initialized by static ctor. should be set here. 7 return EGL_FALSE; 8 } 9 10 // get our driver loader 11 Loader& loader(Loader::getInstance()); 12 13 // dynamically load our EGL implementation 14 egl_connection_t* cnx = &gEGLImpl; 15 if (cnx->dso == 0) { 16 cnx->hooks[egl_connection_t::GLESv1_INDEX] = 17 &gHooks[egl_connection_t::GLESv1_INDEX]; 18 cnx->hooks[egl_connection_t::GLESv2_INDEX] = 19 &gHooks[egl_connection_t::GLESv2_INDEX]; 20 cnx->dso = loader.open(cnx); 21 } 22 23 return cnx->dso ? EGL_TRUE : EGL_FALSE; 24} 25 26static pthread_mutex_t sInitDriverMutex = PTHREAD_MUTEX_INITIALIZER; 27 28EGLBoolean egl_init_drivers() { 29 EGLBoolean res; 30 pthread_mutex_lock(&sInitDriverMutex); 31 res = egl_init_drivers_locked(); 32 pthread_mutex_unlock(&sInitDriverMutex); 33 return res; 34}
图形驱动初始化通过 Loader::open(egl_connection_t* cnx) 完成,初始化的结果将存储于全局结构 egl_connection_t gEGLImpl 和 gl_hooks_t gHooks[2] 中。
来看一下 gl_hooks_t 的定义(位于 frameworks/native/opengl/libs/hooks.h):
1// maximum number of GL extensions that can be used simultaneously in 2// a given process. this limitation exists because we need to have 3// a static function for each extension and currently these static functions 4// are generated at compile time. 5#define MAX_NUMBER_OF_GL_EXTENSIONS 256 6. . . . . . 7#undef GL_ENTRY 8#undef EGL_ENTRY 9#define GL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__); 10#define EGL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__); 11 12struct egl_t { 13 #include "EGL/egl_entries.in" 14}; 15 16struct gl_hooks_t { 17 struct gl_t { 18 #include "entries.in" 19 } gl; 20 struct gl_ext_t { 21 __eglMustCastToProperFunctionPointerType extensions[MAX_NUMBER_OF_GL_EXTENSIONS]; 22 } ext; 23}; 24#undef GL_ENTRY 25#undef EGL_ENTRY
其中 __eglMustCastToProperFunctionPointerType 定义 (位于frameworks/native/opengl/include/EGL/egl.h) 如下:
1/* This is a generic function pointer type, whose name indicates it must 2 * be cast to the proper type *and calling convention* before use. 3 */ 4typedef void (*__eglMustCastToProperFunctionPointerType)(void);
__eglMustCastToProperFunctionPointerType 是函数指针类型。struct gl_hooks_t 的 struct gl_ext_t ext 即为函数指针表,它们用来描述 EGL 扩展接口。
struct gl_hooks_t 内的 struct gl_t 结构体,其结构体成员在另外一个文件,即 entries.in 中定义,该文件位于 frameworks/native/opengl/libs/entries.in:
1GL_ENTRY(void, glActiveShaderProgram, GLuint pipeline, GLuint program) 2GL_ENTRY(void, glActiveShaderProgramEXT, GLuint pipeline, GLuint program) 3GL_ENTRY(void, glActiveTexture, GLenum texture) 4GL_ENTRY(void, glAlphaFunc, GLenum func, GLfloat ref) 5GL_ENTRY(void, glAlphaFuncQCOM, GLenum func, GLclampf ref) 6. . . . . .
配合 frameworks/native/opengl/libs/hooks.h 中 GL_ENTRY 宏的定义:
#define GL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__);
可以看到 struct gl_hooks_t 的 struct gl_t gl 的所有成员都是函数指针,即它是一个函数表,一个 OpenGL 接口函数的函数表。
上面看到的 struct egl_t 与 struct gl_hooks_t 的 struct gl_t gl 定义类似,只是它的结构体成员来自于另外一个文件 frameworks/native/opengl/libs/EGL/egl_entries.in:
1EGL_ENTRY(EGLDisplay, eglGetDisplay, NativeDisplayType) 2EGL_ENTRY(EGLBoolean, eglInitialize, EGLDisplay, EGLint*, EGLint*) 3EGL_ENTRY(EGLBoolean, eglTerminate, EGLDisplay) 4EGL_ENTRY(EGLBoolean, eglGetConfigs, EGLDisplay, EGLConfig*, EGLint, EGLint*) 5EGL_ENTRY(EGLBoolean, eglChooseConfig, EGLDisplay, const EGLint *, EGLConfig *, EGLint, EGLint *) 6. . . . . .
EGL_ENTRY 宏的定义与 GL_ENTRY 宏的完全相同。struct egl_t 同样为一个函数表,只是它是 EGL 接口的函数表。
再来看 egl_connection_t 的定义,位于 frameworks/native/opengl/libs/EGL/egldefs.h:
1struct egl_connection_t { 2 enum { 3 GLESv1_INDEX = 0, 4 GLESv2_INDEX = 1 5 }; 6 7 inline egl_connection_t() : dso(0) { } 8 void * dso; 9 gl_hooks_t * hooks[2]; 10 EGLint major; 11 EGLint minor; 12 egl_t egl; 13 14 void* libEgl; 15 void* libGles1; 16 void* libGles2; 17};
这个结构包含了主、次版本号; 4 个指针;两个函数表的指针以及一个函数表。
Loader::open(egl_connection_t* cnx) 初始化图形驱动,主要是初始化这些函数表和指针。Loader::open(egl_connection_t* cnx) 的定义如下:
1static void* load_wrapper(const char* path) { 2 void* so = dlopen(path, RTLD_NOW | RTLD_LOCAL); 3 ALOGE_IF(!so, "dlopen(\"%s\") failed: %s", path, dlerror()); 4 return so; 5} 6 7#ifndef EGL_WRAPPER_DIR 8#if defined(__LP64__) 9#define EGL_WRAPPER_DIR "/system/lib64" 10#else 11#define EGL_WRAPPER_DIR "/system/lib" 12#endif 13#endif 14 15static void setEmulatorGlesValue(void) { 16 char prop[PROPERTY_VALUE_MAX]; 17 property_get("ro.kernel.qemu", prop, "0"); 18 if (atoi(prop) != 1) return; 19 20 property_get("ro.kernel.qemu.gles",prop,"0"); 21 if (atoi(prop) == 1) { 22 ALOGD("Emulator has host GPU support, qemu.gles is set to 1."); 23 property_set("qemu.gles", "1"); 24 return; 25 } 26 27 // for now, checking the following 28 // directory is good enough for emulator system images 29 const char* vendor_lib_path = 30#if defined(__LP64__) 31 "/vendor/lib64/egl"; 32#else 33 "/vendor/lib/egl"; 34#endif 35 36 const bool has_vendor_lib = (access(vendor_lib_path, R_OK) == 0); 37 if (has_vendor_lib) { 38 ALOGD("Emulator has vendor provided software renderer, qemu.gles is set to 2."); 39 property_set("qemu.gles", "2"); 40 } else { 41 ALOGD("Emulator without GPU support detected. " 42 "Fallback to legacy software renderer, qemu.gles is set to 0."); 43 property_set("qemu.gles", "0"); 44 } 45} 46 47void* Loader::open(egl_connection_t* cnx) 48{ 49 void* dso; 50 driver_t* hnd = 0; 51 52 setEmulatorGlesValue(); 53 54 dso = load_driver("GLES", cnx, EGL | GLESv1_CM | GLESv2); 55 if (dso) { 56 hnd = new driver_t(dso); 57 } else { 58 // Always load EGL first 59 dso = load_driver("EGL", cnx, EGL); 60 if (dso) { 61 hnd = new driver_t(dso); 62 hnd->set( load_driver("GLESv1_CM", cnx, GLESv1_CM), GLESv1_CM ); 63 hnd->set( load_driver("GLESv2", cnx, GLESv2), GLESv2 ); 64 } 65 } 66 67 LOG_ALWAYS_FATAL_IF(!hnd, "couldn't find an OpenGL ES implementation"); 68 69 cnx->libEgl = load_wrapper(EGL_WRAPPER_DIR "/libEGL.so"); 70 cnx->libGles2 = load_wrapper(EGL_WRAPPER_DIR "/libGLESv2.so"); 71 cnx->libGles1 = load_wrapper(EGL_WRAPPER_DIR "/libGLESv1_CM.so"); 72 73 LOG_ALWAYS_FATAL_IF(!cnx->libEgl, 74 "couldn't load system EGL wrapper libraries"); 75 76 LOG_ALWAYS_FATAL_IF(!cnx->libGles2 || !cnx->libGles1, 77 "couldn't load system OpenGL ES wrapper libraries"); 78 79 return (void*)hnd; 80}
这个函数中,执行步骤如下:
- 为设备是模拟器的情况,设置系统属性
qemu.gles。 - 加载设备特有的图形驱动库,包括 EGL 库,OpenGL ES 1.0 和 2.0 的库。
- 加载图形驱动 Wrapper,它们都位于
/system/lib64或/system/lib。
egl_connection_t 中的几个指针中,dso 实际为 struct driver_t 指针,该结构定义(位于 frameworks/native/opengl/libs/EGL/Loader.h)如下:
1 struct driver_t { 2 driver_t(void* gles); 3 ~driver_t(); 4 status_t set(void* hnd, int32_t api); 5 void* dso[3]; 6 };
struct driver_t 包含设备生产商提供的设备特有 EGL 和 OpenGL ES 实现库的句柄,如果 EGL 接口和 OpenGL 接口由单独的库实现,它包含一个库的句柄,即这个单独的库,如果 EGL 接口由不同的库实现,它则包含所有这些库的句柄。
egl_connection_t 的 libEgl、libGles2 和 libGles1 为动态链接库句柄,其中 libEgl 指向 Android 的 EGL Wrapper 库;libGles1 指向 Android 的 GLESv1_CM Wrapper 库;libGles2 指向 Android 的 GLESv2 Wrapper 库。
然后来看 Loader::load_driver():
1/* This function is called to check whether we run inside the emulator, 2 * and if this is the case whether GLES GPU emulation is supported. 3 * 4 * Returned values are: 5 * -1 -> not running inside the emulator 6 * 0 -> running inside the emulator, but GPU emulation not supported 7 * 1 -> running inside the emulator, GPU emulation is supported 8 * through the "emulation" host-side OpenGL ES implementation. 9 * 2 -> running inside the emulator, GPU emulation is supported 10 * through a guest-side vendor driver's OpenGL ES implementation. 11 */ 12static int 13checkGlesEmulationStatus(void) 14{ 15 /* We're going to check for the following kernel parameters: 16 * 17 * qemu=1 -> tells us that we run inside the emulator 18 * android.qemu.gles=<number> -> tells us the GLES GPU emulation status 19 * 20 * Note that we will return <number> if we find it. This let us support 21 * more additionnal emulation modes in the future. 22 */ 23 char prop[PROPERTY_VALUE_MAX]; 24 int result = -1; 25 26 /* First, check for qemu=1 */ 27 property_get("ro.kernel.qemu",prop,"0"); 28 if (atoi(prop) != 1) 29 return -1; 30 31 /* We are in the emulator, get GPU status value */ 32 property_get("qemu.gles",prop,"0"); 33 return atoi(prop); 34} 35. . . . . . 36void Loader::init_api(void* dso, 37 char const * const * api, 38 __eglMustCastToProperFunctionPointerType* curr, 39 getProcAddressType getProcAddress) 40{ 41 const ssize_t SIZE = 256; 42 char scrap[SIZE]; 43 while (*api) { 44 char const * name = *api; 45 __eglMustCastToProperFunctionPointerType f = 46 (__eglMustCastToProperFunctionPointerType)dlsym(dso, name); 47 if (f == NULL) { 48 // couldn't find the entry-point, use eglGetProcAddress() 49 f = getProcAddress(name); 50 } 51 if (f == NULL) { 52 // Try without the OES postfix 53 ssize_t index = ssize_t(strlen(name)) - 3; 54 if ((index>0 && (index<SIZE-1)) && (!strcmp(name+index, "OES"))) { 55 strncpy(scrap, name, index); 56 scrap[index] = 0; 57 f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap); 58 //ALOGD_IF(f, "found <%s> instead", scrap); 59 } 60 } 61 if (f == NULL) { 62 // Try with the OES postfix 63 ssize_t index = ssize_t(strlen(name)) - 3; 64 if (index>0 && strcmp(name+index, "OES")) { 65 snprintf(scrap, SIZE, "%sOES", name); 66 f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap); 67 //ALOGD_IF(f, "found <%s> instead", scrap); 68 } 69 } 70 if (f == NULL) { 71 //ALOGD("%s", name); 72 f = (__eglMustCastToProperFunctionPointerType)gl_unimplemented; 73 74 /* 75 * GL_EXT_debug_label is special, we always report it as 76 * supported, it's handled by GLES_trace. If GLES_trace is not 77 * enabled, then these are no-ops. 78 */ 79 if (!strcmp(name, "glInsertEventMarkerEXT")) { 80 f = (__eglMustCastToProperFunctionPointerType)gl_noop; 81 } else if (!strcmp(name, "glPushGroupMarkerEXT")) { 82 f = (__eglMustCastToProperFunctionPointerType)gl_noop; 83 } else if (!strcmp(name, "glPopGroupMarkerEXT")) { 84 f = (__eglMustCastToProperFunctionPointerType)gl_noop; 85 } 86 } 87 *curr++ = f; 88 api++; 89 } 90} 91 92void *Loader::load_driver(const char* kind, 93 egl_connection_t* cnx, uint32_t mask) 94{ 95 class MatchFile { 96 public: 97 static String8 find(const char* kind) { 98 String8 result; 99 int emulationStatus = checkGlesEmulationStatus(); 100 switch (emulationStatus) { 101 case 0: 102#if defined(__LP64__) 103 result.setTo("/system/lib64/egl/libGLES_android.so"); 104#else 105 result.setTo("/system/lib/egl/libGLES_android.so"); 106#endif 107 return result; 108 case 1: 109 // Use host-side OpenGL through the "emulation" library 110#if defined(__LP64__) 111 result.appendFormat("/system/lib64/egl/lib%s_emulation.so", kind); 112#else 113 result.appendFormat("/system/lib/egl/lib%s_emulation.so", kind); 114#endif 115 return result; 116 default: 117 // Not in emulator, or use other guest-side implementation 118 break; 119 } 120 121 String8 pattern; 122 pattern.appendFormat("lib%s", kind); 123 const char* const searchPaths[] = { 124#if defined(__LP64__) 125 "/vendor/lib64/egl", 126 "/system/lib64/egl" 127#else 128 "/vendor/lib/egl", 129 "/system/lib/egl" 130#endif 131 }; 132 133 // first, we search for the exact name of the GLES userspace 134 // driver in both locations. 135 // i.e.: 136 // libGLES.so, or: 137 // libEGL.so, libGLESv1_CM.so, libGLESv2.so 138 139 for (size_t i=0 ; i<NELEM(searchPaths) ; i++) { 140 if (find(result, pattern, searchPaths[i], true)) { 141 return result; 142 } 143 } 144 145 // for compatibility with the old "egl.cfg" naming convention 146 // we look for files that match: 147 // libGLES_*.so, or: 148 // libEGL_*.so, libGLESv1_CM_*.so, libGLESv2_*.so 149 150 pattern.append("_"); 151 for (size_t i=0 ; i<NELEM(searchPaths) ; i++) { 152 if (find(result, pattern, searchPaths[i], false)) { 153 return result; 154 } 155 } 156 157 // we didn't find the driver. gah. 158 result.clear(); 159 return result; 160 } 161 162 private: 163 static bool find(String8& result, 164 const String8& pattern, const char* const search, bool exact) { 165 if (exact) { 166 String8 absolutePath; 167 absolutePath.appendFormat("%s/%s.so", search, pattern.string()); 168 if (!access(absolutePath.string(), R_OK)) { 169 result = absolutePath; 170 return true; 171 } 172 return false; 173 } 174 175 DIR* d = opendir(search); 176 if (d != NULL) { 177 struct dirent cur; 178 struct dirent* e; 179 while (readdir_r(d, &cur, &e) == 0 && e) { 180 if (e->d_type == DT_DIR) { 181 continue; 182 } 183 if (!strcmp(e->d_name, "libGLES_android.so")) { 184 // always skip the software renderer 185 continue; 186 } 187 if (strstr(e->d_name, pattern.string()) == e->d_name) { 188 if (!strcmp(e->d_name + strlen(e->d_name) - 3, ".so")) { 189 result.clear(); 190 result.appendFormat("%s/%s", search, e->d_name); 191 closedir(d); 192 return true; 193 } 194 } 195 } 196 closedir(d); 197 } 198 return false; 199 } 200 }; 201 202 203 String8 absolutePath = MatchFile::find(kind); 204 if (absolutePath.isEmpty()) { 205 // this happens often, we don't want to log an error 206 return 0; 207 } 208 const char* const driver_absolute_path = absolutePath.string(); 209 210 void* dso = dlopen(driver_absolute_path, RTLD_NOW | RTLD_LOCAL); 211 if (dso == 0) { 212 const char* err = dlerror(); 213 ALOGE("load_driver(%s): %s", driver_absolute_path, err?err:"unknown"); 214 return 0; 215 } 216 217 if (mask & EGL) { 218 ALOGD("EGL loaded %s", driver_absolute_path); 219 getProcAddress = (getProcAddressType)dlsym(dso, "eglGetProcAddress"); 220 221 ALOGE_IF(!getProcAddress, 222 "can't find eglGetProcAddress() in %s", driver_absolute_path); 223 224 egl_t* egl = &cnx->egl; 225 __eglMustCastToProperFunctionPointerType* curr = 226 (__eglMustCastToProperFunctionPointerType*)egl; 227 char const * const * api = egl_names; 228 while (*api) { 229 char const * name = *api; 230 __eglMustCastToProperFunctionPointerType f = 231 (__eglMustCastToProperFunctionPointerType)dlsym(dso, name); 232 if (f == NULL) { 233 // couldn't find the entry-point, use eglGetProcAddress() 234 f = getProcAddress(name); 235 if (f == NULL) { 236 f = (__eglMustCastToProperFunctionPointerType)0; 237 } 238 } 239 *curr++ = f; 240 api++; 241 } 242 } 243 244 if (mask & GLESv1_CM) { 245 ALOGD("GLESv1_CM loaded %s", driver_absolute_path); 246 init_api(dso, gl_names, 247 (__eglMustCastToProperFunctionPointerType*) 248 &cnx->hooks[egl_connection_t::GLESv1_INDEX]->gl, 249 getProcAddress); 250 } 251 252 if (mask & GLESv2) { 253 ALOGD("GLESv2 loaded %s", driver_absolute_path); 254 init_api(dso, gl_names, 255 (__eglMustCastToProperFunctionPointerType*) 256 &cnx->hooks[egl_connection_t::GLESv2_INDEX]->gl, 257 getProcAddress); 258 } 259 260 return dso; 261}
Loader::load_driver() 通过三个步骤完成驱动库加载: 第一步,找到驱动库文件的路径。
1 class MatchFile { 2 public: 3 static String8 find(const char* kind) { 4 String8 result; 5 int emulationStatus = checkGlesEmulationStatus(); 6 switch (emulationStatus) { 7 case 0: 8#if defined(__LP64__) 9 result.setTo("/system/lib64/egl/libGLES_android.so"); 10#else 11 result.setTo("/system/lib/egl/libGLES_android.so"); 12#endif 13 return result; 14 case 1: 15 // Use host-side OpenGL through the "emulation" library 16#if defined(__LP64__) 17 result.appendFormat("/system/lib64/egl/lib%s_emulation.so", kind); 18#else 19 result.appendFormat("/system/lib/egl/lib%s_emulation.so", kind); 20#endif 21 return result; 22 default: 23 // Not in emulator, or use other guest-side implementation 24 break; 25 } 26 27 String8 pattern; 28 pattern.appendFormat("lib%s", kind); 29 const char* const searchPaths[] = { 30#if defined(__LP64__) 31 "/vendor/lib64/egl", 32 "/system/lib64/egl" 33#else 34 "/vendor/lib/egl", 35 "/system/lib/egl" 36#endif 37 }; 38 39 // first, we search for the exact name of the GLES userspace 40 // driver in both locations. 41 // i.e.: 42 // libGLES.so, or: 43 // libEGL.so, libGLESv1_CM.so, libGLESv2.so 44 45 for (size_t i=0 ; i<NELEM(searchPaths) ; i++) { 46 if (find(result, pattern, searchPaths[i], true)) { 47 return result; 48 } 49 } 50 51 // for compatibility with the old "egl.cfg" naming convention 52 // we look for files that match: 53 // libGLES_*.so, or: 54 // libEGL_*.so, libGLESv1_CM_*.so, libGLESv2_*.so 55 56 pattern.append("_"); 57 for (size_t i=0 ; i<NELEM(searchPaths) ; i++) { 58 if (find(result, pattern, searchPaths[i], false)) { 59 return result; 60 } 61 } 62 63 // we didn't find the driver. gah. 64 result.clear(); 65 return result; 66 } 67 68 private: 69 static bool find(String8& result, 70 const String8& pattern, const char* const search, bool exact) { 71 if (exact) { 72 String8 absolutePath; 73 absolutePath.appendFormat("%s/%s.so", search, pattern.string()); 74 if (!access(absolutePath.string(), R_OK)) { 75 result = absolutePath; 76 return true; 77 } 78 return false; 79 } 80 81 DIR* d = opendir(search); 82 if (d != NULL) { 83 struct dirent cur; 84 struct dirent* e; 85 while (readdir_r(d, &cur, &e) == 0 && e) { 86 if (e->d_type == DT_DIR) { 87 continue; 88 } 89 if (!strcmp(e->d_name, "libGLES_android.so")) { 90 // always skip the software renderer 91 continue; 92 } 93 if (strstr(e->d_name, pattern.string()) == e->d_name) { 94 if (!strcmp(e->d_name + strlen(e->d_name) - 3, ".so")) { 95 result.clear(); 96 result.appendFormat("%s/%s", search, e->d_name); 97 closedir(d); 98 return true; 99 } 100 } 101 } 102 closedir(d); 103 } 104 return false; 105 } 106 }; 107 108 109 String8 absolutePath = MatchFile::find(kind); 110 if (absolutePath.isEmpty()) { 111 // this happens often, we don't want to log an error 112 return 0; 113 }
checkGlesEmulationStatus() 函数,在不是运行于模拟器中时,返回 -1;在运行于模拟器中,但不支持 GPU 硬件模拟时返回 0;在运行于模拟器中,通过宿主机端的 OpenGL ES 实现来支持 GPU 硬件模拟时,返回 1;在运行于模拟器中,通过 Android 客户系统端的生产商驱动的 OpenGL ES 实现来支持 GPU 硬件模拟时,返回 2。对于运行环境的这种判断,主要依据两个系统属性,即 ro.kernel.qemu 和 qemu.gles。
只有在 checkGlesEmulationStatus() 返回 0,即运行于模拟器,但不支持 OpenGL ES 的 GPU 硬件模拟时,EGL 和 OpenGL ES 库采用软件实现 /system/lib64/egl/libGLES_android.so 或 /system/lib/egl/libGLES_android.so。
如果是物理设备,或者模拟器开启了 OpenGL ES 的 GPU 硬件模拟,对特定图形驱动库文件——EGL 库文件或 OpenGL ES 库文件——的查找按照如下的顺序进行:
/vendor/lib64/egl或/vendor/lib/egl目录下文件名符合lib%s.so模式,即/vendor下文件名完全匹配的库文件,比如/vendor/lib64/egl/libGLES.so/system/lib64/egl或/system/lib/egl目录下文件名符合lib%s.so模式,即/system下文件名完全匹配的库文件,比如/system/lib64/egl/libGLES.so/vendor/lib64/egl或/vendor/lib/egl目录下文件名符合lib%s_*.so模式,即/vendor下文件名前缀匹配的库文件,比如对于 Pixel 设备的/vendor/lib64/egl/libEGL_adreno.so/system/lib64/egl或/system/lib/egl目录下文件名符合lib%s_*.so模式,即/system下文件名前缀匹配的库文件。
Android 会优先采用 /vendor/ 下设备供应商提供的图形驱动库,优先采用库文件名完全匹配的图形驱动库。
第二步,通过 dlopen() 加载库文件。
1 const char* const driver_absolute_path = absolutePath.string(); 2 3 void* dso = dlopen(driver_absolute_path, RTLD_NOW | RTLD_LOCAL); 4 if (dso == 0) { 5 const char* err = dlerror(); 6 ALOGE("load_driver(%s): %s", driver_absolute_path, err?err:"unknown"); 7 return 0; 8 }
第三步,初始化函数表。
1 if (mask & EGL) { 2 ALOGD("EGL loaded %s", driver_absolute_path); 3 getProcAddress = (getProcAddressType)dlsym(dso, "eglGetProcAddress"); 4 5 ALOGE_IF(!getProcAddress, 6 "can't find eglGetProcAddress() in %s", driver_absolute_path); 7 8 egl_t* egl = &cnx->egl; 9 __eglMustCastToProperFunctionPointerType* curr = 10 (__eglMustCastToProperFunctionPointerType*)egl; 11 char const * const * api = egl_names; 12 while (*api) { 13 char const * name = *api; 14 __eglMustCastToProperFunctionPointerType f = 15 (__eglMustCastToProperFunctionPointerType)dlsym(dso, name); 16 if (f == NULL) { 17 // couldn't find the entry-point, use eglGetProcAddress() 18 f = getProcAddress(name); 19 if (f == NULL) { 20 f = (__eglMustCastToProperFunctionPointerType)0; 21 } 22 } 23 *curr++ = f; 24 api++; 25 } 26 } 27 28 if (mask & GLESv1_CM) { 29 ALOGD("GLESv1_CM loaded %s", driver_absolute_path); 30 init_api(dso, gl_names, 31 (__eglMustCastToProperFunctionPointerType*) 32 &cnx->hooks[egl_connection_t::GLESv1_INDEX]->gl, 33 getProcAddress); 34 } 35 36 if (mask & GLESv2) { 37 ALOGD("GLESv2 loaded %s", driver_absolute_path); 38 init_api(dso, gl_names, 39 (__eglMustCastToProperFunctionPointerType*) 40 &cnx->hooks[egl_connection_t::GLESv2_INDEX]->gl, 41 getProcAddress); 42 } 43 44 return dso; 45}
初始化函数表主要通过 dlsym() 根据函数名,一个个找到对应的地址,并赋值给函数指针来完成。EGL 接口函数名来自于 egl_names,OpenGL ES 接口函数名来自于 gl_names,它们的定义位于 frameworks/native/opengl/libs/EGL/egl.cpp:
1#undef GL_ENTRY 2#undef EGL_ENTRY 3#define GL_ENTRY(_r, _api, ...) #_api, 4#define EGL_ENTRY(_r, _api, ...) #_api, 5 6char const * const gl_names[] = { 7 #include "../entries.in" 8 NULL 9}; 10 11char const * const egl_names[] = { 12 #include "egl_entries.in" 13 NULL 14}; 15 16#undef GL_ENTRY 17#undef EGL_ENTRY
这是两个字符串数组,数组项同样来自于另外的两个文件,gl_names 的数组项来自于 egl_entries.in,gl_names 的数组项来自于 entries.in,这两个文件也正是前面看到的 struct egl_t 结构和 struct gl_hooks_t 的 struct gl_t 结构的结构成员的来源。Android 通过这种方式建立函数表与函数名表中相同函数的项之间的对应关系,即对于相同的函数,它们对应的项在函数表中的偏移,与在函数名表中的偏移相同。
对于特定的进程,Android 图形驱动初始化的过程只执行一次。在 egl_init_drivers_locked() 及 Loader::load_driver() 中加日志,重新编译 frameworks/native/opengl/libs,替换设备中的 /system/lib64/libEGL.so 和 /system/lib/libEGL.so,重新启动设备,可以看到如下的日志输出:
111-27 13:26:19.440 475 475 D libEGL : EGL loaded /vendor/lib64/egl/libEGL_adreno.so 211-27 13:26:19.628 475 475 D libEGL : GLESv1_CM loaded /vendor/lib64/egl/libGLESv1_CM_adreno.so 311-27 13:26:19.648 475 475 D libEGL : GLESv2 loaded /vendor/lib64/egl/libGLESv2_adreno.so 411-27 13:26:21.761 477 547 D libEGL : EGL loaded /vendor/lib64/egl/libEGL_adreno.so 511-27 13:26:21.776 477 547 D libEGL : GLESv1_CM loaded /vendor/lib64/egl/libGLESv1_CM_adreno.so 611-27 13:26:21.785 477 547 D libEGL : GLESv2 loaded /vendor/lib64/egl/libGLESv2_adreno.so 709-14 09:21:47.715 614 614 D libEGL : EGL loaded /vendor/lib/egl/libEGL_adreno.so 809-14 09:21:47.792 614 614 D libEGL : GLESv1_CM loaded /vendor/lib/egl/libGLESv1_CM_adreno.so 909-14 09:21:47.819 614 614 D libEGL : GLESv2 loaded /vendor/lib/egl/libGLESv2_adreno.so 1009-14 09:21:48.492 612 612 D libEGL : EGL loaded /vendor/lib64/egl/libEGL_adreno.so 1109-14 09:21:48.496 613 613 D libEGL : EGL loaded /vendor/lib/egl/libEGL_adreno.so 1209-14 09:21:48.503 612 612 D libEGL : GLESv1_CM loaded /vendor/lib64/egl/libGLESv1_CM_adreno.so 1309-14 09:21:48.510 613 613 D libEGL : GLESv1_CM loaded /vendor/lib/egl/libGLESv1_CM_adreno.so 1409-14 09:21:48.513 612 612 D libEGL : GLESv2 loaded /vendor/lib64/egl/libGLESv2_adreno.so 1509-14 09:21:48.523 613 613 D libEGL : GLESv2 loaded /vendor/lib/egl/libGLESv2_adreno.so
根据这些日志的进程号查找响应的进程:
1system 475 1 151868 22568 SyS_epoll_ 71808e632c S /system/bin/surfaceflinger 2root 612 1 2144132 81252 poll_sched 7627a2044c S zygote64 3root 613 1 1578176 69960 poll_sched 00f5045700 S zygote 4cameraserver 614 1 123228 45404 binder_thr 00efbf4658 S /system/bin/cameraserver
可见 Android 中需要用到 OpenGL ES 图形系统的进程主要有 surfaceflinger,cameraserver 和所有的 Android Java 应用程序。对于普通的 Java 应用程序,这些驱动库会先由 zygote 加载完成,后续 systemserver 指示 zygote 为普通的 Java 应用程序 fork 出新的进程,新的进程继承 zygote 加载的那些库。
图形驱动 Wrapper
Android 中图形驱动 Wrapper 是图形接口的一个中转。Android 中使用 EGL 和 OpenGL ES 接口的应用程序,可能是通过 framework 提供的 Java 接口,也可能通过 NDK 提供的本地层接口,直接调用图形驱动 Wrapper,这些 Wrapper 再将调用转给设备特有的 EGL 和 OpenGL ES 实现库中的函数。
通过 Android.mk 文件可以看到这样的依赖关系。frameworks/native/opengl/libs/Android.mk 文件中存在如下的内容:
1include $(CLEAR_VARS) 2 3LOCAL_SRC_FILES:= \ 4 EGL/egl_tls.cpp \ 5 EGL/egl_cache.cpp \ 6 EGL/egl_display.cpp \ 7 EGL/egl_object.cpp \ 8 EGL/egl.cpp \ 9 EGL/eglApi.cpp \ 10 EGL/getProcAddress.cpp.arm \ 11 EGL/Loader.cpp \ 12# 13 14LOCAL_SHARED_LIBRARIES += libbinder libcutils libutils liblog libui 15LOCAL_MODULE:= libEGL 16LOCAL_LDFLAGS += -Wl,--exclude-libs=ALL 17LOCAL_SHARED_LIBRARIES += libdl 18. . . . . . 19include $(CLEAR_VARS) 20 21LOCAL_SRC_FILES:= \ 22 GLES_CM/gl.cpp.arm \ 23# 24 25LOCAL_CLANG := false 26LOCAL_SHARED_LIBRARIES += libcutils liblog libEGL 27LOCAL_MODULE:= libGLESv1_CM 28 29LOCAL_SHARED_LIBRARIES += libdl 30. . . . . . 31include $(CLEAR_VARS) 32 33LOCAL_SRC_FILES:= \ 34 GLES2/gl2.cpp \ 35# 36 37LOCAL_CLANG := false 38LOCAL_ARM_MODE := arm 39LOCAL_SHARED_LIBRARIES += libcutils libutils liblog libEGL 40LOCAL_MODULE:= libGLESv2 41 42LOCAL_SHARED_LIBRARIES += libdl 43. . . . . . 44include $(CLEAR_VARS) 45 46LOCAL_SRC_FILES:= \ 47 GLES2/gl2.cpp \ 48# 49 50LOCAL_CLANG := false 51LOCAL_ARM_MODE := arm 52LOCAL_SHARED_LIBRARIES += libcutils libutils liblog libEGL 53LOCAL_MODULE:= libGLESv3 54LOCAL_SHARED_LIBRARIES += libdl 55. . . . . . 56
即 frameworks/native/opengl/libs/ 下的源码被编译为了四个动态链接库,分别为 libEGL.so、libGLESv1_CM、libGLESv2 和 libGLESv3,其中 libGLESv2 和 libGLESv3 完全相同。在frameworks/base/core/jni/Android.mk 中可以清晰地看到 framework JNI 对这些库的依赖:
1LOCAL_SHARED_LIBRARIES := \ 2. . . . . . 3 libsqlite \ 4 libEGL \ 5 libGLESv1_CM \ 6 libGLESv2 \ 7 libvulkan \ 8 libETC1 \ 9. . . . . .
EGL 的 Wrapper,如我们前面看到的,位于 frameworks/native/opengl/libs/EGL,其 EGL API 实现位于 frameworks/native/opengl/libs/EGL/eglApi.cpp。
GLESv1_CM 的 Wrapper 位于 frameworks/native/opengl/libs/GLES_CM,其接口实现在 gl.cpp 文件中:
1#elif defined(__arm__) 2 3 #define GET_TLS(reg) "mrc p15, 0, " #reg ", c13, c0, 3 \n" 4 5 #define API_ENTRY(_api) __attribute__((noinline)) _api 6 7 #define CALL_GL_API(_api, ...) \ 8 asm volatile( \ 9 GET_TLS(r12) \ 10 "ldr r12, [r12, %[tls]] \n" \ 11 "cmp r12, #0 \n" \ 12 "ldrne pc, [r12, %[api]] \n" \ 13 : \ 14 : [tls] "J"(TLS_SLOT_OPENGL_API*4), \ 15 [api] "J"(__builtin_offsetof(gl_hooks_t, gl._api)) \ 16 : "r12" \ 17 ); 18 19#elif defined(__aarch64__) 20 21 #define API_ENTRY(_api) __attribute__((noinline)) _api 22 23 #define CALL_GL_API(_api, ...) \ 24 asm volatile( \ 25 "mrs x16, tpidr_el0\n" \ 26 "ldr x16, [x16, %[tls]]\n" \ 27 "cbz x16, 1f\n" \ 28 "ldr x16, [x16, %[api]]\n" \ 29 "br x16\n" \ 30 "1:\n" \ 31 : \ 32 : [tls] "i" (TLS_SLOT_OPENGL_API * sizeof(void*)), \ 33 [api] "i" (__builtin_offsetof(gl_hooks_t, gl._api)) \ 34 : "x16" \ 35 ); 36 37#elif defined(__i386__) 38. . . . . . 39#define CALL_GL_API_RETURN(_api, ...) \ 40 CALL_GL_API(_api, __VA_ARGS__) \ 41 return 0; 42 43 44extern "C" { 45#pragma GCC diagnostic ignored "-Wunused-parameter" 46#include "gl_api.in" 47#include "glext_api.in" 48#pragma GCC diagnostic warning "-Wunused-parameter" 49} 50 51#undef API_ENTRY 52#undef CALL_GL_API 53#undef CALL_GL_API_RETURN
这个文件包含了另外两个文件,gl_api.in 和 glext_api.in。其中 gl_api.in 文件位于 frameworks/native/opengl/libs/GLES_CM/gl_api.in,内容如下:
1void API_ENTRY(glAlphaFunc)(GLenum func, GLfloat ref) { 2 CALL_GL_API(glAlphaFunc, func, ref); 3} 4void API_ENTRY(glClearColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { 5 CALL_GL_API(glClearColor, red, green, blue, alpha); 6} 7void API_ENTRY(glClearDepthf)(GLfloat d) { 8 CALL_GL_API(glClearDepthf, d); 9} 10void API_ENTRY(glClipPlanef)(GLenum p, const GLfloat *eqn) { 11 CALL_GL_API(glClipPlanef, p, eqn); 12} 13void API_ENTRY(glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { 14 CALL_GL_API(glColor4f, red, green, blue, alpha); 15} 16. . . . . .
glext_api.in 文件位于 frameworks/native/opengl/libs/GLES_CM/glext_api.in,内容如下:
1void API_ENTRY(glEGLImageTargetTexture2DOES)(GLenum target, GLeglImageOES image) { 2 CALL_GL_API(glEGLImageTargetTexture2DOES, target, image); 3} 4void API_ENTRY(glEGLImageTargetRenderbufferStorageOES)(GLenum target, GLeglImageOES image) { 5 CALL_GL_API(glEGLImageTargetRenderbufferStorageOES, target, image); 6} 7void API_ENTRY(glBlendEquationSeparateOES)(GLenum modeRGB, GLenum modeAlpha) { 8 CALL_GL_API(glBlendEquationSeparateOES, modeRGB, modeAlpha); 9} 10void API_ENTRY(glBlendFuncSeparateOES)(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) { 11 CALL_GL_API(glBlendFuncSeparateOES, srcRGB, dstRGB, srcAlpha, dstAlpha); 12}
配和前面的 API_ENTRY 和 CALL_GL_API 宏定义,可见 gl.cpp 中主要是定义了 OpenGL ES 函数接口,这些函数的实现为,借助于前面初始化的函数表,通过汇编代码,跳转到相应的 OpenGL ES 函数实现。
GLESv2 Wrapper 位于 frameworks/native/opengl/libs/GLES2,其 OpenGL ES 接口实现在 gl2.cpp 文件中:
1#elif defined(__arm__) 2 3 #define GET_TLS(reg) "mrc p15, 0, " #reg ", c13, c0, 3 \n" 4 5 #define API_ENTRY(_api) __attribute__((noinline)) _api 6 7 #define CALL_GL_API(_api, ...) \ 8 asm volatile( \ 9 GET_TLS(r12) \ 10 "ldr r12, [r12, %[tls]] \n" \ 11 "cmp r12, #0 \n" \ 12 "ldrne pc, [r12, %[api]] \n" \ 13 : \ 14 : [tls] "J"(TLS_SLOT_OPENGL_API*4), \ 15 [api] "J"(__builtin_offsetof(gl_hooks_t, gl._api)) \ 16 : "r12" \ 17 ); 18 19#elif defined(__aarch64__) 20 21 #define API_ENTRY(_api) __attribute__((noinline)) _api 22 23 #define CALL_GL_API(_api, ...) \ 24 asm volatile( \ 25 "mrs x16, tpidr_el0\n" \ 26 "ldr x16, [x16, %[tls]]\n" \ 27 "cbz x16, 1f\n" \ 28 "ldr x16, [x16, %[api]]\n" \ 29 "br x16\n" \ 30 "1:\n" \ 31 : \ 32 : [tls] "i" (TLS_SLOT_OPENGL_API * sizeof(void*)), \ 33 [api] "i" (__builtin_offsetof(gl_hooks_t, gl._api)) \ 34 : "x16" \ 35 ); 36 37#elif defined(__i386__) 38. . . . . . 39#define CALL_GL_API_RETURN(_api, ...) \ 40 CALL_GL_API(_api, __VA_ARGS__) \ 41 return 0; 42 43 44 45extern "C" { 46#pragma GCC diagnostic ignored "-Wunused-parameter" 47#include "gl2_api.in" 48#include "gl2ext_api.in" 49#pragma GCC diagnostic warning "-Wunused-parameter" 50} 51 52#undef API_ENTRY 53#undef CALL_GL_API 54#undef CALL_GL_API_RETURN
这里的实现与前面看到的 GLESv1_CM 的 Wrapper 的接口实现类似。
Android OpenGL ES 图形库结构
Android 的 OpenGL ES 图形系统涉及多个库,根据设备类型的不同,这些库有着不同的结构。
对于模拟器,没有开启 OpenGL ES 的 GPU 硬件模拟的情况,Android OpenGL ES 图形库结构如下:

当为模拟器开启了 OpenGL ES 的 GPU 硬件模拟,实际的 EGL 和 OpenGL ES 实现库会采用由 android-7.1.1_r22/device/generic/goldfish-opengl 下的源码编译出来的几个库文件,即 libGLESv2_emulation.so、libGLESv1_CM_emulation.so 和 libEGL_emulation.so。此时,OpenGL ES 图形库结构如下:

对于真实的物理 Android 设备,OpenGL ES 图形库结构如下:

Done.