egl.cpp revision 5e4059f646a6c648b000d1422180bd85d93c09a9
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 <string.h>
20#include <errno.h>
21#include <dlfcn.h>
22
23#include <sys/ioctl.h>
24
25#ifdef HAVE_ANDROID_OS
26#include <linux/android_pmem.h>
27#endif
28
29#include <EGL/egl.h>
30#include <EGL/eglext.h>
31#include <GLES/gl.h>
32#include <GLES/glext.h>
33
34#include <cutils/log.h>
35#include <cutils/atomic.h>
36#include <cutils/properties.h>
37#include <cutils/memory.h>
38
39#include <utils/SortedVector.h>
40#include <utils/KeyedVector.h>
41#include <utils/String8.h>
42
43#include <ui/egl/android_natives.h>
44
45#include "hooks.h"
46#include "egl_impl.h"
47#include "Loader.h"
48#include "glesv2dbg.h"
49
50#define setError(_e, _r) setErrorEtc(__FUNCTION__, __LINE__, _e, _r)
51
52// ----------------------------------------------------------------------------
53namespace android {
54// ----------------------------------------------------------------------------
55
56#define VERSION_MAJOR 1
57#define VERSION_MINOR 4
58static char const * const gVendorString     = "Android";
59static char const * const gVersionString    = "1.4 Android META-EGL";
60static char const * const gClientApiString  = "OpenGL ES";
61static char const * const gExtensionString  =
62        "EGL_KHR_image "
63        "EGL_KHR_image_base "
64        "EGL_KHR_image_pixmap "
65        "EGL_KHR_gl_texture_2D_image "
66        "EGL_KHR_gl_texture_cubemap_image "
67        "EGL_KHR_gl_renderbuffer_image "
68        "EGL_KHR_fence_sync "
69        "EGL_ANDROID_image_native_buffer "
70        "EGL_ANDROID_swap_rectangle "
71        ;
72
73// ----------------------------------------------------------------------------
74
75class egl_object_t {
76    static SortedVector<egl_object_t*> sObjects;
77    static Mutex sLock;
78
79            volatile int32_t  terminated;
80    mutable volatile int32_t  count;
81
82public:
83    egl_object_t() : terminated(0), count(1) {
84        Mutex::Autolock _l(sLock);
85        sObjects.add(this);
86    }
87
88    inline bool isAlive() const { return !terminated; }
89
90private:
91    bool get() {
92        Mutex::Autolock _l(sLock);
93        if (egl_object_t::sObjects.indexOf(this) >= 0) {
94            android_atomic_inc(&count);
95            return true;
96        }
97        return false;
98    }
99
100    bool put() {
101        Mutex::Autolock _l(sLock);
102        if (android_atomic_dec(&count) == 1) {
103            sObjects.remove(this);
104            return true;
105        }
106        return false;
107    }
108
109public:
110    template <typename N, typename T>
111    struct LocalRef {
112        N* ref;
113        LocalRef(T o) : ref(0) {
114            N* native = reinterpret_cast<N*>(o);
115            if (o && native->get()) {
116                ref = native;
117            }
118        }
119        ~LocalRef() {
120            if (ref && ref->put()) {
121                delete ref;
122            }
123        }
124        inline N* get() {
125            return ref;
126        }
127        void acquire() const {
128            if (ref) {
129                android_atomic_inc(&ref->count);
130            }
131        }
132        void release() const {
133            if (ref) {
134                int32_t c = android_atomic_dec(&ref->count);
135                // ref->count cannot be 1 prior atomic_dec because we have
136                // a reference, and if we have one, it means there was
137                // already one before us.
138                LOGE_IF(c==1, "refcount is now 0 in release()");
139            }
140        }
141        void terminate() {
142            if (ref) {
143                ref->terminated = 1;
144                release();
145            }
146        }
147    };
148};
149
150SortedVector<egl_object_t*> egl_object_t::sObjects;
151Mutex egl_object_t::sLock;
152
153
154struct egl_config_t {
155    egl_config_t() {}
156    egl_config_t(int impl, EGLConfig config)
157        : impl(impl), config(config), configId(0), implConfigId(0) { }
158    int         impl;           // the implementation this config is for
159    EGLConfig   config;         // the implementation's EGLConfig
160    EGLint      configId;       // our CONFIG_ID
161    EGLint      implConfigId;   // the implementation's CONFIG_ID
162    inline bool operator < (const egl_config_t& rhs) const {
163        if (impl < rhs.impl) return true;
164        if (impl > rhs.impl) return false;
165        return config < rhs.config;
166    }
167};
168
169struct egl_display_t {
170    enum { NOT_INITIALIZED, INITIALIZED, TERMINATED };
171
172    struct strings_t {
173        char const * vendor;
174        char const * version;
175        char const * clientApi;
176        char const * extensions;
177    };
178
179    struct DisplayImpl {
180        DisplayImpl() : dpy(EGL_NO_DISPLAY), config(0),
181                        state(NOT_INITIALIZED), numConfigs(0) { }
182        EGLDisplay  dpy;
183        EGLConfig*  config;
184        EGLint      state;
185        EGLint      numConfigs;
186        strings_t   queryString;
187    };
188
189    uint32_t        magic;
190    DisplayImpl     disp[IMPL_NUM_IMPLEMENTATIONS];
191    EGLint          numTotalConfigs;
192    egl_config_t*   configs;
193    uint32_t        refs;
194    Mutex           lock;
195
196    egl_display_t() : magic('_dpy'), numTotalConfigs(0), configs(0) { }
197    ~egl_display_t() { magic = 0; }
198    inline bool isValid() const { return magic == '_dpy'; }
199    inline bool isAlive() const { return isValid(); }
200};
201
202struct egl_surface_t : public egl_object_t
203{
204    typedef egl_object_t::LocalRef<egl_surface_t, EGLSurface> Ref;
205
206    egl_surface_t(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win,
207            EGLSurface surface, int impl, egl_connection_t const* cnx)
208    : dpy(dpy), surface(surface), config(config), win(win), impl(impl), cnx(cnx) {
209    }
210    ~egl_surface_t() {
211    }
212    EGLDisplay                  dpy;
213    EGLSurface                  surface;
214    EGLConfig                   config;
215    sp<ANativeWindow>           win;
216    int                         impl;
217    egl_connection_t const*     cnx;
218};
219
220struct egl_context_t : public egl_object_t
221{
222    typedef egl_object_t::LocalRef<egl_context_t, EGLContext> Ref;
223
224    egl_context_t(EGLDisplay dpy, EGLContext context, EGLConfig config,
225            int impl, egl_connection_t const* cnx, int version)
226    : dpy(dpy), context(context), config(config), read(0), draw(0), impl(impl),
227      cnx(cnx), version(version), dbg(NULL)
228    {
229    }
230    ~egl_context_t()
231    {
232        if (dbg)
233            DestroyDbgContext(dbg);
234        dbg = NULL;
235    }
236    EGLDisplay                  dpy;
237    EGLContext                  context;
238    EGLConfig                   config;
239    EGLSurface                  read;
240    EGLSurface                  draw;
241    int                         impl;
242    egl_connection_t const*     cnx;
243    int                         version;
244    DbgContext *                dbg;
245};
246
247struct egl_image_t : public egl_object_t
248{
249    typedef egl_object_t::LocalRef<egl_image_t, EGLImageKHR> Ref;
250
251    egl_image_t(EGLDisplay dpy, EGLContext context)
252        : dpy(dpy), context(context)
253    {
254        memset(images, 0, sizeof(images));
255    }
256    EGLDisplay dpy;
257    EGLContext context;
258    EGLImageKHR images[IMPL_NUM_IMPLEMENTATIONS];
259};
260
261struct egl_sync_t : public egl_object_t
262{
263    typedef egl_object_t::LocalRef<egl_sync_t, EGLSyncKHR> Ref;
264
265    egl_sync_t(EGLDisplay dpy, EGLContext context, EGLSyncKHR sync)
266        : dpy(dpy), context(context), sync(sync)
267    {
268    }
269    EGLDisplay dpy;
270    EGLContext context;
271    EGLSyncKHR sync;
272};
273
274typedef egl_surface_t::Ref  SurfaceRef;
275typedef egl_context_t::Ref  ContextRef;
276typedef egl_image_t::Ref    ImageRef;
277typedef egl_sync_t::Ref     SyncRef;
278
279struct tls_t
280{
281    tls_t() : error(EGL_SUCCESS), ctx(0), logCallWithNoContext(EGL_TRUE) { }
282    EGLint      error;
283    EGLContext  ctx;
284    EGLBoolean  logCallWithNoContext;
285};
286
287
288// ----------------------------------------------------------------------------
289
290static egl_connection_t gEGLImpl[IMPL_NUM_IMPLEMENTATIONS];
291static egl_display_t gDisplay[NUM_DISPLAYS];
292static pthread_mutex_t gThreadLocalStorageKeyMutex = PTHREAD_MUTEX_INITIALIZER;
293static pthread_key_t gEGLThreadLocalStorageKey = -1;
294
295// ----------------------------------------------------------------------------
296
297EGLAPI gl_hooks_t gHooks[2][IMPL_NUM_IMPLEMENTATIONS];
298EGLAPI gl_hooks_t gHooksNoContext;
299EGLAPI pthread_key_t gGLWrapperKey = -1;
300
301#if EGL_TRACE
302
303EGLAPI pthread_key_t gGLTraceKey = -1;
304
305// ----------------------------------------------------------------------------
306
307static int gEGLTraceLevel, gEGLDebugLevel;
308static int gEGLApplicationTraceLevel;
309extern EGLAPI gl_hooks_t gHooksTrace, gHooksDebug;
310
311static inline void setGlTraceThreadSpecific(gl_hooks_t const *value) {
312    pthread_setspecific(gGLTraceKey, value);
313}
314
315gl_hooks_t const* getGLTraceThreadSpecific() {
316    return static_cast<gl_hooks_t*>(pthread_getspecific(gGLTraceKey));
317}
318
319static void initEglTraceLevel() {
320    char value[PROPERTY_VALUE_MAX];
321    property_get("debug.egl.trace", value, "0");
322    int propertyLevel = atoi(value);
323    int applicationLevel = gEGLApplicationTraceLevel;
324    gEGLTraceLevel = propertyLevel > applicationLevel ? propertyLevel : applicationLevel;
325
326    property_get("debug.egl.debug_proc", value, "");
327    long pid = getpid();
328    char procPath[128] = {};
329    sprintf(procPath, "/proc/%ld/cmdline", pid);
330    FILE * file = fopen(procPath, "r");
331    if (file)
332    {
333        char cmdline[256] = {};
334        if (fgets(cmdline, sizeof(cmdline) - 1, file))
335        {
336            if (!strcmp(value, cmdline))
337                gEGLDebugLevel = 1;
338        }
339        fclose(file);
340    }
341
342    if (gEGLDebugLevel > 0)
343        StartDebugServer();
344}
345
346static void setGLHooksThreadSpecific(gl_hooks_t const *value) {
347    if (gEGLTraceLevel > 0) {
348        setGlTraceThreadSpecific(value);
349        setGlThreadSpecific(&gHooksTrace);
350    } else if (gEGLDebugLevel > 0 && value != &gHooksNoContext) {
351        setGlTraceThreadSpecific(value);
352        setGlThreadSpecific(&gHooksDebug);
353        LOGD("\n* setGLHooksThreadSpecific gHooksDebug");
354    } else {
355        setGlThreadSpecific(value);
356    }
357}
358
359/*
360 * Global entry point to allow applications to modify their own trace level.
361 * The effective trace level is the max of this level and the value of debug.egl.trace.
362 */
363extern "C"
364void setGLTraceLevel(int level) {
365    gEGLApplicationTraceLevel = level;
366}
367
368#else
369
370static inline void setGLHooksThreadSpecific(gl_hooks_t const *value) {
371    setGlThreadSpecific(value);
372}
373
374#endif
375
376// ----------------------------------------------------------------------------
377
378static __attribute__((noinline))
379const char *egl_strerror(EGLint err)
380{
381    switch (err){
382        case EGL_SUCCESS:               return "EGL_SUCCESS";
383        case EGL_NOT_INITIALIZED:       return "EGL_NOT_INITIALIZED";
384        case EGL_BAD_ACCESS:            return "EGL_BAD_ACCESS";
385        case EGL_BAD_ALLOC:             return "EGL_BAD_ALLOC";
386        case EGL_BAD_ATTRIBUTE:         return "EGL_BAD_ATTRIBUTE";
387        case EGL_BAD_CONFIG:            return "EGL_BAD_CONFIG";
388        case EGL_BAD_CONTEXT:           return "EGL_BAD_CONTEXT";
389        case EGL_BAD_CURRENT_SURFACE:   return "EGL_BAD_CURRENT_SURFACE";
390        case EGL_BAD_DISPLAY:           return "EGL_BAD_DISPLAY";
391        case EGL_BAD_MATCH:             return "EGL_BAD_MATCH";
392        case EGL_BAD_NATIVE_PIXMAP:     return "EGL_BAD_NATIVE_PIXMAP";
393        case EGL_BAD_NATIVE_WINDOW:     return "EGL_BAD_NATIVE_WINDOW";
394        case EGL_BAD_PARAMETER:         return "EGL_BAD_PARAMETER";
395        case EGL_BAD_SURFACE:           return "EGL_BAD_SURFACE";
396        case EGL_CONTEXT_LOST:          return "EGL_CONTEXT_LOST";
397        default: return "UNKNOWN";
398    }
399}
400
401static __attribute__((noinline))
402void clearTLS() {
403    if (gEGLThreadLocalStorageKey != -1) {
404        tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
405        if (tls) {
406            delete tls;
407            pthread_setspecific(gEGLThreadLocalStorageKey, 0);
408        }
409    }
410}
411
412static tls_t* getTLS()
413{
414    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
415    if (tls == 0) {
416        tls = new tls_t;
417        pthread_setspecific(gEGLThreadLocalStorageKey, tls);
418    }
419    return tls;
420}
421
422static inline void clearError() {
423    // This must clear the error from all the underlying EGL implementations as
424    // well as the EGL wrapper layer.
425    eglGetError();
426}
427
428template<typename T>
429static __attribute__((noinline))
430T setErrorEtc(const char* caller, int line, EGLint error, T returnValue) {
431    if (gEGLThreadLocalStorageKey == -1) {
432        pthread_mutex_lock(&gThreadLocalStorageKeyMutex);
433        if (gEGLThreadLocalStorageKey == -1)
434            pthread_key_create(&gEGLThreadLocalStorageKey, NULL);
435        pthread_mutex_unlock(&gThreadLocalStorageKeyMutex);
436    }
437    tls_t* tls = getTLS();
438    if (tls->error != error) {
439        LOGE("%s:%d error %x (%s)", caller, line, error, egl_strerror(error));
440        tls->error = error;
441    }
442    return returnValue;
443}
444
445static __attribute__((noinline))
446GLint getError() {
447    if (gEGLThreadLocalStorageKey == -1)
448        return EGL_SUCCESS;
449    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
450    if (!tls) return EGL_SUCCESS;
451    GLint error = tls->error;
452    tls->error = EGL_SUCCESS;
453    return error;
454}
455
456static __attribute__((noinline))
457void setContext(EGLContext ctx) {
458    if (gEGLThreadLocalStorageKey == -1) {
459        pthread_mutex_lock(&gThreadLocalStorageKeyMutex);
460        if (gEGLThreadLocalStorageKey == -1)
461            pthread_key_create(&gEGLThreadLocalStorageKey, NULL);
462        pthread_mutex_unlock(&gThreadLocalStorageKeyMutex);
463    }
464    tls_t* tls = getTLS();
465    tls->ctx = ctx;
466}
467
468static __attribute__((noinline))
469EGLContext getContext() {
470    if (gEGLThreadLocalStorageKey == -1)
471        return EGL_NO_CONTEXT;
472    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
473    if (!tls) return EGL_NO_CONTEXT;
474    return tls->ctx;
475}
476
477/*****************************************************************************/
478
479template<typename T>
480static __attribute__((noinline))
481int binarySearch(
482        T const sortedArray[], int first, int last, T key)
483{
484    while (first <= last) {
485        int mid = (first + last) / 2;
486        if (sortedArray[mid] < key) {
487            first = mid + 1;
488        } else if (key < sortedArray[mid]) {
489            last = mid - 1;
490        } else {
491            return mid;
492        }
493    }
494    return -1;
495}
496
497static int cmp_configs(const void* a, const void *b)
498{
499    const egl_config_t& c0 = *(egl_config_t const *)a;
500    const egl_config_t& c1 = *(egl_config_t const *)b;
501    return c0<c1 ? -1 : (c1<c0 ? 1 : 0);
502}
503
504struct extention_map_t {
505    const char* name;
506    __eglMustCastToProperFunctionPointerType address;
507};
508
509static const extention_map_t gExtentionMap[] = {
510    { "eglLockSurfaceKHR",
511            (__eglMustCastToProperFunctionPointerType)&eglLockSurfaceKHR },
512    { "eglUnlockSurfaceKHR",
513            (__eglMustCastToProperFunctionPointerType)&eglUnlockSurfaceKHR },
514    { "eglCreateImageKHR",
515            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR },
516    { "eglDestroyImageKHR",
517            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR },
518    { "eglSetSwapRectangleANDROID",
519            (__eglMustCastToProperFunctionPointerType)&eglSetSwapRectangleANDROID },
520};
521
522extern const __eglMustCastToProperFunctionPointerType gExtensionForwarders[MAX_NUMBER_OF_GL_EXTENSIONS];
523
524// accesses protected by gInitDriverMutex
525static DefaultKeyedVector<String8, __eglMustCastToProperFunctionPointerType> gGLExtentionMap;
526static int gGLExtentionSlot = 0;
527
528static void(*findProcAddress(const char* name,
529        const extention_map_t* map, size_t n))()
530{
531    for (uint32_t i=0 ; i<n ; i++) {
532        if (!strcmp(name, map[i].name)) {
533            return map[i].address;
534        }
535    }
536    return NULL;
537}
538
539// ----------------------------------------------------------------------------
540
541static int gl_no_context() {
542    tls_t* tls = getTLS();
543    if (tls->logCallWithNoContext == EGL_TRUE) {
544        tls->logCallWithNoContext = EGL_FALSE;
545        LOGE("call to OpenGL ES API with no current context "
546             "(logged once per thread)");
547    }
548    return 0;
549}
550
551static void early_egl_init(void)
552{
553#if !USE_FAST_TLS_KEY
554    pthread_key_create(&gGLWrapperKey, NULL);
555#endif
556#if EGL_TRACE
557    pthread_key_create(&gGLTraceKey, NULL);
558    initEglTraceLevel();
559#endif
560    uint32_t addr = (uint32_t)((void*)gl_no_context);
561    android_memset32(
562            (uint32_t*)(void*)&gHooksNoContext,
563            addr,
564            sizeof(gHooksNoContext));
565
566    setGLHooksThreadSpecific(&gHooksNoContext);
567}
568
569static pthread_once_t once_control = PTHREAD_ONCE_INIT;
570static int sEarlyInitState = pthread_once(&once_control, &early_egl_init);
571
572
573static inline
574egl_display_t* get_display(EGLDisplay dpy)
575{
576    uintptr_t index = uintptr_t(dpy)-1U;
577    return (index >= NUM_DISPLAYS) ? NULL : &gDisplay[index];
578}
579
580template<typename NATIVE, typename EGL>
581static inline NATIVE* egl_to_native_cast(EGL arg) {
582    return reinterpret_cast<NATIVE*>(arg);
583}
584
585static inline
586egl_surface_t* get_surface(EGLSurface surface) {
587    return egl_to_native_cast<egl_surface_t>(surface);
588}
589
590static inline
591egl_context_t* get_context(EGLContext context) {
592    return egl_to_native_cast<egl_context_t>(context);
593}
594
595DbgContext * getDbgContextThreadSpecific()
596{
597    return get_context(getContext())->dbg;
598}
599
600static inline
601egl_image_t* get_image(EGLImageKHR image) {
602    return egl_to_native_cast<egl_image_t>(image);
603}
604
605static inline
606egl_sync_t* get_sync(EGLSyncKHR sync) {
607    return egl_to_native_cast<egl_sync_t>(sync);
608}
609
610static egl_connection_t* validate_display_config(
611        EGLDisplay dpy, EGLConfig config,
612        egl_display_t const*& dp)
613{
614    dp = get_display(dpy);
615    if (!dp) return setError(EGL_BAD_DISPLAY, (egl_connection_t*)NULL);
616
617    if (intptr_t(config) >= dp->numTotalConfigs) {
618        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
619    }
620    egl_connection_t* const cnx = &gEGLImpl[dp->configs[intptr_t(config)].impl];
621    if (cnx->dso == 0) {
622        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
623    }
624    return cnx;
625}
626
627static EGLBoolean validate_display_context(EGLDisplay dpy, EGLContext ctx)
628{
629    if ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS)
630        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
631    if (!get_display(dpy)->isAlive())
632        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
633    if (!get_context(ctx)->isAlive())
634        return setError(EGL_BAD_CONTEXT, EGL_FALSE);
635    return EGL_TRUE;
636}
637
638static EGLBoolean validate_display_surface(EGLDisplay dpy, EGLSurface surface)
639{
640    if ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS)
641        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
642    if (!get_display(dpy)->isAlive())
643        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
644    if (!get_surface(surface)->isAlive())
645        return setError(EGL_BAD_SURFACE, EGL_FALSE);
646    return EGL_TRUE;
647}
648
649EGLImageKHR egl_get_image_for_current_context(EGLImageKHR image)
650{
651    ImageRef _i(image);
652    if (!_i.get()) return EGL_NO_IMAGE_KHR;
653
654    EGLContext context = getContext();
655    if (context == EGL_NO_CONTEXT || image == EGL_NO_IMAGE_KHR)
656        return EGL_NO_IMAGE_KHR;
657
658    egl_context_t const * const c = get_context(context);
659    if (!c->isAlive())
660        return EGL_NO_IMAGE_KHR;
661
662    egl_image_t const * const i = get_image(image);
663    return i->images[c->impl];
664}
665
666// ----------------------------------------------------------------------------
667
668// this mutex protects:
669//    d->disp[]
670//    egl_init_drivers_locked()
671//
672static pthread_mutex_t gInitDriverMutex = PTHREAD_MUTEX_INITIALIZER;
673
674EGLBoolean egl_init_drivers_locked()
675{
676    if (sEarlyInitState) {
677        // initialized by static ctor. should be set here.
678        return EGL_FALSE;
679    }
680
681    // get our driver loader
682    Loader& loader(Loader::getInstance());
683
684    // dynamically load all our EGL implementations for all displays
685    // and retrieve the corresponding EGLDisplay
686    // if that fails, don't use this driver.
687    // TODO: currently we only deal with EGL_DEFAULT_DISPLAY
688    egl_connection_t* cnx;
689    egl_display_t* d = &gDisplay[0];
690
691    cnx = &gEGLImpl[IMPL_SOFTWARE];
692    if (cnx->dso == 0) {
693        cnx->hooks[GLESv1_INDEX] = &gHooks[GLESv1_INDEX][IMPL_SOFTWARE];
694        cnx->hooks[GLESv2_INDEX] = &gHooks[GLESv2_INDEX][IMPL_SOFTWARE];
695        cnx->dso = loader.open(EGL_DEFAULT_DISPLAY, 0, cnx);
696        if (cnx->dso) {
697            EGLDisplay dpy = cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
698            LOGE_IF(dpy==EGL_NO_DISPLAY, "No EGLDisplay for software EGL!");
699            d->disp[IMPL_SOFTWARE].dpy = dpy;
700            if (dpy == EGL_NO_DISPLAY) {
701                loader.close(cnx->dso);
702                cnx->dso = NULL;
703            }
704        }
705    }
706
707    cnx = &gEGLImpl[IMPL_HARDWARE];
708    if (cnx->dso == 0) {
709        char value[PROPERTY_VALUE_MAX];
710        property_get("debug.egl.hw", value, "1");
711        if (atoi(value) != 0) {
712            cnx->hooks[GLESv1_INDEX] = &gHooks[GLESv1_INDEX][IMPL_HARDWARE];
713            cnx->hooks[GLESv2_INDEX] = &gHooks[GLESv2_INDEX][IMPL_HARDWARE];
714            cnx->dso = loader.open(EGL_DEFAULT_DISPLAY, 1, cnx);
715            if (cnx->dso) {
716                EGLDisplay dpy = cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
717                LOGE_IF(dpy==EGL_NO_DISPLAY, "No EGLDisplay for hardware EGL!");
718                d->disp[IMPL_HARDWARE].dpy = dpy;
719                if (dpy == EGL_NO_DISPLAY) {
720                    loader.close(cnx->dso);
721                    cnx->dso = NULL;
722                }
723            }
724        } else {
725            LOGD("3D hardware acceleration is disabled");
726        }
727    }
728
729    if (!gEGLImpl[IMPL_SOFTWARE].dso && !gEGLImpl[IMPL_HARDWARE].dso) {
730        return EGL_FALSE;
731    }
732
733    return EGL_TRUE;
734}
735
736EGLBoolean egl_init_drivers()
737{
738    EGLBoolean res;
739    pthread_mutex_lock(&gInitDriverMutex);
740    res = egl_init_drivers_locked();
741    pthread_mutex_unlock(&gInitDriverMutex);
742    return res;
743}
744
745// ----------------------------------------------------------------------------
746}; // namespace android
747// ----------------------------------------------------------------------------
748
749using namespace android;
750
751EGLDisplay eglGetDisplay(NativeDisplayType display)
752{
753    clearError();
754
755    uint32_t index = uint32_t(display);
756    if (index >= NUM_DISPLAYS) {
757        return setError(EGL_BAD_PARAMETER, EGL_NO_DISPLAY);
758    }
759
760    if (egl_init_drivers() == EGL_FALSE) {
761        return setError(EGL_BAD_PARAMETER, EGL_NO_DISPLAY);
762    }
763
764    EGLDisplay dpy = EGLDisplay(uintptr_t(display) + 1LU);
765    return dpy;
766}
767
768// ----------------------------------------------------------------------------
769// Initialization
770// ----------------------------------------------------------------------------
771
772EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
773{
774    clearError();
775
776    egl_display_t * const dp = get_display(dpy);
777    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
778
779    Mutex::Autolock _l(dp->lock);
780
781    if (dp->refs > 0) {
782        if (major != NULL) *major = VERSION_MAJOR;
783        if (minor != NULL) *minor = VERSION_MINOR;
784        dp->refs++;
785        return EGL_TRUE;
786    }
787
788#if EGL_TRACE
789
790    // Called both at early_init time and at this time. (Early_init is pre-zygote, so
791    // the information from that call may be stale.)
792    initEglTraceLevel();
793
794#endif
795
796    setGLHooksThreadSpecific(&gHooksNoContext);
797
798    // initialize each EGL and
799    // build our own extension string first, based on the extension we know
800    // and the extension supported by our client implementation
801    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
802        egl_connection_t* const cnx = &gEGLImpl[i];
803        cnx->major = -1;
804        cnx->minor = -1;
805        if (!cnx->dso)
806            continue;
807
808#if defined(ADRENO130)
809#warning "Adreno-130 eglInitialize() workaround"
810        /*
811         * The ADRENO 130 driver returns a different EGLDisplay each time
812         * eglGetDisplay() is called, but also makes the EGLDisplay invalid
813         * after eglTerminate() has been called, so that eglInitialize()
814         * cannot be called again. Therefore, we need to make sure to call
815         * eglGetDisplay() before calling eglInitialize();
816         */
817        if (i == IMPL_HARDWARE) {
818            dp->disp[i].dpy =
819                cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
820        }
821#endif
822
823
824        EGLDisplay idpy = dp->disp[i].dpy;
825        if (cnx->egl.eglInitialize(idpy, &cnx->major, &cnx->minor)) {
826            //LOGD("initialized %d dpy=%p, ver=%d.%d, cnx=%p",
827            //        i, idpy, cnx->major, cnx->minor, cnx);
828
829            // display is now initialized
830            dp->disp[i].state = egl_display_t::INITIALIZED;
831
832            // get the query-strings for this display for each implementation
833            dp->disp[i].queryString.vendor =
834                cnx->egl.eglQueryString(idpy, EGL_VENDOR);
835            dp->disp[i].queryString.version =
836                cnx->egl.eglQueryString(idpy, EGL_VERSION);
837            dp->disp[i].queryString.extensions =
838                    cnx->egl.eglQueryString(idpy, EGL_EXTENSIONS);
839            dp->disp[i].queryString.clientApi =
840                cnx->egl.eglQueryString(idpy, EGL_CLIENT_APIS);
841
842        } else {
843            LOGW("%d: eglInitialize(%p) failed (%s)", i, idpy,
844                    egl_strerror(cnx->egl.eglGetError()));
845        }
846    }
847
848    EGLBoolean res = EGL_FALSE;
849    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
850        egl_connection_t* const cnx = &gEGLImpl[i];
851        if (cnx->dso && cnx->major>=0 && cnx->minor>=0) {
852            EGLint n;
853            if (cnx->egl.eglGetConfigs(dp->disp[i].dpy, 0, 0, &n)) {
854                dp->disp[i].config = (EGLConfig*)malloc(sizeof(EGLConfig)*n);
855                if (dp->disp[i].config) {
856                    if (cnx->egl.eglGetConfigs(
857                            dp->disp[i].dpy, dp->disp[i].config, n,
858                            &dp->disp[i].numConfigs))
859                    {
860                        dp->numTotalConfigs += n;
861                        res = EGL_TRUE;
862                    }
863                }
864            }
865        }
866    }
867
868    if (res == EGL_TRUE) {
869        dp->configs = new egl_config_t[ dp->numTotalConfigs ];
870        for (int i=0, k=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
871            egl_connection_t* const cnx = &gEGLImpl[i];
872            if (cnx->dso && cnx->major>=0 && cnx->minor>=0) {
873                for (int j=0 ; j<dp->disp[i].numConfigs ; j++) {
874                    dp->configs[k].impl = i;
875                    dp->configs[k].config = dp->disp[i].config[j];
876                    dp->configs[k].configId = k + 1; // CONFIG_ID start at 1
877                    // store the implementation's CONFIG_ID
878                    cnx->egl.eglGetConfigAttrib(
879                            dp->disp[i].dpy,
880                            dp->disp[i].config[j],
881                            EGL_CONFIG_ID,
882                            &dp->configs[k].implConfigId);
883                    k++;
884                }
885            }
886        }
887
888        // sort our configurations so we can do binary-searches
889        qsort(  dp->configs,
890                dp->numTotalConfigs,
891                sizeof(egl_config_t), cmp_configs);
892
893        dp->refs++;
894        if (major != NULL) *major = VERSION_MAJOR;
895        if (minor != NULL) *minor = VERSION_MINOR;
896        return EGL_TRUE;
897    }
898    return setError(EGL_NOT_INITIALIZED, EGL_FALSE);
899}
900
901EGLBoolean eglTerminate(EGLDisplay dpy)
902{
903    // NOTE: don't unload the drivers b/c some APIs can be called
904    // after eglTerminate() has been called. eglTerminate() only
905    // terminates an EGLDisplay, not a EGL itself.
906
907    clearError();
908
909    egl_display_t* const dp = get_display(dpy);
910    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
911
912    Mutex::Autolock _l(dp->lock);
913
914    if (dp->refs == 0) {
915        return setError(EGL_NOT_INITIALIZED, EGL_FALSE);
916    }
917
918    // this is specific to Android, display termination is ref-counted.
919    if (dp->refs > 1) {
920        dp->refs--;
921        return EGL_TRUE;
922    }
923
924    EGLBoolean res = EGL_FALSE;
925    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
926        egl_connection_t* const cnx = &gEGLImpl[i];
927        if (cnx->dso && dp->disp[i].state == egl_display_t::INITIALIZED) {
928            if (cnx->egl.eglTerminate(dp->disp[i].dpy) == EGL_FALSE) {
929                LOGW("%d: eglTerminate(%p) failed (%s)", i, dp->disp[i].dpy,
930                        egl_strerror(cnx->egl.eglGetError()));
931            }
932            // REVISIT: it's unclear what to do if eglTerminate() fails
933            free(dp->disp[i].config);
934
935            dp->disp[i].numConfigs = 0;
936            dp->disp[i].config = 0;
937            dp->disp[i].state = egl_display_t::TERMINATED;
938
939            res = EGL_TRUE;
940        }
941    }
942
943    // TODO: all egl_object_t should be marked for termination
944
945    dp->refs--;
946    dp->numTotalConfigs = 0;
947    delete [] dp->configs;
948
949    return res;
950}
951
952// ----------------------------------------------------------------------------
953// configuration
954// ----------------------------------------------------------------------------
955
956EGLBoolean eglGetConfigs(   EGLDisplay dpy,
957                            EGLConfig *configs,
958                            EGLint config_size, EGLint *num_config)
959{
960    clearError();
961
962    egl_display_t const * const dp = get_display(dpy);
963    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
964
965    GLint numConfigs = dp->numTotalConfigs;
966    if (!configs) {
967        *num_config = numConfigs;
968        return EGL_TRUE;
969    }
970
971    GLint n = 0;
972    for (intptr_t i=0 ; i<dp->numTotalConfigs && config_size ; i++) {
973        *configs++ = EGLConfig(i);
974        config_size--;
975        n++;
976    }
977
978    *num_config = n;
979    return EGL_TRUE;
980}
981
982EGLBoolean eglChooseConfig( EGLDisplay dpy, const EGLint *attrib_list,
983                            EGLConfig *configs, EGLint config_size,
984                            EGLint *num_config)
985{
986    clearError();
987
988    egl_display_t const * const dp = get_display(dpy);
989    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
990
991    if (num_config==0) {
992        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
993    }
994
995    EGLint n;
996    EGLBoolean res = EGL_FALSE;
997    *num_config = 0;
998
999
1000    // It is unfortunate, but we need to remap the EGL_CONFIG_IDs,
1001    // to do this, we have to go through the attrib_list array once
1002    // to figure out both its size and if it contains an EGL_CONFIG_ID
1003    // key. If so, the full array is copied and patched.
1004    // NOTE: we assume that there can be only one occurrence
1005    // of EGL_CONFIG_ID.
1006
1007    EGLint patch_index = -1;
1008    GLint attr;
1009    size_t size = 0;
1010    if (attrib_list) {
1011        while ((attr=attrib_list[size]) != EGL_NONE) {
1012            if (attr == EGL_CONFIG_ID)
1013                patch_index = size;
1014            size += 2;
1015        }
1016    }
1017    if (patch_index >= 0) {
1018        size += 2; // we need copy the sentinel as well
1019        EGLint* new_list = (EGLint*)malloc(size*sizeof(EGLint));
1020        if (new_list == 0)
1021            return setError(EGL_BAD_ALLOC, EGL_FALSE);
1022        memcpy(new_list, attrib_list, size*sizeof(EGLint));
1023
1024        // patch the requested EGL_CONFIG_ID
1025        bool found = false;
1026        EGLConfig ourConfig(0);
1027        EGLint& configId(new_list[patch_index+1]);
1028        for (intptr_t i=0 ; i<dp->numTotalConfigs ; i++) {
1029            if (dp->configs[i].configId == configId) {
1030                ourConfig = EGLConfig(i);
1031                configId = dp->configs[i].implConfigId;
1032                found = true;
1033                break;
1034            }
1035        }
1036
1037        egl_connection_t* const cnx = &gEGLImpl[dp->configs[intptr_t(ourConfig)].impl];
1038        if (found && cnx->dso) {
1039            // and switch to the new list
1040            attrib_list = const_cast<const EGLint *>(new_list);
1041
1042            // At this point, the only configuration that can match is
1043            // dp->configs[i][index], however, we don't know if it would be
1044            // rejected because of the other attributes, so we do have to call
1045            // cnx->egl.eglChooseConfig() -- but we don't have to loop
1046            // through all the EGLimpl[].
1047            // We also know we can only get a single config back, and we know
1048            // which one.
1049
1050            res = cnx->egl.eglChooseConfig(
1051                    dp->disp[ dp->configs[intptr_t(ourConfig)].impl ].dpy,
1052                    attrib_list, configs, config_size, &n);
1053            if (res && n>0) {
1054                // n has to be 0 or 1, by construction, and we already know
1055                // which config it will return (since there can be only one).
1056                if (configs) {
1057                    configs[0] = ourConfig;
1058                }
1059                *num_config = 1;
1060            }
1061        }
1062
1063        free(const_cast<EGLint *>(attrib_list));
1064        return res;
1065    }
1066
1067
1068    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1069        egl_connection_t* const cnx = &gEGLImpl[i];
1070        if (cnx->dso) {
1071            if (cnx->egl.eglChooseConfig(
1072                    dp->disp[i].dpy, attrib_list, configs, config_size, &n)) {
1073                if (configs) {
1074                    // now we need to convert these client EGLConfig to our
1075                    // internal EGLConfig format.
1076                    // This is done in O(n Log(n)) time.
1077                    for (int j=0 ; j<n ; j++) {
1078                        egl_config_t key(i, configs[j]);
1079                        intptr_t index = binarySearch<egl_config_t>(
1080                                dp->configs, 0, dp->numTotalConfigs, key);
1081                        if (index >= 0) {
1082                            configs[j] = EGLConfig(index);
1083                        } else {
1084                            return setError(EGL_BAD_CONFIG, EGL_FALSE);
1085                        }
1086                    }
1087                    configs += n;
1088                    config_size -= n;
1089                }
1090                *num_config += n;
1091                res = EGL_TRUE;
1092            }
1093        }
1094    }
1095    return res;
1096}
1097
1098EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
1099        EGLint attribute, EGLint *value)
1100{
1101    clearError();
1102
1103    egl_display_t const* dp = 0;
1104    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1105    if (!cnx) return EGL_FALSE;
1106
1107    if (attribute == EGL_CONFIG_ID) {
1108        *value = dp->configs[intptr_t(config)].configId;
1109        return EGL_TRUE;
1110    }
1111    return cnx->egl.eglGetConfigAttrib(
1112            dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1113            dp->configs[intptr_t(config)].config, attribute, value);
1114}
1115
1116// ----------------------------------------------------------------------------
1117// surfaces
1118// ----------------------------------------------------------------------------
1119
1120EGLSurface eglCreateWindowSurface(  EGLDisplay dpy, EGLConfig config,
1121                                    NativeWindowType window,
1122                                    const EGLint *attrib_list)
1123{
1124    clearError();
1125
1126    egl_display_t const* dp = 0;
1127    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1128    if (cnx) {
1129        EGLDisplay iDpy = dp->disp[ dp->configs[intptr_t(config)].impl ].dpy;
1130        EGLConfig iConfig = dp->configs[intptr_t(config)].config;
1131        EGLint format;
1132
1133        // for now fail if the window is not a Surface.
1134        int type = -1;
1135        ANativeWindow* anw = reinterpret_cast<ANativeWindow*>(window);
1136        if ((anw->query(window, NATIVE_WINDOW_CONCRETE_TYPE, &type) != 0) ||
1137                (type == NATIVE_WINDOW_SURFACE_TEXTURE_CLIENT)) {
1138            LOGE("native window is a SurfaceTextureClient (currently "
1139                    "unsupported)");
1140            return setError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
1141        }
1142
1143        // set the native window's buffers format to match this config
1144        if (cnx->egl.eglGetConfigAttrib(iDpy,
1145                iConfig, EGL_NATIVE_VISUAL_ID, &format)) {
1146            if (format != 0) {
1147                native_window_set_buffers_geometry(window, 0, 0, format);
1148            }
1149        }
1150
1151        EGLSurface surface = cnx->egl.eglCreateWindowSurface(
1152                iDpy, iConfig, window, attrib_list);
1153        if (surface != EGL_NO_SURFACE) {
1154            egl_surface_t* s = new egl_surface_t(dpy, config, window, surface,
1155                    dp->configs[intptr_t(config)].impl, cnx);
1156            return s;
1157        }
1158    }
1159    return EGL_NO_SURFACE;
1160}
1161
1162EGLSurface eglCreatePixmapSurface(  EGLDisplay dpy, EGLConfig config,
1163                                    NativePixmapType pixmap,
1164                                    const EGLint *attrib_list)
1165{
1166    clearError();
1167
1168    egl_display_t const* dp = 0;
1169    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1170    if (cnx) {
1171        EGLSurface surface = cnx->egl.eglCreatePixmapSurface(
1172                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1173                dp->configs[intptr_t(config)].config, pixmap, attrib_list);
1174        if (surface != EGL_NO_SURFACE) {
1175            egl_surface_t* s = new egl_surface_t(dpy, config, NULL, surface,
1176                    dp->configs[intptr_t(config)].impl, cnx);
1177            return s;
1178        }
1179    }
1180    return EGL_NO_SURFACE;
1181}
1182
1183EGLSurface eglCreatePbufferSurface( EGLDisplay dpy, EGLConfig config,
1184                                    const EGLint *attrib_list)
1185{
1186    clearError();
1187
1188    egl_display_t const* dp = 0;
1189    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1190    if (cnx) {
1191        EGLSurface surface = cnx->egl.eglCreatePbufferSurface(
1192                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1193                dp->configs[intptr_t(config)].config, attrib_list);
1194        if (surface != EGL_NO_SURFACE) {
1195            egl_surface_t* s = new egl_surface_t(dpy, config, NULL, surface,
1196                    dp->configs[intptr_t(config)].impl, cnx);
1197            return s;
1198        }
1199    }
1200    return EGL_NO_SURFACE;
1201}
1202
1203EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
1204{
1205    clearError();
1206
1207    SurfaceRef _s(surface);
1208    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1209
1210    if (!validate_display_surface(dpy, surface))
1211        return EGL_FALSE;
1212    egl_display_t const * const dp = get_display(dpy);
1213
1214    egl_surface_t * const s = get_surface(surface);
1215    EGLBoolean result = s->cnx->egl.eglDestroySurface(
1216            dp->disp[s->impl].dpy, s->surface);
1217    if (result == EGL_TRUE) {
1218        if (s->win != NULL) {
1219            native_window_set_buffers_geometry(s->win.get(), 0, 0, 0);
1220        }
1221        _s.terminate();
1222    }
1223    return result;
1224}
1225
1226EGLBoolean eglQuerySurface( EGLDisplay dpy, EGLSurface surface,
1227                            EGLint attribute, EGLint *value)
1228{
1229    clearError();
1230
1231    SurfaceRef _s(surface);
1232    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1233
1234    if (!validate_display_surface(dpy, surface))
1235        return EGL_FALSE;
1236    egl_display_t const * const dp = get_display(dpy);
1237    egl_surface_t const * const s = get_surface(surface);
1238
1239    EGLBoolean result(EGL_TRUE);
1240    if (attribute == EGL_CONFIG_ID) {
1241        // We need to remap EGL_CONFIG_IDs
1242        *value = dp->configs[intptr_t(s->config)].configId;
1243    } else {
1244        result = s->cnx->egl.eglQuerySurface(
1245                dp->disp[s->impl].dpy, s->surface, attribute, value);
1246    }
1247
1248    return result;
1249}
1250
1251// ----------------------------------------------------------------------------
1252// Contexts
1253// ----------------------------------------------------------------------------
1254
1255EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config,
1256                            EGLContext share_list, const EGLint *attrib_list)
1257{
1258    clearError();
1259
1260    egl_display_t const* dp = 0;
1261    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1262    if (cnx) {
1263        if (share_list != EGL_NO_CONTEXT) {
1264            egl_context_t* const c = get_context(share_list);
1265            share_list = c->context;
1266        }
1267        EGLContext context = cnx->egl.eglCreateContext(
1268                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1269                dp->configs[intptr_t(config)].config,
1270                share_list, attrib_list);
1271        if (context != EGL_NO_CONTEXT) {
1272            // figure out if it's a GLESv1 or GLESv2
1273            int version = 0;
1274            if (attrib_list) {
1275                while (*attrib_list != EGL_NONE) {
1276                    GLint attr = *attrib_list++;
1277                    GLint value = *attrib_list++;
1278                    if (attr == EGL_CONTEXT_CLIENT_VERSION) {
1279                        if (value == 1) {
1280                            version = GLESv1_INDEX;
1281                        } else if (value == 2) {
1282                            version = GLESv2_INDEX;
1283                        }
1284                    }
1285                };
1286            }
1287            egl_context_t* c = new egl_context_t(dpy, context, config,
1288                    dp->configs[intptr_t(config)].impl, cnx, version);
1289            return c;
1290        }
1291    }
1292    return EGL_NO_CONTEXT;
1293}
1294
1295EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
1296{
1297    clearError();
1298
1299    ContextRef _c(ctx);
1300    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1301
1302    if (!validate_display_context(dpy, ctx))
1303        return EGL_FALSE;
1304    egl_display_t const * const dp = get_display(dpy);
1305    egl_context_t * const c = get_context(ctx);
1306    EGLBoolean result = c->cnx->egl.eglDestroyContext(
1307            dp->disp[c->impl].dpy, c->context);
1308    if (result == EGL_TRUE) {
1309        _c.terminate();
1310    }
1311    return result;
1312}
1313
1314static void loseCurrent(egl_context_t * cur_c)
1315{
1316    if (cur_c) {
1317        egl_surface_t * cur_r = get_surface(cur_c->read);
1318        egl_surface_t * cur_d = get_surface(cur_c->draw);
1319
1320        // by construction, these are either 0 or valid (possibly terminated)
1321        // it should be impossible for these to be invalid
1322        ContextRef _cur_c(cur_c);
1323        SurfaceRef _cur_r(cur_r);
1324        SurfaceRef _cur_d(cur_d);
1325
1326        cur_c->read = NULL;
1327        cur_c->draw = NULL;
1328
1329        _cur_c.release();
1330        _cur_r.release();
1331        _cur_d.release();
1332    }
1333}
1334
1335EGLBoolean eglMakeCurrent(  EGLDisplay dpy, EGLSurface draw,
1336                            EGLSurface read, EGLContext ctx)
1337{
1338    clearError();
1339
1340    // get a reference to the object passed in
1341    ContextRef _c(ctx);
1342    SurfaceRef _d(draw);
1343    SurfaceRef _r(read);
1344
1345    // validate the display and the context (if not EGL_NO_CONTEXT)
1346    egl_display_t const * const dp = get_display(dpy);
1347    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1348    if ((ctx != EGL_NO_CONTEXT) && (!validate_display_context(dpy, ctx))) {
1349        // EGL_NO_CONTEXT is valid
1350        return EGL_FALSE;
1351    }
1352
1353    // these are the underlying implementation's object
1354    EGLContext impl_ctx  = EGL_NO_CONTEXT;
1355    EGLSurface impl_draw = EGL_NO_SURFACE;
1356    EGLSurface impl_read = EGL_NO_SURFACE;
1357
1358    // these are our objects structs passed in
1359    egl_context_t       * c = NULL;
1360    egl_surface_t const * d = NULL;
1361    egl_surface_t const * r = NULL;
1362
1363    // these are the current objects structs
1364    egl_context_t * cur_c = get_context(getContext());
1365
1366    if (ctx != EGL_NO_CONTEXT) {
1367        c = get_context(ctx);
1368        impl_ctx = c->context;
1369    } else {
1370        // no context given, use the implementation of the current context
1371        if (cur_c == NULL) {
1372            // no current context
1373            if (draw != EGL_NO_SURFACE || read != EGL_NO_SURFACE) {
1374                // calling eglMakeCurrent( ..., !=0, !=0, EGL_NO_CONTEXT);
1375                return setError(EGL_BAD_MATCH, EGL_FALSE);
1376            }
1377            // not an error, there is just no current context.
1378            return EGL_TRUE;
1379        }
1380    }
1381
1382    // retrieve the underlying implementation's draw EGLSurface
1383    if (draw != EGL_NO_SURFACE) {
1384        d = get_surface(draw);
1385        // make sure the EGLContext and EGLSurface passed in are for
1386        // the same driver
1387        if (c && d->impl != c->impl)
1388            return setError(EGL_BAD_MATCH, EGL_FALSE);
1389        impl_draw = d->surface;
1390    }
1391
1392    // retrieve the underlying implementation's read EGLSurface
1393    if (read != EGL_NO_SURFACE) {
1394        r = get_surface(read);
1395        // make sure the EGLContext and EGLSurface passed in are for
1396        // the same driver
1397        if (c && r->impl != c->impl)
1398            return setError(EGL_BAD_MATCH, EGL_FALSE);
1399        impl_read = r->surface;
1400    }
1401
1402    EGLBoolean result;
1403
1404    if (c) {
1405        result = c->cnx->egl.eglMakeCurrent(
1406                dp->disp[c->impl].dpy, impl_draw, impl_read, impl_ctx);
1407    } else {
1408        result = cur_c->cnx->egl.eglMakeCurrent(
1409                dp->disp[cur_c->impl].dpy, impl_draw, impl_read, impl_ctx);
1410    }
1411
1412    if (result == EGL_TRUE) {
1413
1414        loseCurrent(cur_c);
1415
1416        if (ctx != EGL_NO_CONTEXT) {
1417            if (!c->dbg && gEGLDebugLevel > 0)
1418                c->dbg = CreateDbgContext(c->version, c->cnx->hooks[c->version]);
1419            setGLHooksThreadSpecific(c->cnx->hooks[c->version]);
1420            setContext(ctx);
1421            _c.acquire();
1422            _r.acquire();
1423            _d.acquire();
1424            c->read = read;
1425            c->draw = draw;
1426        } else {
1427            setGLHooksThreadSpecific(&gHooksNoContext);
1428            setContext(EGL_NO_CONTEXT);
1429        }
1430    }
1431    return result;
1432}
1433
1434
1435EGLBoolean eglQueryContext( EGLDisplay dpy, EGLContext ctx,
1436                            EGLint attribute, EGLint *value)
1437{
1438    clearError();
1439
1440    ContextRef _c(ctx);
1441    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1442
1443    if (!validate_display_context(dpy, ctx))
1444        return EGL_FALSE;
1445
1446    egl_display_t const * const dp = get_display(dpy);
1447    egl_context_t * const c = get_context(ctx);
1448
1449    EGLBoolean result(EGL_TRUE);
1450    if (attribute == EGL_CONFIG_ID) {
1451        *value = dp->configs[intptr_t(c->config)].configId;
1452    } else {
1453        // We need to remap EGL_CONFIG_IDs
1454        result = c->cnx->egl.eglQueryContext(
1455                dp->disp[c->impl].dpy, c->context, attribute, value);
1456    }
1457
1458    return result;
1459}
1460
1461EGLContext eglGetCurrentContext(void)
1462{
1463    // could be called before eglInitialize(), but we wouldn't have a context
1464    // then, and this function would correctly return EGL_NO_CONTEXT.
1465
1466    clearError();
1467
1468    EGLContext ctx = getContext();
1469    return ctx;
1470}
1471
1472EGLSurface eglGetCurrentSurface(EGLint readdraw)
1473{
1474    // could be called before eglInitialize(), but we wouldn't have a context
1475    // then, and this function would correctly return EGL_NO_SURFACE.
1476
1477    clearError();
1478
1479    EGLContext ctx = getContext();
1480    if (ctx) {
1481        egl_context_t const * const c = get_context(ctx);
1482        if (!c) return setError(EGL_BAD_CONTEXT, EGL_NO_SURFACE);
1483        switch (readdraw) {
1484            case EGL_READ: return c->read;
1485            case EGL_DRAW: return c->draw;
1486            default: return setError(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
1487        }
1488    }
1489    return EGL_NO_SURFACE;
1490}
1491
1492EGLDisplay eglGetCurrentDisplay(void)
1493{
1494    // could be called before eglInitialize(), but we wouldn't have a context
1495    // then, and this function would correctly return EGL_NO_DISPLAY.
1496
1497    clearError();
1498
1499    EGLContext ctx = getContext();
1500    if (ctx) {
1501        egl_context_t const * const c = get_context(ctx);
1502        if (!c) return setError(EGL_BAD_CONTEXT, EGL_NO_SURFACE);
1503        return c->dpy;
1504    }
1505    return EGL_NO_DISPLAY;
1506}
1507
1508EGLBoolean eglWaitGL(void)
1509{
1510    // could be called before eglInitialize(), but we wouldn't have a context
1511    // then, and this function would return GL_TRUE, which isn't wrong.
1512
1513    clearError();
1514
1515    EGLBoolean res = EGL_TRUE;
1516    EGLContext ctx = getContext();
1517    if (ctx) {
1518        egl_context_t const * const c = get_context(ctx);
1519        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1520        if (uint32_t(c->impl)>=2)
1521            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1522        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1523        if (!cnx->dso)
1524            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1525        res = cnx->egl.eglWaitGL();
1526    }
1527    return res;
1528}
1529
1530EGLBoolean eglWaitNative(EGLint engine)
1531{
1532    // could be called before eglInitialize(), but we wouldn't have a context
1533    // then, and this function would return GL_TRUE, which isn't wrong.
1534
1535    clearError();
1536
1537    EGLBoolean res = EGL_TRUE;
1538    EGLContext ctx = getContext();
1539    if (ctx) {
1540        egl_context_t const * const c = get_context(ctx);
1541        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1542        if (uint32_t(c->impl)>=2)
1543            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1544        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1545        if (!cnx->dso)
1546            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1547        res = cnx->egl.eglWaitNative(engine);
1548    }
1549    return res;
1550}
1551
1552EGLint eglGetError(void)
1553{
1554    EGLint result = EGL_SUCCESS;
1555    EGLint err;
1556    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1557        err = EGL_SUCCESS;
1558        egl_connection_t* const cnx = &gEGLImpl[i];
1559        if (cnx->dso)
1560            err = cnx->egl.eglGetError();
1561        if (err!=EGL_SUCCESS && result==EGL_SUCCESS)
1562            result = err;
1563    }
1564    err = getError();
1565    if (result == EGL_SUCCESS)
1566        result = err;
1567    return result;
1568}
1569
1570// Note: Similar implementations of these functions also exist in
1571// gl2.cpp and gl.cpp, and are used by applications that call the
1572// exported entry points directly.
1573typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
1574typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
1575
1576static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES_impl = NULL;
1577static PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC glEGLImageTargetRenderbufferStorageOES_impl = NULL;
1578
1579static void glEGLImageTargetTexture2DOES_wrapper(GLenum target, GLeglImageOES image)
1580{
1581    GLeglImageOES implImage =
1582        (GLeglImageOES)egl_get_image_for_current_context((EGLImageKHR)image);
1583    glEGLImageTargetTexture2DOES_impl(target, implImage);
1584}
1585
1586static void glEGLImageTargetRenderbufferStorageOES_wrapper(GLenum target, GLeglImageOES image)
1587{
1588    GLeglImageOES implImage =
1589        (GLeglImageOES)egl_get_image_for_current_context((EGLImageKHR)image);
1590    glEGLImageTargetRenderbufferStorageOES_impl(target, implImage);
1591}
1592
1593__eglMustCastToProperFunctionPointerType eglGetProcAddress(const char *procname)
1594{
1595    // eglGetProcAddress() could be the very first function called
1596    // in which case we must make sure we've initialized ourselves, this
1597    // happens the first time egl_get_display() is called.
1598
1599    clearError();
1600
1601    if (egl_init_drivers() == EGL_FALSE) {
1602        setError(EGL_BAD_PARAMETER, NULL);
1603        return  NULL;
1604    }
1605
1606    __eglMustCastToProperFunctionPointerType addr;
1607    addr = findProcAddress(procname, gExtentionMap, NELEM(gExtentionMap));
1608    if (addr) return addr;
1609
1610    // this protects accesses to gGLExtentionMap and gGLExtentionSlot
1611    pthread_mutex_lock(&gInitDriverMutex);
1612
1613        /*
1614         * Since eglGetProcAddress() is not associated to anything, it needs
1615         * to return a function pointer that "works" regardless of what
1616         * the current context is.
1617         *
1618         * For this reason, we return a "forwarder", a small stub that takes
1619         * care of calling the function associated with the context
1620         * currently bound.
1621         *
1622         * We first look for extensions we've already resolved, if we're seeing
1623         * this extension for the first time, we go through all our
1624         * implementations and call eglGetProcAddress() and record the
1625         * result in the appropriate implementation hooks and return the
1626         * address of the forwarder corresponding to that hook set.
1627         *
1628         */
1629
1630        const String8 name(procname);
1631        addr = gGLExtentionMap.valueFor(name);
1632        const int slot = gGLExtentionSlot;
1633
1634        LOGE_IF(slot >= MAX_NUMBER_OF_GL_EXTENSIONS,
1635                "no more slots for eglGetProcAddress(\"%s\")",
1636                procname);
1637
1638        if (!addr && (slot < MAX_NUMBER_OF_GL_EXTENSIONS)) {
1639            bool found = false;
1640            for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1641                egl_connection_t* const cnx = &gEGLImpl[i];
1642                if (cnx->dso && cnx->egl.eglGetProcAddress) {
1643                    found = true;
1644                    // Extensions are independent of the bound context
1645                    cnx->hooks[GLESv1_INDEX]->ext.extensions[slot] =
1646                    cnx->hooks[GLESv2_INDEX]->ext.extensions[slot] =
1647#if EGL_TRACE
1648                    gHooksDebug.ext.extensions[slot] = gHooksTrace.ext.extensions[slot] =
1649#endif
1650                            cnx->egl.eglGetProcAddress(procname);
1651                }
1652            }
1653            if (found) {
1654                addr = gExtensionForwarders[slot];
1655
1656                if (!strcmp(procname, "glEGLImageTargetTexture2DOES")) {
1657                    glEGLImageTargetTexture2DOES_impl = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)addr;
1658                    addr = (__eglMustCastToProperFunctionPointerType)glEGLImageTargetTexture2DOES_wrapper;
1659                }
1660                if (!strcmp(procname, "glEGLImageTargetRenderbufferStorageOES")) {
1661                    glEGLImageTargetRenderbufferStorageOES_impl = (PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC)addr;
1662                    addr = (__eglMustCastToProperFunctionPointerType)glEGLImageTargetRenderbufferStorageOES_wrapper;
1663                }
1664
1665                gGLExtentionMap.add(name, addr);
1666                gGLExtentionSlot++;
1667            }
1668        }
1669
1670    pthread_mutex_unlock(&gInitDriverMutex);
1671    return addr;
1672}
1673
1674EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw)
1675{
1676    EGLBoolean Debug_eglSwapBuffers(EGLDisplay dpy, EGLSurface draw);
1677    if (gEGLDebugLevel > 0)
1678        Debug_eglSwapBuffers(dpy, draw);
1679
1680    clearError();
1681
1682    SurfaceRef _s(draw);
1683    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1684
1685    if (!validate_display_surface(dpy, draw))
1686        return EGL_FALSE;
1687    egl_display_t const * const dp = get_display(dpy);
1688    egl_surface_t const * const s = get_surface(draw);
1689    return s->cnx->egl.eglSwapBuffers(dp->disp[s->impl].dpy, s->surface);
1690}
1691
1692EGLBoolean eglCopyBuffers(  EGLDisplay dpy, EGLSurface surface,
1693                            NativePixmapType target)
1694{
1695    clearError();
1696
1697    SurfaceRef _s(surface);
1698    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1699
1700    if (!validate_display_surface(dpy, surface))
1701        return EGL_FALSE;
1702    egl_display_t const * const dp = get_display(dpy);
1703    egl_surface_t const * const s = get_surface(surface);
1704    return s->cnx->egl.eglCopyBuffers(
1705            dp->disp[s->impl].dpy, s->surface, target);
1706}
1707
1708const char* eglQueryString(EGLDisplay dpy, EGLint name)
1709{
1710    clearError();
1711
1712    egl_display_t const * const dp = get_display(dpy);
1713    switch (name) {
1714        case EGL_VENDOR:
1715            return gVendorString;
1716        case EGL_VERSION:
1717            return gVersionString;
1718        case EGL_EXTENSIONS:
1719            return gExtensionString;
1720        case EGL_CLIENT_APIS:
1721            return gClientApiString;
1722    }
1723    return setError(EGL_BAD_PARAMETER, (const char *)0);
1724}
1725
1726
1727// ----------------------------------------------------------------------------
1728// EGL 1.1
1729// ----------------------------------------------------------------------------
1730
1731EGLBoolean eglSurfaceAttrib(
1732        EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
1733{
1734    clearError();
1735
1736    SurfaceRef _s(surface);
1737    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1738
1739    if (!validate_display_surface(dpy, surface))
1740        return EGL_FALSE;
1741    egl_display_t const * const dp = get_display(dpy);
1742    egl_surface_t const * const s = get_surface(surface);
1743    if (s->cnx->egl.eglSurfaceAttrib) {
1744        return s->cnx->egl.eglSurfaceAttrib(
1745                dp->disp[s->impl].dpy, s->surface, attribute, value);
1746    }
1747    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1748}
1749
1750EGLBoolean eglBindTexImage(
1751        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1752{
1753    clearError();
1754
1755    SurfaceRef _s(surface);
1756    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1757
1758    if (!validate_display_surface(dpy, surface))
1759        return EGL_FALSE;
1760    egl_display_t const * const dp = get_display(dpy);
1761    egl_surface_t const * const s = get_surface(surface);
1762    if (s->cnx->egl.eglBindTexImage) {
1763        return s->cnx->egl.eglBindTexImage(
1764                dp->disp[s->impl].dpy, s->surface, buffer);
1765    }
1766    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1767}
1768
1769EGLBoolean eglReleaseTexImage(
1770        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1771{
1772    clearError();
1773
1774    SurfaceRef _s(surface);
1775    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1776
1777    if (!validate_display_surface(dpy, surface))
1778        return EGL_FALSE;
1779    egl_display_t const * const dp = get_display(dpy);
1780    egl_surface_t const * const s = get_surface(surface);
1781    if (s->cnx->egl.eglReleaseTexImage) {
1782        return s->cnx->egl.eglReleaseTexImage(
1783                dp->disp[s->impl].dpy, s->surface, buffer);
1784    }
1785    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1786}
1787
1788EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval)
1789{
1790    clearError();
1791
1792    egl_display_t * const dp = get_display(dpy);
1793    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1794
1795    EGLBoolean res = EGL_TRUE;
1796    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1797        egl_connection_t* const cnx = &gEGLImpl[i];
1798        if (cnx->dso) {
1799            if (cnx->egl.eglSwapInterval) {
1800                if (cnx->egl.eglSwapInterval(
1801                        dp->disp[i].dpy, interval) == EGL_FALSE) {
1802                    res = EGL_FALSE;
1803                }
1804            }
1805        }
1806    }
1807    return res;
1808}
1809
1810
1811// ----------------------------------------------------------------------------
1812// EGL 1.2
1813// ----------------------------------------------------------------------------
1814
1815EGLBoolean eglWaitClient(void)
1816{
1817    clearError();
1818
1819    // could be called before eglInitialize(), but we wouldn't have a context
1820    // then, and this function would return GL_TRUE, which isn't wrong.
1821    EGLBoolean res = EGL_TRUE;
1822    EGLContext ctx = getContext();
1823    if (ctx) {
1824        egl_context_t const * const c = get_context(ctx);
1825        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1826        if (uint32_t(c->impl)>=2)
1827            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1828        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1829        if (!cnx->dso)
1830            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1831        if (cnx->egl.eglWaitClient) {
1832            res = cnx->egl.eglWaitClient();
1833        } else {
1834            res = cnx->egl.eglWaitGL();
1835        }
1836    }
1837    return res;
1838}
1839
1840EGLBoolean eglBindAPI(EGLenum api)
1841{
1842    clearError();
1843
1844    if (egl_init_drivers() == EGL_FALSE) {
1845        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1846    }
1847
1848    // bind this API on all EGLs
1849    EGLBoolean res = EGL_TRUE;
1850    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1851        egl_connection_t* const cnx = &gEGLImpl[i];
1852        if (cnx->dso) {
1853            if (cnx->egl.eglBindAPI) {
1854                if (cnx->egl.eglBindAPI(api) == EGL_FALSE) {
1855                    res = EGL_FALSE;
1856                }
1857            }
1858        }
1859    }
1860    return res;
1861}
1862
1863EGLenum eglQueryAPI(void)
1864{
1865    clearError();
1866
1867    if (egl_init_drivers() == EGL_FALSE) {
1868        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1869    }
1870
1871    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1872        egl_connection_t* const cnx = &gEGLImpl[i];
1873        if (cnx->dso) {
1874            if (cnx->egl.eglQueryAPI) {
1875                // the first one we find is okay, because they all
1876                // should be the same
1877                return cnx->egl.eglQueryAPI();
1878            }
1879        }
1880    }
1881    // or, it can only be OpenGL ES
1882    return EGL_OPENGL_ES_API;
1883}
1884
1885EGLBoolean eglReleaseThread(void)
1886{
1887    clearError();
1888
1889    // If there is context bound to the thread, release it
1890    loseCurrent(get_context(getContext()));
1891
1892    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1893        egl_connection_t* const cnx = &gEGLImpl[i];
1894        if (cnx->dso) {
1895            if (cnx->egl.eglReleaseThread) {
1896                cnx->egl.eglReleaseThread();
1897            }
1898        }
1899    }
1900    clearTLS();
1901    return EGL_TRUE;
1902}
1903
1904EGLSurface eglCreatePbufferFromClientBuffer(
1905          EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
1906          EGLConfig config, const EGLint *attrib_list)
1907{
1908    clearError();
1909
1910    egl_display_t const* dp = 0;
1911    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1912    if (!cnx) return EGL_FALSE;
1913    if (cnx->egl.eglCreatePbufferFromClientBuffer) {
1914        return cnx->egl.eglCreatePbufferFromClientBuffer(
1915                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1916                buftype, buffer,
1917                dp->configs[intptr_t(config)].config, attrib_list);
1918    }
1919    return setError(EGL_BAD_CONFIG, EGL_NO_SURFACE);
1920}
1921
1922// ----------------------------------------------------------------------------
1923// EGL_EGLEXT_VERSION 3
1924// ----------------------------------------------------------------------------
1925
1926EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
1927        const EGLint *attrib_list)
1928{
1929    clearError();
1930
1931    SurfaceRef _s(surface);
1932    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1933
1934    if (!validate_display_surface(dpy, surface))
1935        return EGL_FALSE;
1936
1937    egl_display_t const * const dp = get_display(dpy);
1938    egl_surface_t const * const s = get_surface(surface);
1939
1940    if (s->cnx->egl.eglLockSurfaceKHR) {
1941        return s->cnx->egl.eglLockSurfaceKHR(
1942                dp->disp[s->impl].dpy, s->surface, attrib_list);
1943    }
1944    return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1945}
1946
1947EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
1948{
1949    clearError();
1950
1951    SurfaceRef _s(surface);
1952    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1953
1954    if (!validate_display_surface(dpy, surface))
1955        return EGL_FALSE;
1956
1957    egl_display_t const * const dp = get_display(dpy);
1958    egl_surface_t const * const s = get_surface(surface);
1959
1960    if (s->cnx->egl.eglUnlockSurfaceKHR) {
1961        return s->cnx->egl.eglUnlockSurfaceKHR(
1962                dp->disp[s->impl].dpy, s->surface);
1963    }
1964    return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1965}
1966
1967EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
1968        EGLClientBuffer buffer, const EGLint *attrib_list)
1969{
1970    clearError();
1971
1972    if (ctx != EGL_NO_CONTEXT) {
1973        ContextRef _c(ctx);
1974        if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
1975        if (!validate_display_context(dpy, ctx))
1976            return EGL_NO_IMAGE_KHR;
1977        egl_display_t const * const dp = get_display(dpy);
1978        egl_context_t * const c = get_context(ctx);
1979        // since we have an EGLContext, we know which implementation to use
1980        EGLImageKHR image = c->cnx->egl.eglCreateImageKHR(
1981                dp->disp[c->impl].dpy, c->context, target, buffer, attrib_list);
1982        if (image == EGL_NO_IMAGE_KHR)
1983            return image;
1984
1985        egl_image_t* result = new egl_image_t(dpy, ctx);
1986        result->images[c->impl] = image;
1987        return (EGLImageKHR)result;
1988    } else {
1989        // EGL_NO_CONTEXT is a valid parameter
1990        egl_display_t const * const dp = get_display(dpy);
1991        if (dp == 0) {
1992            return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
1993        }
1994
1995        /* Since we don't have a way to know which implementation to call,
1996         * we're calling all of them. If at least one of the implementation
1997         * succeeded, this is a success.
1998         */
1999
2000        EGLint currentError = eglGetError();
2001
2002        EGLImageKHR implImages[IMPL_NUM_IMPLEMENTATIONS];
2003        bool success = false;
2004        for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
2005            egl_connection_t* const cnx = &gEGLImpl[i];
2006            implImages[i] = EGL_NO_IMAGE_KHR;
2007            if (cnx->dso) {
2008                if (cnx->egl.eglCreateImageKHR) {
2009                    implImages[i] = cnx->egl.eglCreateImageKHR(
2010                            dp->disp[i].dpy, ctx, target, buffer, attrib_list);
2011                    if (implImages[i] != EGL_NO_IMAGE_KHR) {
2012                        success = true;
2013                    }
2014                }
2015            }
2016        }
2017
2018        if (!success) {
2019            // failure, if there was an error when we entered this function,
2020            // the error flag must not be updated.
2021            // Otherwise, the error is whatever happened in the implementation
2022            // that faulted.
2023            if (currentError != EGL_SUCCESS) {
2024                setError(currentError, EGL_NO_IMAGE_KHR);
2025            }
2026            return EGL_NO_IMAGE_KHR;
2027        } else {
2028            // In case of success, we need to clear all error flags
2029            // (especially those caused by the implementation that didn't
2030            // succeed). TODO: we could avoid this if we knew this was
2031            // a "full" success (all implementation succeeded).
2032            eglGetError();
2033        }
2034
2035        egl_image_t* result = new egl_image_t(dpy, ctx);
2036        memcpy(result->images, implImages, sizeof(implImages));
2037        return (EGLImageKHR)result;
2038    }
2039}
2040
2041EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
2042{
2043    clearError();
2044
2045    egl_display_t const * const dp = get_display(dpy);
2046     if (dp == 0) {
2047         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2048     }
2049
2050     ImageRef _i(img);
2051     if (!_i.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2052
2053     egl_image_t* image = get_image(img);
2054     bool success = false;
2055     for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
2056         egl_connection_t* const cnx = &gEGLImpl[i];
2057         if (image->images[i] != EGL_NO_IMAGE_KHR) {
2058             if (cnx->dso) {
2059                 if (cnx->egl.eglDestroyImageKHR) {
2060                     if (cnx->egl.eglDestroyImageKHR(
2061                             dp->disp[i].dpy, image->images[i])) {
2062                         success = true;
2063                     }
2064                 }
2065             }
2066         }
2067     }
2068     if (!success)
2069         return EGL_FALSE;
2070
2071     _i.terminate();
2072
2073     return EGL_TRUE;
2074}
2075
2076// ----------------------------------------------------------------------------
2077// EGL_EGLEXT_VERSION 5
2078// ----------------------------------------------------------------------------
2079
2080
2081EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list)
2082{
2083    clearError();
2084
2085    EGLContext ctx = eglGetCurrentContext();
2086    ContextRef _c(ctx);
2087    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_NO_SYNC_KHR);
2088    if (!validate_display_context(dpy, ctx))
2089        return EGL_NO_SYNC_KHR;
2090    egl_display_t const * const dp = get_display(dpy);
2091    egl_context_t * const c = get_context(ctx);
2092    EGLSyncKHR result = EGL_NO_SYNC_KHR;
2093    if (c->cnx->egl.eglCreateSyncKHR) {
2094        EGLSyncKHR sync = c->cnx->egl.eglCreateSyncKHR(
2095                dp->disp[c->impl].dpy, type, attrib_list);
2096        if (sync == EGL_NO_SYNC_KHR)
2097            return sync;
2098        result = (egl_sync_t*)new egl_sync_t(dpy, ctx, sync);
2099    }
2100    return (EGLSyncKHR)result;
2101}
2102
2103EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync)
2104{
2105    clearError();
2106
2107    egl_display_t const * const dp = get_display(dpy);
2108    if (dp == 0) {
2109        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2110    }
2111
2112    SyncRef _s(sync);
2113    if (!_s.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2114    egl_sync_t* syncObject = get_sync(sync);
2115
2116    EGLContext ctx = syncObject->context;
2117    ContextRef _c(ctx);
2118    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
2119    if (!validate_display_context(dpy, ctx))
2120        return EGL_FALSE;
2121
2122    EGLBoolean result = EGL_FALSE;
2123    egl_context_t * const c = get_context(ctx);
2124    if (c->cnx->egl.eglDestroySyncKHR) {
2125        result = c->cnx->egl.eglDestroySyncKHR(
2126                dp->disp[c->impl].dpy, syncObject->sync);
2127        if (result)
2128            _s.terminate();
2129    }
2130    return result;
2131}
2132
2133EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout)
2134{
2135    clearError();
2136
2137    egl_display_t const * const dp = get_display(dpy);
2138    if (dp == 0) {
2139        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2140    }
2141
2142    SyncRef _s(sync);
2143    if (!_s.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2144    egl_sync_t* syncObject = get_sync(sync);
2145
2146    EGLContext ctx = syncObject->context;
2147    ContextRef _c(ctx);
2148    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
2149    if (!validate_display_context(dpy, ctx))
2150        return EGL_FALSE;
2151
2152    egl_context_t * const c = get_context(ctx);
2153
2154    if (c->cnx->egl.eglClientWaitSyncKHR) {
2155        return c->cnx->egl.eglClientWaitSyncKHR(
2156                dp->disp[c->impl].dpy, syncObject->sync, flags, timeout);
2157    }
2158
2159    return EGL_FALSE;
2160}
2161
2162EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value)
2163{
2164    clearError();
2165
2166    egl_display_t const * const dp = get_display(dpy);
2167    if (dp == 0) {
2168        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2169    }
2170
2171    SyncRef _s(sync);
2172    if (!_s.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2173    egl_sync_t* syncObject = get_sync(sync);
2174
2175    EGLContext ctx = syncObject->context;
2176    ContextRef _c(ctx);
2177    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
2178    if (!validate_display_context(dpy, ctx))
2179        return EGL_FALSE;
2180
2181    egl_context_t * const c = get_context(ctx);
2182
2183    if (c->cnx->egl.eglGetSyncAttribKHR) {
2184        return c->cnx->egl.eglGetSyncAttribKHR(
2185                dp->disp[c->impl].dpy, syncObject->sync, attribute, value);
2186    }
2187
2188    return EGL_FALSE;
2189}
2190
2191// ----------------------------------------------------------------------------
2192// ANDROID extensions
2193// ----------------------------------------------------------------------------
2194
2195EGLBoolean eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
2196        EGLint left, EGLint top, EGLint width, EGLint height)
2197{
2198    clearError();
2199
2200    SurfaceRef _s(draw);
2201    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
2202
2203    if (!validate_display_surface(dpy, draw))
2204        return EGL_FALSE;
2205    egl_display_t const * const dp = get_display(dpy);
2206    egl_surface_t const * const s = get_surface(draw);
2207    if (s->cnx->egl.eglSetSwapRectangleANDROID) {
2208        return s->cnx->egl.eglSetSwapRectangleANDROID(
2209                dp->disp[s->impl].dpy, s->surface, left, top, width, height);
2210    }
2211    return setError(EGL_BAD_DISPLAY, NULL);
2212}
2213