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