Loader.cpp revision 993814255fc248454368ed9fe34b4703a05eaf99
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 "../glestrace.h"
32
33#include "egldefs.h"
34#include "Loader.h"
35
36// ----------------------------------------------------------------------------
37namespace android {
38// ----------------------------------------------------------------------------
39
40
41/*
42 * EGL userspace drivers must be provided either:
43 * - as a single library:
44 *      /vendor/lib/egl/libGLES.so
45 *
46 * - as separate libraries:
47 *      /vendor/lib/egl/libEGL.so
48 *      /vendor/lib/egl/libGLESv1_CM.so
49 *      /vendor/lib/egl/libGLESv2.so
50 *
51 * The software renderer for the emulator must be provided as a single
52 * library at:
53 *
54 *      /system/lib/egl/libGLES_android.so
55 *
56 *
57 * For backward compatibility and to facilitate the transition to
58 * this new naming scheme, the loader will additionally look for:
59 *
60 *      /{vendor|system}/lib/egl/lib{GLES | [EGL|GLESv1_CM|GLESv2]}_*.so
61 *
62 */
63
64ANDROID_SINGLETON_STATIC_INSTANCE( Loader )
65
66/* This function is called to check whether we run inside the emulator,
67 * and if this is the case whether GLES GPU emulation is supported.
68 *
69 * Returned values are:
70 *  -1   -> not running inside the emulator
71 *   0   -> running inside the emulator, but GPU emulation not supported
72 *   1   -> running inside the emulator, GPU emulation is supported
73 *          through the "emulation" config.
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    GLTrace_stop();
162}
163
164void* Loader::open(egl_connection_t* cnx)
165{
166    void* dso;
167    driver_t* hnd = 0;
168
169    dso = load_driver("GLES", cnx, EGL | GLESv1_CM | GLESv2);
170    if (dso) {
171        hnd = new driver_t(dso);
172    } else {
173        // Always load EGL first
174        dso = load_driver("EGL", cnx, EGL);
175        if (dso) {
176            hnd = new driver_t(dso);
177            hnd->set( load_driver("GLESv1_CM", cnx, GLESv1_CM), GLESv1_CM );
178            hnd->set( load_driver("GLESv2",    cnx, GLESv2),    GLESv2 );
179        }
180    }
181
182    LOG_ALWAYS_FATAL_IF(!hnd, "couldn't find an OpenGL ES implementation");
183
184    return (void*)hnd;
185}
186
187status_t Loader::close(void* driver)
188{
189    driver_t* hnd = (driver_t*)driver;
190    delete hnd;
191    return NO_ERROR;
192}
193
194void Loader::init_api(void* dso,
195        char const * const * api,
196        __eglMustCastToProperFunctionPointerType* curr,
197        getProcAddressType getProcAddress)
198{
199    const ssize_t SIZE = 256;
200    char scrap[SIZE];
201    while (*api) {
202        char const * name = *api;
203        __eglMustCastToProperFunctionPointerType f =
204            (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
205        if (f == NULL) {
206            // couldn't find the entry-point, use eglGetProcAddress()
207            f = getProcAddress(name);
208        }
209        if (f == NULL) {
210            // Try without the OES postfix
211            ssize_t index = ssize_t(strlen(name)) - 3;
212            if ((index>0 && (index<SIZE-1)) && (!strcmp(name+index, "OES"))) {
213                strncpy(scrap, name, index);
214                scrap[index] = 0;
215                f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
216                //ALOGD_IF(f, "found <%s> instead", scrap);
217            }
218        }
219        if (f == NULL) {
220            // Try with the OES postfix
221            ssize_t index = ssize_t(strlen(name)) - 3;
222            if (index>0 && strcmp(name+index, "OES")) {
223                snprintf(scrap, SIZE, "%sOES", name);
224                f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
225                //ALOGD_IF(f, "found <%s> instead", scrap);
226            }
227        }
228        if (f == NULL) {
229            //ALOGD("%s", name);
230            f = (__eglMustCastToProperFunctionPointerType)gl_unimplemented;
231
232            /*
233             * GL_EXT_debug_label is special, we always report it as
234             * supported, it's handled by GLES_trace. If GLES_trace is not
235             * enabled, then these are no-ops.
236             */
237            if (!strcmp(name, "glInsertEventMarkerEXT")) {
238                f = (__eglMustCastToProperFunctionPointerType)gl_noop;
239            } else if (!strcmp(name, "glPushGroupMarkerEXT")) {
240                f = (__eglMustCastToProperFunctionPointerType)gl_noop;
241            } else if (!strcmp(name, "glPopGroupMarkerEXT")) {
242                f = (__eglMustCastToProperFunctionPointerType)gl_noop;
243            }
244        }
245        *curr++ = f;
246        api++;
247    }
248}
249
250void *Loader::load_driver(const char* kind,
251        egl_connection_t* cnx, uint32_t mask)
252{
253    class MatchFile {
254    public:
255        static String8 find(const char* kind) {
256            String8 result;
257            String8 pattern;
258            pattern.appendFormat("lib%s", kind);
259            const char* const searchPaths[] = {
260                    "/vendor/lib/egl",
261                    "/system/lib/egl"
262            };
263
264            // first, we search for the exact name of the GLES userspace
265            // driver in both locations.
266            // i.e.:
267            //      libGLES.so, or:
268            //      libEGL.so, libGLESv1_CM.so, libGLESv2.so
269
270            for (size_t i=0 ; i<NELEM(searchPaths) ; i++) {
271                if (find(result, pattern, searchPaths[i], true)) {
272                    return result;
273                }
274            }
275
276            // for compatibility with the old "egl.cfg" naming convention
277            // we look for files that match:
278            //      libGLES_*.so, or:
279            //      libEGL_*.so, libGLESv1_CM_*.so, libGLESv2_*.so
280
281            pattern.append("_");
282            for (size_t i=0 ; i<NELEM(searchPaths) ; i++) {
283                if (find(result, pattern, searchPaths[i], false)) {
284                    return result;
285                }
286            }
287
288            // we didn't find the driver. gah.
289            result.clear();
290            return result;
291        }
292
293    private:
294        static bool find(String8& result,
295                const String8& pattern, const char* const search, bool exact) {
296
297            // in the emulator case, we just return the hardcoded name
298            // of the software renderer.
299            if (checkGlesEmulationStatus() == 0) {
300                ALOGD("Emulator without GPU support detected. "
301                      "Fallback to software renderer.");
302                result.setTo("/system/lib/egl/libGLES_android.so");
303                return true;
304            }
305
306            if (exact) {
307                String8 absolutePath;
308                absolutePath.appendFormat("%s/%s.so", search, pattern.string());
309                if (!access(absolutePath.string(), R_OK)) {
310                    result = absolutePath;
311                    return true;
312                }
313                return false;
314            }
315
316            DIR* d = opendir(search);
317            if (d != NULL) {
318                struct dirent cur;
319                struct dirent* e;
320                while (readdir_r(d, &cur, &e) == 0 && e) {
321                    if (e->d_type == DT_DIR) {
322                        continue;
323                    }
324                    if (!strcmp(e->d_name, "libGLES_android.so")) {
325                        // always skip the software renderer
326                        continue;
327                    }
328                    if (strstr(e->d_name, pattern.string()) == e->d_name) {
329                        if (!strcmp(e->d_name + strlen(e->d_name) - 3, ".so")) {
330                            result.clear();
331                            result.appendFormat("%s/%s", search, e->d_name);
332                            closedir(d);
333                            return true;
334                        }
335                    }
336                }
337                closedir(d);
338            }
339            return false;
340        }
341    };
342
343
344    String8 absolutePath = MatchFile::find(kind);
345    if (absolutePath.isEmpty()) {
346        // this happens often, we don't want to log an error
347        return 0;
348    }
349    const char* const driver_absolute_path = absolutePath.string();
350
351    void* dso = dlopen(driver_absolute_path, RTLD_NOW | RTLD_LOCAL);
352    if (dso == 0) {
353        const char* err = dlerror();
354        ALOGE("load_driver(%s): %s", driver_absolute_path, err?err:"unknown");
355        return 0;
356    }
357
358    ALOGD("loaded %s", driver_absolute_path);
359
360    if (mask & EGL) {
361        getProcAddress = (getProcAddressType)dlsym(dso, "eglGetProcAddress");
362
363        ALOGE_IF(!getProcAddress,
364                "can't find eglGetProcAddress() in %s", driver_absolute_path);
365
366#ifdef SYSTEMUI_PBSIZE_HACK
367#warning "SYSTEMUI_PBSIZE_HACK enabled"
368        /*
369         * TODO: replace SYSTEMUI_PBSIZE_HACK by something less hackish
370         *
371         * Here we adjust the PB size from its default value to 512KB which
372         * is the minimum acceptable for the systemui process.
373         * We do this on low-end devices only because it allows us to enable
374         * h/w acceleration in the systemui process while keeping the
375         * memory usage down.
376         *
377         * Obviously, this is the wrong place and wrong way to make this
378         * adjustment, but at the time of this writing this was the safest
379         * solution.
380         */
381        const char *cmdline = getProcessCmdline();
382        if (strstr(cmdline, "systemui")) {
383            void *imgegl = dlopen("/vendor/lib/libIMGegl.so", RTLD_LAZY);
384            if (imgegl) {
385                unsigned int *PVRDefaultPBS =
386                        (unsigned int *)dlsym(imgegl, "PVRDefaultPBS");
387                if (PVRDefaultPBS) {
388                    ALOGD("setting default PBS to 512KB, was %d KB", *PVRDefaultPBS / 1024);
389                    *PVRDefaultPBS = 512*1024;
390                }
391            }
392        }
393#endif
394
395        egl_t* egl = &cnx->egl;
396        __eglMustCastToProperFunctionPointerType* curr =
397            (__eglMustCastToProperFunctionPointerType*)egl;
398        char const * const * api = egl_names;
399        while (*api) {
400            char const * name = *api;
401            __eglMustCastToProperFunctionPointerType f =
402                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
403            if (f == NULL) {
404                // couldn't find the entry-point, use eglGetProcAddress()
405                f = getProcAddress(name);
406                if (f == NULL) {
407                    f = (__eglMustCastToProperFunctionPointerType)0;
408                }
409            }
410            *curr++ = f;
411            api++;
412        }
413    }
414
415    if (mask & GLESv1_CM) {
416        init_api(dso, gl_names,
417            (__eglMustCastToProperFunctionPointerType*)
418                &cnx->hooks[egl_connection_t::GLESv1_INDEX]->gl,
419            getProcAddress);
420    }
421
422    if (mask & GLESv2) {
423      init_api(dso, gl_names,
424            (__eglMustCastToProperFunctionPointerType*)
425                &cnx->hooks[egl_connection_t::GLESv2_INDEX]->gl,
426            getProcAddress);
427    }
428
429    return dso;
430}
431
432// ----------------------------------------------------------------------------
433}; // namespace android
434// ----------------------------------------------------------------------------
435