egl: improve attribute checking for eglCreateContext
[mesa.git] / src / egl / main / egldriver.c
index 2359253ff137a0350fead125cba3a76370fa25af..b9b21dec5ea5903ff2606fec48b6ba84caaa3b0a 100644 (file)
@@ -1,3 +1,33 @@
+/**************************************************************************
+ *
+ * Copyright 2008 VMware, Inc.
+ * Copyright 2009-2010 Chia-I Wu <olvaffe@gmail.com>
+ * Copyright 2010-2011 LunarG, Inc.
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sub license, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ **************************************************************************/
+
+
 /**
  * Functions for choosing and opening/loading device drivers.
  */
 #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include "c11/threads.h"
 
-#include "eglstring.h"
 #include "egldefines.h"
 #include "egldisplay.h"
 #include "egldriver.h"
 #include "egllog.h"
-#include "eglmutex.h"
-
-#if defined(_EGL_OS_UNIX)
-#include <dlfcn.h>
-#include <sys/types.h>
-#include <dirent.h>
-#include <unistd.h>
-#endif
-
 
 typedef struct _egl_module {
-   char *Path;
-   void *Handle;
+   char *Name;
+   _EGLMain_t BuiltIn;
    _EGLDriver *Driver;
 } _EGLModule;
 
-static _EGL_DECLARE_MUTEX(_eglModuleMutex);
+static mtx_t _eglModuleMutex = _MTX_INITIALIZER_NP;
 static _EGLArray *_eglModules;
 
-
-/**
- * Wrappers for dlopen/dlclose()
- */
-#if defined(_EGL_OS_WINDOWS)
-
-
-typedef HMODULE lib_handle;
-
-static HMODULE
-open_library(const char *filename)
-{
-   return LoadLibrary(filename);
-}
-
-static void
-close_library(HMODULE lib)
-{
-   FreeLibrary(lib);
-}
-
-
-static const char *
-library_suffix(void)
-{
-   return ".dll";
-}
-
-
-#elif defined(_EGL_OS_UNIX)
-
-
-typedef void * lib_handle;
-
-static void *
-open_library(const char *filename)
-{
-   return dlopen(filename, RTLD_LAZY);
-}
-
-static void
-close_library(void *lib)
-{
-   dlclose(lib);
-}
-
-
-static const char *
-library_suffix(void)
-{
-   return ".so";
-}
-
-
+const struct {
+   const char *name;
+   _EGLMain_t main;
+} _eglBuiltInDrivers[] = {
+#ifdef _EGL_BUILT_IN_DRIVER_DRI2
+   { "egl_dri2", _eglBuiltInDriverDRI2 },
 #endif
-
-
-/**
- * Open the named driver and find its bootstrap function: _eglMain().
- */
-static _EGLMain_t
-_eglOpenLibrary(const char *driverPath, lib_handle *handle)
-{
-   lib_handle lib;
-   _EGLMain_t mainFunc = NULL;
-   const char *error = "unknown error";
-
-   assert(driverPath);
-
-   _eglLog(_EGL_DEBUG, "dlopen(%s)", driverPath);
-   lib = open_library(driverPath);
-
-#if defined(_EGL_OS_WINDOWS)
-   /* XXX untested */
-   if (lib)
-      mainFunc = (_EGLMain_t) GetProcAddress(lib, "_eglMain");
-#elif defined(_EGL_OS_UNIX)
-   if (lib) {
-      union {
-         _EGLMain_t func;
-         void *ptr;
-      } tmp = { NULL };
-      /* direct cast gives a warning when compiled with -pedantic */
-      tmp.ptr = dlsym(lib, "_eglMain");
-      mainFunc = tmp.func;
-      if (!mainFunc)
-         error = dlerror();
-   }
-   else {
-      error = dlerror();
-   }
+#ifdef _EGL_BUILT_IN_DRIVER_HAIKU
+   { "egl_haiku", _eglBuiltInDriverHaiku },
 #endif
-
-   if (!lib) {
-      _eglLog(_EGL_WARNING, "Could not open driver %s (%s)",
-              driverPath, error);
-      if (!getenv("EGL_DRIVER"))
-         _eglLog(_EGL_WARNING,
-                 "The driver can be overridden by setting EGL_DRIVER");
-      return NULL;
-   }
-
-   if (!mainFunc) {
-      _eglLog(_EGL_WARNING, "_eglMain not found in %s (%s)",
-              driverPath, error);
-      if (lib)
-         close_library(lib);
-      return NULL;
-   }
-
-   *handle = lib;
-   return mainFunc;
-}
-
+   { NULL, NULL }
+};
 
 /**
  * Load a module and create the driver object.
@@ -153,27 +72,18 @@ _eglOpenLibrary(const char *driverPath, lib_handle *handle)
 static EGLBoolean
 _eglLoadModule(_EGLModule *mod)
 {
-   _EGLMain_t mainFunc;
-   lib_handle lib;
    _EGLDriver *drv;
 
-   mainFunc = _eglOpenLibrary(mod->Path, &lib);
-   if (!mainFunc)
-      return EGL_FALSE;
+   if (mod->Driver)
+      return EGL_TRUE;
 
-   drv = mainFunc(NULL);
-   if (!drv) {
-      if (lib)
-         close_library(lib);
-      return EGL_FALSE;
-   }
+   if (!mod->BuiltIn)
+         return EGL_FALSE;
 
-   if (!drv->Name) {
-      _eglLog(_EGL_WARNING, "Driver loaded from %s has no name", mod->Path);
-      drv->Name = "UNNAMED";
-   }
+   drv = mod->BuiltIn(NULL);
+   if (!drv || !drv->Name)
+      return EGL_FALSE;
 
-   mod->Handle = (void *) lib;
    mod->Driver = drv;
 
    return EGL_TRUE;
@@ -189,11 +99,8 @@ _eglUnloadModule(_EGLModule *mod)
    /* destroy the driver */
    if (mod->Driver && mod->Driver->Unload)
       mod->Driver->Unload(mod->Driver);
