Loader.cpp revision 776951f9db5744c94167d463584e9ee42c849712
1/*
2 ** Copyright 2007, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 **     http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
17#include <ctype.h>
18#include <stdlib.h>
19#include <stdio.h>
20#include <string.h>
21#include <errno.h>
22#include <dlfcn.h>
23#include <limits.h>
24#include <dirent.h>
25
26#include <cutils/log.h>
27#include <cutils/properties.h>
28
29#include <EGL/egl.h>
30
31#include "egldefs.h"
32#include "Loader.h"
33
34// ----------------------------------------------------------------------------
35namespace android {
36// ----------------------------------------------------------------------------
37
38
39/*
40 * EGL userspace drivers must be provided either:
41 * - as a single library:
42 *      /vendor/lib/egl/libGLES.so
43 *
44 * - as separate libraries:
45 *      /vendor/lib/egl/libEGL.so
46 *      /vendor/lib/egl/libGLESv1_CM.so
47 *      /vendor/lib/egl/libGLESv2.so
48 *
49 * The software renderer for the emulator must be provided as a single
50 * library at:
51 *
52 *      /system/lib/egl/libGLES_android.so
53 *
54 *
55 * For backward compatibility and to facilitate the transition to
56 * this new naming scheme, the loader will additionally look for:
57 *
58 *      /{vendor|system}/lib/egl/lib{GLES | [EGL|GLESv1_CM|GLESv2]}_*.so
59 *
60 */
61
62ANDROID_SINGLETON_STATIC_INSTANCE( Loader )
63
64/* This function is called to check whether we run inside the emulator,
65 * and if this is the case whether GLES GPU emulation is supported.
66 *
67 * Returned values are:
68 *  -1   -> not running inside the emulator
69 *   0   -> running inside the emulator, but GPU emulation not supported
70 *   1   -> running inside the emulator, GPU emulation is supported
71 *          through the "emulation" host-side OpenGL ES implementation.
72 *   2   -> running inside the emulator, GPU emulation is supported
73 *          through a guest-side vendor driver's OpenGL ES implementation.
74 */
75static int
76checkGlesEmulationStatus(void)
77{
78    /* We're going to check for the following kernel parameters:
79     *
80     *    qemu=1                      -> tells us that we run inside the emulator
81     *    android.qemu.gles=<number>  -> tells us the GLES GPU emulation status
82     *
83     * Note that we will return <number> if we find it. This let us support
84     * more additionnal emulation modes in the future.
85     */
86    char  prop[PROPERTY_VALUE_MAX];
87    int   result = -1;
88
89    /* First, check for qemu=1 */
90    property_get("ro.kernel.qemu",prop,"0");
91    if (atoi(prop) != 1)
92        return -1;
93
94    /* We are in the emulator, get GPU status value */
95    property_get("ro.kernel.qemu.gles",prop,"0");
96    return atoi(prop);
97}
98
99// ----------------------------------------------------------------------------
100
101static char const * getProcessCmdline() {
102    long pid = getpid();
103    char procPath[128];
104    snprintf(procPath, 128, "/proc/%ld/cmdline", pid);
105    FILE * file = fopen(procPath, "r");
106    if (file) {
107        static char cmdline[256];
108        char *str = fgets(cmdline, sizeof(cmdline) - 1, file);
109        fclose(file);
110        if (str) {
111            return cmdline;
112        }
113    }
114    return NULL;
115}
116
117// ----------------------------------------------------------------------------
118
119Loader::driver_t::driver_t(void* gles)
120{
121    dso[0] = gles;
122    for (size_t i=1 ; i<NELEM(dso) ; i++)
123        dso[i] = 0;
124}
125
126Loader::driver_t::~driver_t()
127{
128    for (size_t i=0 ; i<NELEM(dso) ; i++) {
129        if (dso[i]) {
130            dlclose(dso[i]);
131            dso[i] = 0;
132        }
133    }
134}
135
136status_t Loader::driver_t::set(void* hnd, int32_t api)
137{
138    switch (api) {
139        case EGL:
140            dso[0] = hnd;
141            break;
142        case GLESv1_CM:
143            dso[1] = hnd;
144            break;
145        case GLESv2:
146            dso[2] = hnd;
147            break;
148        default:
149            return BAD_INDEX;
150    }
151    return NO_ERROR;
152}
153
154// ----------------------------------------------------------------------------
155
156Loader::Loader()
157    : getProcAddress(NULL) {
158}
159
160Loader::~Loader() {
161}
162
163static void* load_wrapper(const char* path) {
164    void* so = dlopen(path, RTLD_NOW | RTLD_LOCAL);
165    ALOGE_IF(!so, "dlopen(\"%s\") failed: %s", path, dlerror());
166    return so;
167}
168
169#ifndef EGL_WRAPPER_DIR
170#if defined(__LP64__)
171#define EGL_WRAPPER_DIR "/system/lib64"
172#else
173#define EGL_WRAPPER_DIR "/system/lib"
174#endif
175#endif
176
177void* Loader::open(egl_connection_t* cnx)
178{
179    void* dso;
180    driver_t* hnd = 0;
181
182    dso = load_driver("GLES", cnx, EGL | GLESv1_CM | GLESv2);
183    if (dso) {
184        hnd = new driver_t(dso);
185    } else {
186        // Always load EGL first
187        dso = load_driver("EGL", cnx, EGL);
188        if (dso) {
189            hnd = new driver_t(dso);
190            hnd->set( load_driver("GLESv1_CM", cnx, GLESv1_CM), GLESv1_CM );
191            hnd->set( load_driver("GLESv2",    cnx, GLESv2),    GLESv2 );
192        }
193    }
194
195    LOG_ALWAYS_FATAL_IF(!hnd, "couldn't find an OpenGL ES implementation");
196
197    cnx->libEgl   = load_wrapper(EGL_WRAPPER_DIR "/libEGL.so");
198    cnx->libGles2 = load_wrapper(EGL_WRAPPER_DIR "/libGLESv2.so");
199    cnx->libGles1 = load_wrapper(EGL_WRAPPER_DIR "/libGLESv1_CM.so");
200
201    LOG_ALWAYS_FATAL_IF(!cnx->libEgl,
202            "couldn't load system EGL wrapper libraries");
203
204    LOG_ALWAYS_FATAL_IF(!cnx->libGles2 || !cnx->libGles1,
205            "couldn't load system OpenGL ES wrapper libraries");
206
207    return (void*)hnd;
208}
209
210status_t Loader::close(void* driver)
211{
212    driver_t* hnd = (driver_t*)driver;
213    delete hnd;
214    return NO_ERROR;
215}
216
217void Loader::init_api(void* dso,
218        char const * const * api,
219        __eglMustCastToProperFunctionPointerType* curr,
220        getProcAddressType getProcAddress)
221{
222    const ssize_t SIZE = 256;
223    char scrap[SIZE];
224    while (*api) {
225        char const * name = *api;
226        __eglMustCastToProperFunctionPointerType f =
227            (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
228        if (f == NULL) {
229            // couldn't find the entry-point, use eglGetProcAddress()
230            f = getProcAddress(name);
231        }
232        if (f == NULL) {
233            // Try without the OES postfix
234            ssize_t index = ssize_t(strlen(name)) - 3;
235            if ((index>0 && (index<SIZE-1)) && (!strcmp(name+index, "OES"))) {
236                strncpy(scrap, name, index);
237                scrap[index] = 0;
238                f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
239                //ALOGD_IF(f, "found <%s> instead", scrap);
240            }
241        }
242        if (f == NULL) {
243            // Try with the OES postfix
244            ssize_t index = ssize_t(strlen(name)) - 3;
245            if (index>0 && strcmp(name+index, "OES")) {
246                snprintf(scrap, SIZE, "%sOES", name);
247                f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
248                //ALOGD_IF(f, "found <%s> instead", scrap);
249            }
250        }
251        if (f == NULL) {
252            //ALOGD("%s", name);
253            f = (__eglMustCastToProperFunctionPointerType)gl_unimplemented;
254
255            /*
256             * GL_EXT_debug_label is special, we always report it as
257             * supported, it's handled by GLES_trace. If GLES_trace is not
258             * enabled, then these are no-ops.
259             */
260            if (!strcmp(name, "glInsertEventMarkerEXT")) {
261                f = (__eglMustCastToProperFunctionPointerType)gl_noop;
262            } else if (!strcmp(name, "glPushGroupMarkerEXT")) {
263                f = (__eglMustCastToProperFunctionPointerType)gl_noop;
264            } else if (!strcmp(name, "glPopGroupMarkerEXT")) {
265                f = (__eglMustCastToProperFunctionPointerType)gl_noop;
266            }
267        }
268        *curr++ = f;
269        api++;
270    }
271}
272
273void *Loader::load_driver(const char* kind,
274        egl_connection_t* cnx, uint32_t mask)
275{
276    class MatchFile {
277    public:
278        static String8 find(const char* kind) {
279            String8 result;
280            int emulationStatus = checkGlesEmulationStatus();
281            switch (emulationStatus) {
282                case 0:
283                    ALOGD("Emulator without GPU support detected. "
284                          "Fallback to legacy software renderer.");
285#if defined(__LP64__)
286                    result.setTo("/system/lib64/egl/libGLES_android.so");
287#else
288                    result.setTo("/system/lib/egl/libGLES_android.so");
289#endif
290                    return result;
291                case 1:
292                    // Use host-side OpenGL through the "emulation" library
293#if defined(__LP64__)
294                    result.appendFormat("/system/lib64/egl/lib%s_emulation.so", kind);
295#else
296                    result.appendFormat("/system/lib/egl/lib%s_emulation.so", kind);
297#endif
298                    return result;
299                default:
300                    // Not in emulator, or use other guest-side implementation
301                    break;
302            }
303
304            String8 pattern;
305            pattern.appendFormat("lib%s", kind);
306            const char* const searchPaths[] = {
307#if defined(__LP64__)
308                    "/vendor/lib64/egl",
309                    "/system/lib64/egl"
310#else
311                    "/vendor/lib/egl",
312                    "/system/lib/egl"
313#endif
314            };
315
316            // first, we search for the exact name of the GLES userspace
317            // driver in both locations.
318            // i.e.:
319            //      libGLES.so, or:
320            //      libEGL.so, libGLESv1_CM.so, libGLESv2.so
321
322            for (size_t i=0 ; i<NELEM(searchPaths) ; i++) {
323                if (find(result, pattern, searchPaths[i], true)) {
324                    return result;
325                }
326            }
327
328            // for compatibility with the old "egl.cfg" naming convention
329            // we look for files that match:
330            //      libGLES_*.so, or:
331            //      libEGL_*.so, libGLESv1_CM_*.so, libGLESv2_*.so
332
333            pattern.append("_");
334            for (size_t i=0 ; i<NELEM(searchPaths) ; i++) {
335                if (find(result, pattern, searchPaths[i], false)) {
336                    return result;
337                }
338            }
339
340            // we didn't find the driver. gah.
341            result.clear();
342            return result;
343        }
344
345    private:
346        static bool find(String8& result,
347                const String8& pattern, const char* const search, bool exact) {
348            if (exact) {
349                String8 absolutePath;
350                absolutePath.appendFormat("%s/%s.so", search, pattern.string());
351                if (!access(absolutePath.string(), R_OK)) {
352                    result = absolutePath;
353                    return true;
354                }
355                return false;
356            }
357
358            DIR* d = opendir(search);
359            if (d != NULL) {
360                struct dirent cur;
361                struct dirent* e;
362                while (readdir_r(d, &cur, &e) == 0 && e) {
363                    if (e->d_type == DT_DIR) {
364                        continue;
365                    }
366                    if (!strcmp(e->d_name, "libGLES_android.so")) {
367                        // always skip the software renderer
368                        continue;
369                    }
370                    if (strstr(e->d_name, pattern.string()) == e->d_name) {
371                        if (!strcmp(e->d_name + strlen(e->d_name) - 3, ".so")) {
372                            result.clear();
373                            result.appendFormat("%s/%s", search, e->d_name);
374                            closedir(d);
375                            return true;
376                        }
377                    }
378                }
379                closedir(d);
380            }
381            return false;
382        }
383    };
384
385
386    String8 absolutePath = MatchFile::find(kind);
387    if (absolutePath.isEmpty()) {
388        // this happens often, we don't want to log an error
389        return 0;
390    }
391    const char* const driver_absolute_path = absolutePath.string();
392
393    void* dso = dlopen(driver_absolute_path, RTLD_NOW | RTLD_LOCAL);
394    if (dso == 0) {
395        const char* err = dlerror();
396        ALOGE("load_driver(%s): %s", driver_absolute_path, err?err:"unknown");
397        return 0;
398    }
399
400    ALOGD("loaded %s", driver_absolute_path);
401
402    if (mask & EGL) {
403        getProcAddress = (getProcAddressType)dlsym(dso, "eglGetProcAddress");
404
405        ALOGE_IF(!getProcAddress,
406                "can't find eglGetProcAddress() in %s", driver_absolute_path);
407
408        egl_t* egl = &cnx->egl;
409        __eglMustCastToProperFunctionPointerType* curr =
410            (__eglMustCastToProperFunctionPointerType*)egl;
411        char const * const * api = egl_names;
412        while (*api) {
413            char const * name = *api;
414            __eglMustCastToProperFunctionPointerType f =
415                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
416            if (f == NULL) {
417                // couldn't find the entry-point, use eglGetProcAddress()
418                f = getProcAddress(name);
419                if (f == NULL) {
420                    f = (__eglMustCastToProperFunctionPointerType)0;
421                }
422            }
423            *curr++ = f;
424            api++;
425        }
426    }
427
428    if (mask & GLESv1_CM) {
429        init_api(dso, gl_names,
430            (__eglMustCastToProperFunctionPointerType*)
431                &cnx->hooks[egl_connection_t::GLESv1_INDEX]->gl,
432            getProcAddress);
433    }
434
435    if (mask & GLESv2) {
436      init_api(dso, gl_names,
437            (__eglMustCastToProperFunctionPointerType*)
438                &cnx->hooks[egl_connection_t::GLESv2_INDEX]->gl,
439            getProcAddress);
440    }
441
442    return dso;
443}
444
445// ----------------------------------------------------------------------------
446}; // namespace android
447// ----------------------------------------------------------------------------
448