-   if (mod->Handle)
-      close_library(mod->Handle);
 
    mod->Driver = NULL;
-   mod->Handle = NULL;
 }
 
 
@@ -201,7 +108,7 @@ _eglUnloadModule(_EGLModule *mod)
  * Add a module to the module array.
  */
 static _EGLModule *
-_eglAddModule(const char *path)
+_eglAddModule(const char *name)
 {
    _EGLModule *mod;
    EGLint i;
@@ -215,22 +122,22 @@ _eglAddModule(const char *path)
    /* find duplicates */
    for (i = 0; i < _eglModules->Size; i++) {
       mod = _eglModules->Elements[i];
-      if (strcmp(mod->Path, path) == 0)
+      if (strcmp(mod->Name, name) == 0)
          return mod;
    }
 
    /* allocate a new one */
    mod = calloc(1, sizeof(*mod));
    if (mod) {
-      mod->Path = _eglstrdup(path);
-      if (!mod->Path) {
+      mod->Name = strdup(name);
+      if (!mod->Name) {
          free(mod);
          mod = NULL;
       }
    }
    if (mod) {
       _eglAppendArray(_eglModules, (void *) mod);
-      _eglLog(_EGL_DEBUG, "added %s to module array", mod->Path);
+      _eglLog(_EGL_DEBUG, "added %s to module array", mod->Name);
    }
 
    return mod;
@@ -246,239 +153,53 @@ _eglFreeModule(void *module)
    _EGLModule *mod = (_EGLModule *) module;
 
    _eglUnloadModule(mod);
-   free(mod->Path);
+   free(mod->Name);
    free(mod);
 }
 
 
-/**
- * A loader function for use with _eglPreloadForEach.  The loader data is the
- * filename of the driver.   This function stops on the first valid driver.
- */
-static EGLBoolean
-_eglLoaderFile(const char *dir, size_t len, void *loader_data)
-{
-   char path[1024];
-   const char *filename = (const char *) loader_data;
-   size_t flen = strlen(filename);
-
-   /* make a full path */
-   if (len + flen + 2 > sizeof(path))
-      return EGL_TRUE;
-   if (len) {
-      memcpy(path, dir, len);
-      path[len++] = '/';
-   }
-   memcpy(path + len, filename, flen);
-   len += flen;
-   path[len] = '\0';
-
-   if (library_suffix()) {
-      const char *suffix = library_suffix();
-      size_t slen = strlen(suffix);
-      const char *p;
-      EGLBoolean need_suffix;
-
-      p = filename + flen - slen;
-      need_suffix = (p < filename || strcmp(p, suffix) != 0);
-      if (need_suffix) {
-         /* overflow */
-         if (len + slen + 1 > sizeof(path))
-            return EGL_TRUE;
-         strcpy(path + len, suffix);
-      }
-   }
-
-#if defined(_EGL_OS_UNIX)
-   /* check if the file exists */
-   if (access(path, F_OK))
-      return EGL_TRUE;
-#endif
-
-   _eglAddModule(path);
-
-   return EGL_TRUE;
-}
-
-
-/**
- * A loader function for use with _eglPreloadForEach.  The loader data is the
- * pattern (prefix) of the files to look for.
- */
-static EGLBoolean
-_eglLoaderPattern(const char *dir, size_t len, void *loader_data)
-{
-#if defined(_EGL_OS_UNIX)
-   const char *prefix, *suffix;
-   size_t prefix_len, suffix_len;
-   DIR *dirp;
-   struct dirent *dirent;
-   char path[1024];
-
-   if (len + 2 > sizeof(path))
-      return EGL_TRUE;
-   if (len) {
-      memcpy(path, dir, len);
-      path[len++] = '/';
-   }
-   path[len] = '\0';
-
-   dirp = opendir(path);
-   if (!dirp)
-      return EGL_TRUE;
-
-   prefix = (const char *) loader_data;
-   prefix_len = strlen(prefix);
-   suffix = library_suffix();
-   suffix_len = (suffix) ? strlen(suffix) : 0;
-
-   while ((dirent = readdir(dirp))) {
-      size_t dirent_len = strlen(dirent->d_name);
-      const char *p;
-
-      /* match the prefix */
-      if (strncmp(dirent->d_name, prefix, prefix_len) != 0)
-         continue;
-      /* match the suffix */
-      if (suffix) {
-         p = dirent->d_name + dirent_len - suffix_len;
-         if (p < dirent->d_name || strcmp(p, suffix) != 0)
-            continue;
-      }
-
-      /* make a full path and add it to the module array */
-      if (len + dirent_len + 1 <= sizeof(path)) {
-         strcpy(path + len, dirent->d_name);
-         _eglAddModule(path);
-      }
-   }
-
-   closedir(dirp);
-
-   return EGL_TRUE;
-#else /* _EGL_OS_UNIX */
-   /* stop immediately */
-   return EGL_FALSE;
-#endif
-}
-
-
-/**
- * Run the callback function on each driver directory.
- *
- * The process may end prematurely if the callback function returns false.
- */
-static void
-_eglPreloadForEach(const char *search_path,
-                   EGLBoolean (*loader)(const char *, size_t, void *),
-                   void *loader_data)
-{
-   const char *cur, *next;
-   size_t len;
-
-   cur = search_path;
-   while (cur) {
-      next = strchr(cur, ':');
-      len = (next) ? next - cur : strlen(cur);
-
-      if (!loader(cur, len, loader_data))
-         break;
-
-      cur = (next) ? next + 1 : NULL;
-   }
-}
-
-
-/**
- * Return a list of colon-separated driver directories.
- */
-static const char *
-_eglGetSearchPath(void)
-{
-   static const char *search_path;
-
-#if defined(_EGL_OS_UNIX) || defined(_EGL_OS_WINDOWS)
-   if (!search_path) {
-      static char buffer[1024];
-      const char *p;
-      int ret;
-
-      p = getenv("EGL_DRIVERS_PATH");
-#if defined(_EGL_OS_UNIX)
-      if (p && (geteuid() != getuid() || getegid() != getgid())) {
-         _eglLog(_EGL_DEBUG,
-               "ignore EGL_DRIVERS_PATH for setuid/setgid binaries");
-         p = NULL;
-      }
-#endif /* _EGL_OS_UNIX */
-
-      if (p) {
-         ret = _eglsnprintf(buffer, sizeof(buffer),
-               "%s:%s", p, _EGL_DRIVER_SEARCH_DIR);
-         if (ret > 0 && ret < sizeof(buffer))
-            search_path = buffer;
-      }
-   }
-   if (!search_path)
-      search_path = _EGL_DRIVER_SEARCH_DIR;
-#else
-   search_path = "";
-#endif
-
-   return search_path;
-}
-
-
 /**
  * Add the user driver to the module array.
  *
  * The user driver is specified by EGL_DRIVER.
  */
-static void
+static EGLBoolean
 _eglAddUserDriver(void)
 {
-   const char *search_path = _eglGetSearchPath();
    char *env;
 
    env = getenv("EGL_DRIVER");
-#if defined(_EGL_OS_UNIX)
-   if (env && strchr(env, '/')) {
-      search_path = "";
-      if ((geteuid() != getuid() || getegid() != getgid())) {
-         _eglLog(_EGL_DEBUG,
-               "ignore EGL_DRIVER for setuid/setgid binaries");
-         env = NULL;
+   if (env) {
+      EGLint i;
+
+      for (i = 0; _eglBuiltInDrivers[i].name; i++) {
+         if (!strcmp(_eglBuiltInDrivers[i].name, env)) {
+            _EGLModule *mod = _eglAddModule(env);
+            if (mod)
+               mod->BuiltIn = _eglBuiltInDrivers[i].main;
+
+            return EGL_TRUE;
+         }
       }
    }
-#endif /* _EGL_OS_UNIX */
-   if (env)
-      _eglPreloadForEach(search_path, _eglLoaderFile, (void *) env);
+
+   return EGL_FALSE;
 }
 
 
 /**
- * Add default drivers to the module array.
+ * Add built-in drivers to the module array.
  */
 static void
-_eglAddDefaultDrivers(void)
+_eglAddBuiltInDrivers(void)
 {
-   const char *search_path = _eglGetSearchPath();
+   _EGLModule *mod;
    EGLint i;
-#if defined(_EGL_OS_WINDOWS)
-   const char *DefaultDriverNames[] = {
-      "egl_gallium"
-   };
-#elif defined(_EGL_OS_UNIX)
-   const char *DefaultDriverNames[] = {
-      "egl_gallium",
-      "egl_dri2",
-      "egl_glx"
-   };
-#endif
 
-   for (i = 0; i < ARRAY_SIZE(DefaultDriverNames); i++) {
-      void *name = (void *) DefaultDriverNames[i];
-      _eglPreloadForEach(search_path, _eglLoaderFile, name);
+   for (i = 0; _eglBuiltInDrivers[i].name; i++) {
+      mod = _eglAddModule(_eglBuiltInDrivers[i].name);
+      if (mod)
+         mod->BuiltIn = _eglBuiltInDrivers[i].main;
    }
 }
 
@@ -493,113 +214,95 @@ _eglAddDrivers(void)
    if (_eglModules)
       return EGL_TRUE;
 
-   /* the order here decides the priorities of the drivers */
-   _eglAddUserDriver();
-   _eglAddDefaultDrivers();
-   _eglPreloadForEach(_eglGetSearchPath(), _eglLoaderPattern, (void *) "egl_");
+   if (!_eglAddUserDriver()) {
+      /*
+       * Add other drivers only when EGL_DRIVER is not set.  The order here
+       * decides the priorities.
+       */
+      _eglAddBuiltInDrivers();
+   }
 
    return (_eglModules != NULL);
 }
 
 
 /**
- * Match a display to a driver.  The display is initialized unless use_probe is
- * true.
- *
- * The matching is done by finding the first driver that can initialize the
- * display, or when use_probe is true, the driver with highest score.
+ * A helper function for _eglMatchDriver.  It finds the first driver that can
+ * initialize the display and return.
  */
-_EGLDriver *
-_eglMatchDriver(_EGLDisplay *dpy, EGLBoolean use_probe)
+static _EGLDriver *
+_eglMatchAndInitialize(_EGLDisplay *dpy)
 {
-   _EGLModule *mod;
-   _EGLDriver *best_drv = NULL;
-   EGLint best_score = 0;
-   EGLint major, minor, i;
-
-   _eglLockMutex(&_eglModuleMutex);
+   _EGLDriver *drv = NULL;
+   EGLint i = 0;
 
    if (!_eglAddDrivers()) {
-      _eglUnlockMutex(&_eglModuleMutex);
-      return EGL_FALSE;
+      _eglLog(_EGL_WARNING, "failed to find any driver");
+      return NULL;
    }
 
-   /* match the loaded modules */
-   for (i = 0; i < _eglModules->Size; i++) {
-      mod = (_EGLModule *) _eglModules->Elements[i];
-      if (!mod->Driver)
-         break;
+   if (dpy->Driver) {
+      drv = dpy->Driver;
+      /* no re-matching? */
+      if (!drv->API.Initialize(drv, dpy))
+         drv = NULL;
+      return drv;
+   }
 
-      if (use_probe) {
-         EGLint score = (mod->Driver->Probe) ?
-            mod->Driver->Probe(mod->Driver, dpy) : 1;
-         if (score > best_score) {
-            best_drv = mod->Driver;
-            best_score = score;
-         }
+   while (i < _eglModules->Size) {
+      _EGLModule *mod = (_EGLModule *) _eglModules->Elements[i];
+
+      if (!_eglLoadModule(mod)) {
+         /* remove invalid modules */
+         _eglEraseArray(_eglModules, i, _eglFreeModule);
+         continue;
+      }
+
+      if (mod->Driver->API.Initialize(mod->Driver, dpy)) {
+         drv = mod->Driver;
+         break;
       }
       else {
-         if (mod->Driver->API.Initialize(mod->Driver, dpy, &major, &minor)) {
-            best_drv = mod->Driver;
-            best_score = 100;
-         }
+         i++;
       }
-      /* perfect match */
-      if (best_score >= 100)
-         break;
    }
 
-   /* load more modules */
-   if (!best_drv) {
-      EGLint first_unloaded = i;
+   return drv;
+}
 
-      while (i < _eglModules->Size) {
-         mod = (_EGLModule *) _eglModules->Elements[i];
-         assert(!mod->Driver);
 
-         if (!_eglLoadModule(mod)) {
-            /* remove invalid modules */
-            _eglEraseArray(_eglModules, i, _eglFreeModule);
-            continue;
-         }
+/**
+ * Match a display to a driver.  The display is initialized unless test_only is
+ * true.  The matching is done by finding the first driver that can initialize
+ * the display.
+ */
+_EGLDriver *
+_eglMatchDriver(_EGLDisplay *dpy, EGLBoolean test_only)
+{
+   _EGLDriver *best_drv;
 
-         if (use_probe) {
-            best_score = (mod->Driver->Probe) ?
-               mod->Driver->Probe(mod->Driver, dpy) : 1;
-         }
-         else {
-            if (mod->Driver->API.Initialize(mod->Driver, dpy, &major, &minor))
-               best_score = 100;
-         }
+   assert(!dpy->Initialized);
 
-         if (best_score > 0) {
-            best_drv = mod->Driver;
-            /* loaded modules come before unloaded ones */
-            if (first_unloaded != i) {
-               void *tmp = _eglModules->Elements[i];
-               _eglModules->Elements[i] =
-                  _eglModules->Elements[first_unloaded];
-               _eglModules->Elements[first_unloaded] = tmp;
-            }
-            break;
-         }
-         else {
-            _eglUnloadModule(mod);
-            i++;
-         }
-      }
+   mtx_lock(&_eglModuleMutex);
+
+   /* set options */
+   dpy->Options.TestOnly = test_only;
+   dpy->Options.UseFallback = EGL_FALSE;
+
+   best_drv = _eglMatchAndInitialize(dpy);
+   if (!best_drv) {
+      dpy->Options.UseFallback = EGL_TRUE;
+      best_drv = _eglMatchAndInitialize(dpy);
    }
 
-   _eglUnlockMutex(&_eglModuleMutex);
+   mtx_unlock(&_eglModuleMutex);
 
    if (best_drv) {
-      _eglLog(_EGL_DEBUG, "the best driver is %s (score %d)",
-            best_drv->Name, best_score);
-      if (!use_probe) {
+      _eglLog(_EGL_DEBUG, "the best driver is %s%s",
+            best_drv->Name, (test_only) ? " (test only) " : "");
+      if (!test_only) {
          dpy->Driver = best_drv;
          dpy->Initialized = EGL_TRUE;
-         dpy->APImajor = major;
-         dpy->APIminor = minor;
       }
    }
 
@@ -643,27 +346,7 @@ _eglUnloadDrivers(void)
 {
    /* this is called at atexit time */
    if (_eglModules) {
-#if defined(_EGL_OS_UNIX)
       _eglDestroyArray(_eglModules, _eglFreeModule);
-#elif defined(_EGL_OS_WINDOWS)
-      /* XXX Windows unloads DLLs before atexit */
-      _eglDestroyArray(_eglModules, NULL);
-#endif
       _eglModules = NULL;
    }
 }
-
-
-/**
- * Invoke a callback function on each EGL search path.
- *
- * The first argument of the callback function is the name of the search path.
- * The second argument is the length of the name.
- */
-void
-_eglSearchPathForEach(EGLBoolean (*callback)(const char *, size_t, void *),
-                      void *callback_data)
-{
-   const char *search_path = _eglGetSearchPath();
-   _eglPreloadForEach(search_path, callback, callback_data);
-}