diff --git a/README.md b/README.md index 20309c9304bbe26e09e4fd15a5c3f852f0633293..dc0f45cbdf84ef8c4baa484ecfc199200a36995e 100644 --- a/README.md +++ b/README.md @@ -509,6 +509,8 @@ The implementation of this macro carries the following license: modified version of the Autoconf Macro, you may extend this special exception to the GPL to apply to your modified version as well. +### cJSON ### + libglvnd uses the cJSON library for reading JSON files: https://github.com/DaveGamble/cJSON @@ -535,3 +537,32 @@ This library carries the following copyright notice: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +### tomlc99 ### + +libglvnd uses the tomlc99 library for reading TOML files: + +https://github.com/cktan/tomlc99 + +This library carries the following copyright notice: + + Copyright (c) 2017 CK Tan + https://github.com/cktan/tomlc99 + + 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, sublicense, 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 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. + diff --git a/configure.ac b/configure.ac index d2b00df98f3fd21c54546976b64db40234b357e3..df5951455afa441da7851ec8bb469db10c04bdc6 100644 --- a/configure.ac +++ b/configure.ac @@ -116,6 +116,26 @@ AS_IF([test "x$enable_entrypoint_patching" = "xyes"], [AC_DEFINE([GLDISPATCH_ENABLE_PATCHING], 1, [Define to 1 to enable entrypoint patching in libGLdispatch.])]) +AC_ARG_ENABLE([app-profile], + [AS_HELP_STRING([--app-profile], + [Do not build or use the app profile library @<:@default=enabled@:>@])], + [enable_app_profile="$enableval"], + [enable_app_profile=yes] +) +AM_CONDITIONAL([ENABLE_APP_PROFILE], [test "x$enable_app_profile" = "xyes"]) + +AC_ARG_ENABLE([vulkan], + [AS_HELP_STRING([--disable-vulkan], + [Disable Vulkan app profile layer @<:@default=enabled@:>@])], + [enable_vulkan="$enableval"], + [enable_vulkan="$enable_app_profile"] +) +AM_CONDITIONAL([ENABLE_VULKAN], [test "x$enable_vulkan" = "xyes"]) + +if test "x$enable_app_profile" != "xyes" -a "x$enable_vulkan" = "xyes" ; then + AC_MSG_ERROR([Can't build the Vulkan layer without the app profile library.]) +fi + dnl dnl Arch/platform-specific settings. Copied from mesa dnl @@ -211,6 +231,10 @@ if test "x$enable_glx" = "xyes" ; then PKG_CHECK_MODULES([GLPROTO], [glproto]) fi +if test "x$enable_vulkan" = "xyes" ; then + PKG_CHECK_MODULES([VULKAN], [vulkan]) +fi + dnl Checks for typedefs, structures, and compiler characteristics. AC_C_TYPEOF @@ -384,6 +408,21 @@ AS_IF([test "x$HAVE_RTLD_NOLOAD" = "xyes"], [AC_DEFINE([HAVE_RTLD_NOLOAD], 1, [Define to 1 if the compiler supports RTLD_NOLOAD.])]) +AC_MSG_CHECKING([for FNM_CASEFOLD]) +AC_COMPILE_IFELSE([AC_LANG_SOURCE([ +#define _GNU_SOURCE +#include +void foo(void) +{ + (void) FNM_CASEFOLD; +} +])], +[HAVE_FNM_CASEFOLD=yes],[HAVE_FNM_CASEFOLD=no]) +AC_MSG_RESULT($HAVE_FNM_CASEFOLD) +AS_IF([test "x$HAVE_FNM_CASEFOLD" = "xyes"], + [AC_DEFINE([HAVE_FNM_CASEFOLD], 1, + [Define to 1 if the compiler supports FNM_CASEFOLD.])]) + AC_MSG_CHECKING([for dirent.d_type]) AC_COMPILE_IFELSE([AC_LANG_SOURCE([ #include @@ -437,6 +476,8 @@ AC_CONFIG_FILES([Makefile src/GLdispatch/Makefile src/GLdispatch/vnd-glapi/Makefile src/util/Makefile + src/app_profile/Makefile + src/vulkanconfig/Makefile tests/Makefile tests/dummy/Makefile]) AC_OUTPUT diff --git a/include/glvnd/libeglabi.h b/include/glvnd/libeglabi.h index b2f19c01fe10210f4bf83d7fce42c09386962c00..546c15e8d0f072da18aa3ae80f956d1409848ce0 100644 --- a/include/glvnd/libeglabi.h +++ b/include/glvnd/libeglabi.h @@ -221,6 +221,30 @@ enum * to modify libEGL to match. */ __EGL_VENDOR_STRING_PLATFORM_EXTENSIONS, + + /*! + * The name of the vendor, if the vendor supports GPU offloading. + * + * If the vendor provides this string, then it must also support libglvnd's + * GPU offloading interface. + * + * If the process is configured for GPU offloading, then the libglvnd will + * append an EGL_DEVICE_EXT attribute to eglGetPlatformDisplay, which + * specifies an EGLDeviceEXT handle. + * + * If the vendor can't support GPU offloading for the native display on + * that particular device, then the vendor's return EGL_NO_DISPLAY from + * its eglGetPlatformDisplay implementation. That is, the vendor must check + * for support in eglGetPlatformDisplay, *not* in eglInitialize. + * + * In addition, the vendor must support the EGL_EXT_device_persistent_id + * extension, and the EGL_DRIVER_NAME_EXT string for each device must match + * the string for __EGL_VENDOR_OFFLOAD_NAME. + * + * The vendor name should also match the vendor name used for GLX, so that + * the same configuration can apply to EGL and GLX. + */ + __EGL_VENDOR_OFFLOAD_NAME, }; /*! diff --git a/include/glvnd/libglxabi.h b/include/glvnd/libglxabi.h index 195f2a92771acdfc56646172460e5b44bb2ac03d..c34c439a7e97a1252980d511becdba95fa48d126 100644 --- a/include/glvnd/libglxabi.h +++ b/include/glvnd/libglxabi.h @@ -96,7 +96,7 @@ extern "C" { * will still work. */ #define GLX_VENDOR_ABI_MAJOR_VERSION ((uint32_t) 1) -#define GLX_VENDOR_ABI_MINOR_VERSION ((uint32_t) 0) +#define GLX_VENDOR_ABI_MINOR_VERSION ((uint32_t) 1) #define GLX_VENDOR_ABI_VERSION ((GLX_VENDOR_ABI_MAJOR_VERSION << 16) | GLX_VENDOR_ABI_MINOR_VERSION) static inline uint32_t GLX_VENDOR_ABI_GET_MAJOR_VERSION(uint32_t version) { @@ -223,7 +223,6 @@ typedef struct __GLXapiExportsRec { * thing that matters is finding out which vendor to dispatch to. */ __GLXvendorInfo * (*vendorFromDrawable)(Display *dpy, GLXDrawable drawable); - } __GLXapiExports; /***************************************************************************** @@ -386,6 +385,26 @@ typedef struct __GLXapiImportsRec { */ void (*patchThreadAttach)(void); + /*! + * (OPTIONAL) Requests that a vendor enable GPU offloading for a display. + * + * If the user requests GPU offloading, then libglvnd will call this + * function before it tries to select a vendor for any screens. + * + * If the vendor supports GPU offloading, then it should set + * enabledScreens[SCREEN] to True for whichever screens it supports, and + * then return True. + * + * If initOffloadVendor returns True, then libglvnd will assign this vendor + * to any screens where enabledScreens[SCREEN] is True. For any remaining + * screens, libglvnd will use its nromal vendor selection behavior. + * + * \param dpy The display pointer. + * \param deviceUUID The device UUID, as a 16-byte binary value. + * \param[out] enabledScreens An array of length ScreenCount(dpy), which + * indicates which screens the vendor supports. + */ + Bool (*initOffloadVendor) (Display *dpy, const GLubyte *deviceUUID, Bool *enabledScreens); } __GLXapiImports; /*****************************************************************************/ diff --git a/meson.build b/meson.build index fb456bc2cf7d007ea89f3407c86bab555152d310..57985fcc3d5824488792d93c3043c5f19afb8d7c 100644 --- a/meson.build +++ b/meson.build @@ -106,6 +106,21 @@ elif not get_option('glx').disabled() and dep_x11.found() endif dep_glx = [dep_xext, dep_glproto] +dep_vulkan = dep_null +with_vulkan = false +if get_option('vulkan').enabled() + if not get_option('app-profile') + error('Can\'t build the Vulkan layer without the app profile library.') + endif + dep_vulkan = dependency('vulkan', required : true) + with_vulkan = true +elif get_option('vulkan').auto() + if get_option('app-profile') + dep_vulkan = dependency('vulkan', required : false) + with_vulkan = dep_vulkan.found() + endif +endif + if cc.compiles('typeof(int *);', name : 'typeof') add_project_arguments('-DHAVE_TYPEOF', language : ['c']) endif @@ -220,6 +235,10 @@ if cc.has_header_symbol('dlfcn.h', 'RTLD_NOLOAD') add_project_arguments('-DHAVE_RTLD_NOLOAD', language : ['c']) endif +if cc.has_header_symbol('fnmatch.h', 'FNM_CASEFOLD', args: ['-D_GNU_SOURCE']) + add_project_arguments('-DHAVE_FNM_CASEFOLD', language : ['c']) +endif + if cc.has_member('struct dirent', 'd_type', prefix : '#include ') add_project_arguments('-DHAVE_DIRENT_DTYPE', language : ['c']) endif diff --git a/meson_options.txt b/meson_options.txt index 43198f6d92aa1d63c7471af1e438c879fb140c57..27485bbcfeddabc5659af54246b4bde06c830e09 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -83,3 +83,14 @@ option( type : 'feature', description : 'Allow vendor libraries to patch OpenGL entrypoint functions.' ) +option( + 'app-profile', + type : 'boolean', + value : true, + description : 'Build and use the app profile library.' +) +option( + 'vulkan', + type : 'feature', + description : 'Build the Vulkan app profile layer.' +) diff --git a/src/EGL/Makefile.am b/src/EGL/Makefile.am index c49d97685f10075d9dc08d21757e7c6600323469..53ce5c949f637430582a1320ebfbe0667d650622 100644 --- a/src/EGL/Makefile.am +++ b/src/EGL/Makefile.am @@ -44,6 +44,7 @@ GL_DISPATCH_DIR = ../GLdispatch libEGL_la_CFLAGS = -I$(srcdir)/$(UTHASH_DIR) libEGL_la_CFLAGS += -I$(srcdir)/$(UTIL_DIR) libEGL_la_CFLAGS += -I$(srcdir)/$(GL_DISPATCH_DIR) +libEGL_la_CFLAGS += -I$(top_srcdir)/src/app_profile libEGL_la_CFLAGS += -I$(top_srcdir)/include if ENABLE_X11 libEGL_la_CFLAGS += $(X11_CFLAGS) @@ -65,6 +66,7 @@ libEGL_la_LIBADD += $(UTIL_DIR)/libutils_misc.la libEGL_la_LIBADD += $(UTIL_DIR)/libcJSON.la libEGL_la_LIBADD += $(UTIL_DIR)/libwinsys_dispatch.la libEGL_la_LIBADD += libEGL_dispatch_stubs.la +libEGL_la_LIBADD += $(top_builddir)/src/app_profile/libGlvndAppProfile.la libEGL_la_LDFLAGS = -shared -Wl,-Bsymbolic -version-info 2:0:1 $(LINKER_FLAG_NO_UNDEFINED) diff --git a/src/EGL/libegl.c b/src/EGL/libegl.c index 9fea10a1c7f50071547a380543cfab7f610babc1..2b16275ed3a06b946e4bb6b0f6d5914e25257c37 100644 --- a/src/EGL/libegl.c +++ b/src/EGL/libegl.c @@ -48,6 +48,7 @@ #include "utils_misc.h" #include "lkdhash.h" +#include "app_profile.h" #if !defined(HAVE_RTLD_NOLOAD) #define RTLD_NOLOAD 0 @@ -267,6 +268,192 @@ static EGLenum GuessPlatformType(EGLNativeDisplayType display_id) return EGL_NONE; }; +static EGLBoolean FindOffloadDevice(const char *vendorName, const uint8_t *uuid, + __EGLvendorInfo **ret_vendor, EGLDeviceEXT *ret_device) +{ + struct glvnd_list *vendorList = __eglLoadVendors(); + __EGLvendorInfo *vendor; + + glvnd_list_for_each_entry(vendor, vendorList, entry) { + const char *name; + EGLDeviceEXT *devices; + EGLint num = 0; + EGLBoolean found = EGL_FALSE; + EGLint i; + + if (!vendor->supportsDevice || !vendor->supportsDeviceQuery) { + continue; + } + if (vendor->staticDispatch.queryDeviceBinaryEXT == NULL) { + continue; + } + if (vendor->eglvc.getVendorString == NULL) { + continue; + } + + name = vendor->eglvc.getVendorString(__EGL_VENDOR_OFFLOAD_NAME); + if (name == NULL || strcmp(name, vendorName) != 0) { + continue; + } + + if (!vendor->staticDispatch.queryDevicesEXT(0, NULL, &num) || num <= 0) { + continue; + } + + devices = malloc(num * sizeof(EGLDeviceEXT)); + if (devices == NULL) { + return EGL_FALSE; + } + + if (!vendor->staticDispatch.queryDevicesEXT(num, devices, &num) || num <= 0) { + free(devices); + continue; + } + + for (i=0; istaticDispatch.queryDeviceStringEXT(devices[i], EGL_EXTENSIONS); + if (str == NULL || !IsTokenInString(str, NAME_PERSISTENT_ID, sizeof(NAME_PERSISTENT_ID) - 1, " ")) { + continue; + } + + str = vendor->staticDispatch.queryDeviceStringEXT(devices[i], EGL_DRIVER_NAME_EXT); + if (str == NULL || strcmp(str, vendorName) != 0) { + continue; + } + + if (!vendor->staticDispatch.queryDeviceBinaryEXT(devices[i], + EGL_DEVICE_UUID_EXT, sizeof(deviceUUID), deviceUUID, &size) + || size != sizeof(deviceUUID)) { + continue; + } + + if (memcmp(deviceUUID, uuid, sizeof(deviceUUID)) != 0) { + continue; + } + + // We found a matching device, so use it. + *ret_device = devices[i]; + *ret_vendor = vendor; + found = EGL_TRUE; + break; + } + free(devices); + + if (found) { + return EGL_TRUE; + } + } + + return EGL_FALSE; +} + +static EGLBoolean TryOffloadDisplay(EGLenum platform, + void *native_display, const EGLAttrib *attrib_list, + const char *funcName, + __EGLvendorInfo **ret_vendor, EGLDisplay *ret_dpy) +{ + static const uintptr_t PROFILE_HINTS[] = { + GLVND_PROFILE_HINT_API_NAME, (uintptr_t) "egl", + 0 + }; + + GLVNDProfile *profile; + int major, minor; + int i, devCount; + const char **profileVendors = NULL; + const uint8_t **profileUUIDs = NULL; + EGLAttrib *newAttribs = NULL; + int attribCount = 0; + EGLBoolean found = EGL_FALSE; + + if (platform == EGL_PLATFORM_DEVICE_EXT) { + return EGL_FALSE; + } + + // Count the number of attributes, and see if the application already + // specified a device. + if (attrib_list != NULL) { + for (attribCount = 0; attrib_list[attribCount] != EGL_NONE; attribCount += 2) { + if (attrib_list[attribCount] == EGL_DEVICE_EXT) { + // The application already specified a device. + return EGL_FALSE; + } + } + } + + glvndProfileGetVersion(&major, &minor); + if (major != PROFILE_VERSION_MAJOR) { + return EGL_FALSE; + } + + profile = glvndProfileLoad(PROFILE_HINTS); + if (profile == NULL) { + return EGL_FALSE; + } + + devCount = glvndProfileGetAttribute(profile, GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, 0, NULL, NULL); + if (devCount <= 0) { + glvndProfileFree(profile); + return EGL_FALSE; + } + profileUUIDs = alloca(devCount * sizeof(const uint8_t *)); + profileVendors = alloca(devCount * sizeof(const char *)); + if (glvndProfileGetAttribute(profile, GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, + devCount, NULL, (uintptr_t *) profileUUIDs) != devCount) + { + glvndProfileFree(profile); + return EGL_FALSE; + } + if (glvndProfileGetAttribute(profile, GLVND_PROFILE_ATTRIB_OFFLOAD_VENDOR_NAME, + devCount, NULL, (uintptr_t *) profileVendors) != devCount) + { + glvndProfileFree(profile); + return EGL_FALSE; + } + + // Allocate a copy of the attribute list, with an EGL_DEVICE_EXT attribute + // appended to the end. + newAttribs = malloc((attribCount * 2 + 3) * sizeof(EGLAttrib)); + if (newAttribs == NULL) { + glvndProfileFree(profile); + return EGL_FALSE; + } + if (attribCount > 0) { + memcpy(newAttribs, attrib_list, attribCount * 2 * sizeof(EGLAttrib)); + } + newAttribs[attribCount] = EGL_DEVICE_EXT; + newAttribs[attribCount + 1] = 0; + newAttribs[attribCount + 2] = EGL_NONE; + + for (i = 0; i < devCount; i++) { + __EGLvendorInfo *vendor = NULL; + EGLDeviceEXT dev = EGL_NO_DEVICE_EXT; + EGLDisplay dpy; + + if (!FindOffloadDevice(profileVendors[i], profileUUIDs[i], &vendor, &dev)) { + continue; + } + + newAttribs[attribCount + 1] = (EGLAttrib) dev; + dpy = vendor->eglvc.getPlatformDisplay(platform, native_display, newAttribs); + if (dpy != NULL) { + *ret_vendor = vendor; + *ret_dpy = dpy; + found = EGL_TRUE; + break; + } + } + + glvndProfileFree(profile); + free(newAttribs); + return found; +} + static EGLDisplay GetPlatformDisplayCommon(EGLenum platform, void *native_display, const EGLAttrib *attrib_list, const char *funcName) @@ -309,6 +496,21 @@ static EGLDisplay GetPlatformDisplayCommon(EGLenum platform, } } + if (dpyInfo == NULL) { + EGLDisplay dpy = EGL_NO_DISPLAY; + __EGLvendorInfo *vendor = NULL; + + if (TryOffloadDisplay(platform, native_display, attrib_list, funcName, + &vendor, &dpy)) { + dpyInfo = __eglAddDisplay(dpy, vendor); + if (dpyInfo == NULL) { + __eglReportCritical(EGL_BAD_ALLOC, funcName, __eglGetThreadLabel(), + "Can't allocate display"); + return EGL_NO_DISPLAY; + } + } + } + // Note that if multiple threads try to call eglGetPlatformDisplay with the // same arguments, then the same vendor library should return the same // EGLDisplay handle. In that case, __eglAddDisplay will return the same diff --git a/src/EGL/libeglabipriv.h b/src/EGL/libeglabipriv.h index bf7d3e356f2fbb1451d468d726a60b8c448de963..b3170f20b176739db835903de643d43b3b1d67a2 100644 --- a/src/EGL/libeglabipriv.h +++ b/src/EGL/libeglabipriv.h @@ -91,7 +91,9 @@ typedef struct __EGLdispatchTableStaticRec { // Extension functions that libEGL cares about. EGLBoolean (* queryDevicesEXT) (EGLint max_devices, EGLDeviceEXT *devices, EGLint *num_devices); + const char * (* queryDeviceStringEXT) (EGLDeviceEXT device, EGLint name); EGLBoolean (* queryDisplayAttrib) (EGLDisplay dpy, EGLint attribute, EGLAttrib *value); + EGLBoolean (* queryDeviceBinaryEXT) (EGLDeviceEXT device, EGLint name, EGLint max_size, void *value, EGLint *size); EGLint (* debugMessageControlKHR) (EGLDEBUGPROCKHR callback, const EGLAttrib *attrib_list); diff --git a/src/EGL/libeglvendor.c b/src/EGL/libeglvendor.c index acece59708ab03b9623c5b0ecd39839b6a43ced5..cd540af9bb9ebc24e1dbd27230559c3c34ab28c7 100644 --- a/src/EGL/libeglvendor.c +++ b/src/EGL/libeglvendor.c @@ -242,10 +242,12 @@ static GLboolean LookupVendorEntrypoints(__EGLvendorInfo *vendor) LOADENTRYPOINT(createPlatformPixmapSurface, "eglCreatePlatformPixmapSurface" ); LOADENTRYPOINT(waitSync, "eglWaitSync" ); LOADENTRYPOINT(queryDevicesEXT, "eglQueryDevicesEXT" ); + LOADENTRYPOINT(queryDeviceStringEXT, "eglQueryDeviceStringEXT" ); LOADENTRYPOINT(debugMessageControlKHR, "eglDebugMessageControlKHR" ); LOADENTRYPOINT(queryDebugKHR, "eglQueryDebugKHR" ); LOADENTRYPOINT(labelObjectKHR, "eglLabelObjectKHR" ); + LOADENTRYPOINT(queryDeviceBinaryEXT, "eglQueryDeviceBinaryEXT" ); #undef LOADENTRYPOINT // eglQueryDisplayAttrib has KHR, EXT, and NV versions. They're all @@ -385,6 +387,7 @@ static void CheckVendorExtensionString(__EGLvendorInfo *vendor, const char *str) { static const char NAME_DEVICE_BASE[] = "EGL_EXT_device_base"; static const char NAME_DEVICE_ENUM[] = "EGL_EXT_device_enumeration"; + static const char NAME_DEVICE_QUERY[] = "EGL_EXT_device_query"; static const char NAME_PLATFORM_DEVICE[] = "EGL_EXT_platform_device"; static const char NAME_MESA_PLATFORM_GBM[] = "EGL_MESA_platform_gbm"; static const char NAME_KHR_PLATFORM_GBM[] = "EGL_KHR_platform_gbm"; @@ -397,9 +400,20 @@ static void CheckVendorExtensionString(__EGLvendorInfo *vendor, const char *str) return; } + if (!vendor->supportsDevice || !vendor->supportsDeviceQuery) { + if (IsTokenInString(str, NAME_DEVICE_BASE, sizeof(NAME_DEVICE_BASE) - 1, " ")) { + vendor->supportsDevice = EGL_TRUE; + vendor->supportsDeviceQuery = EGL_TRUE; + } + } + + if (!vendor->supportsDeviceQuery) { + if (IsTokenInString(str, NAME_DEVICE_QUERY, sizeof(NAME_DEVICE_QUERY) - 1, " ")) { + vendor->supportsDeviceQuery = EGL_TRUE; + } + } if (!vendor->supportsDevice) { - if (IsTokenInString(str, NAME_DEVICE_BASE, sizeof(NAME_DEVICE_BASE) - 1, " ") - || IsTokenInString(str, NAME_DEVICE_ENUM, sizeof(NAME_DEVICE_ENUM) - 1, " ")) { + if (IsTokenInString(str, NAME_DEVICE_ENUM, sizeof(NAME_DEVICE_ENUM) - 1, " ")) { vendor->supportsDevice = EGL_TRUE; } } @@ -445,6 +459,9 @@ static void CheckVendorExtensions(__EGLvendorInfo *vendor) if (vendor->staticDispatch.queryDevicesEXT == NULL) { vendor->supportsDevice = EGL_FALSE; } + if (vendor->staticDispatch.queryDeviceStringEXT == NULL) { + vendor->supportsDeviceQuery = EGL_FALSE; + } if (!vendor->supportsDevice) { vendor->supportsPlatformDevice = EGL_FALSE; diff --git a/src/EGL/libeglvendor.h b/src/EGL/libeglvendor.h index 443f285e20ff86100d7134158d740f791f710a10..ec7ac98374a6d1cfad9f9532008e245922e4284b 100644 --- a/src/EGL/libeglvendor.h +++ b/src/EGL/libeglvendor.h @@ -30,6 +30,7 @@ struct __EGLvendorInfoRec { EGLBoolean supportsGLES; EGLBoolean supportsDevice; + EGLBoolean supportsDeviceQuery; EGLBoolean supportsPlatformDevice; EGLBoolean supportsPlatformGbm; EGLBoolean supportsPlatformX11; diff --git a/src/EGL/meson.build b/src/EGL/meson.build index 7396bd12eb72560873a81750681a1e85e298778c..2b3c95827b1999345aa36d19de97a73b98fb1e4f 100644 --- a/src/EGL/meson.build +++ b/src/EGL/meson.build @@ -49,6 +49,7 @@ libEGL = shared_library( dependencies : [ dep_threads, dep_dl, dep_m, dep_x11_headers, idep_trace, idep_glvnd_pthread, idep_utils_misc, idep_cjson, idep_winsys_dispatch, idep_gldispatch, + idep_AppProfile, ], version : '1.1.0', install : true, diff --git a/src/GLX/Makefile.am b/src/GLX/Makefile.am index 49a352cc7c5c8e8095bbc99a6ade75429b1b39bb..122b1c5951de14212d12d42c6582424865b1f6a9 100644 --- a/src/GLX/Makefile.am +++ b/src/GLX/Makefile.am @@ -42,6 +42,7 @@ libGLX_la_CFLAGS = -I$(srcdir)/$(UTHASH_DIR) libGLX_la_CFLAGS += -I$(srcdir)/$(UTIL_DIR) libGLX_la_CFLAGS += -I$(srcdir)/$(GL_DISPATCH_DIR) libGLX_la_CFLAGS += -I$(top_srcdir)/include +libGLX_la_CFLAGS += -I$(top_srcdir)/src/app_profile libGLX_la_CFLAGS += $(GLPROTO_CFLAGS) $(X11_CFLAGS) $(XEXT_CFLAGS) # Required library flags @@ -57,6 +58,7 @@ libGLX_la_LIBADD += $(UTIL_DIR)/libglvnd_pthread.la libGLX_la_LIBADD += $(UTIL_DIR)/libutils_misc.la libGLX_la_LIBADD += $(UTIL_DIR)/libapp_error_check.la libGLX_la_LIBADD += $(UTIL_DIR)/libwinsys_dispatch.la +libGLX_la_LIBADD += $(top_builddir)/src/app_profile/libGlvndAppProfile.la libGLX_la_LDFLAGS = -shared -Wl,-Bsymbolic -version-info 0 $(LINKER_FLAG_NO_UNDEFINED) diff --git a/src/GLX/libglxmapping.c b/src/GLX/libglxmapping.c index ff2c3a63679762fc0eb2e72dc5f068349c4b2a69..4f920f8e638213ea048b5ff4d623d8e1682410b8 100644 --- a/src/GLX/libglxmapping.c +++ b/src/GLX/libglxmapping.c @@ -41,6 +41,7 @@ #include "glvnd_genentry.h" #include "trace.h" #include "winsys_dispatch.h" +#include "app_profile.h" #include "lkdhash.h" @@ -127,6 +128,33 @@ static const __GLXapiExports glxExportsTable = { .vendorFromDrawable = __glXVendorFromDrawable, }; +static GLVNDProfile *appProfile = NULL; +static glvnd_once_t appProfileInitControl = GLVND_ONCE_INIT; + +static void LoadAppProfileOnce(void) +{ + int major, minor; + static const uintptr_t PROFILE_HINTS[] = { + GLVND_PROFILE_HINT_API_NAME, (uintptr_t) "GLX", + 0 + }; + + major = minor = -1; + glvndProfileGetVersion(&major, &minor); + if (major != PROFILE_VERSION_MAJOR) { + // The app profile library is a version that we don't support. + return; + } + + appProfile = glvndProfileLoad(PROFILE_HINTS); +} + +static void LoadAppProfile(void) +{ + __glvndPthreadFuncs.once(&appProfileInitControl, LoadAppProfileOnce); +} + + /*! * Looks for a GLX dispatch function. * @@ -516,6 +544,70 @@ fail: return NULL; } +static Bool TryGPUOffloadingVendor(__GLXdisplayInfo *dpyInfo, const char *vendorName, const GLubyte *deviceUUID) +{ + Bool *screensSupported; + __GLXvendorInfo *vendor; + int i; + + vendor = __glXLookupVendorByName(vendorName); + if (vendor == NULL || vendor->glxvc->initOffloadVendor == NULL) { + return False; + } + + screensSupported = alloca(sizeof(Bool) * ScreenCount(dpyInfo->dpy)); + memset(screensSupported, 0, sizeof(Bool) * ScreenCount(dpyInfo->dpy)); + + if (!vendor->glxvc->initOffloadVendor(dpyInfo->dpy, deviceUUID, screensSupported)) { + return False; + } + + // The vendor library supports offloading, so assign it to whichever + // screens it supports. + for (i=0; idpy); i++) { + if (screensSupported[i]) { + dpyInfo->vendors[i] = vendor; + } + } + + return True; +} + +static void CheckGPUOffloading(__GLXdisplayInfo *dpyInfo) +{ + int i, count; + const char **vendorNames; + const GLubyte **deviceUUIDs; + + LoadAppProfile(); + + if (appProfile == NULL) { + return; + } + + count = glvndProfileGetAttribute(appProfile, GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, 0, NULL, NULL); + if (count <= 0) { + return; + } + + deviceUUIDs = alloca(count * sizeof(const char *)); + vendorNames = alloca(count * sizeof(const GLubyte *)); + if (glvndProfileGetAttribute(appProfile, GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, + count, NULL, (uintptr_t *) deviceUUIDs) != count) { + return; + } + if (glvndProfileGetAttribute(appProfile, GLVND_PROFILE_ATTRIB_OFFLOAD_VENDOR_NAME, + count, NULL, (uintptr_t *) vendorNames) != count) { + return; + } + + for (i = 0; i < count; i++) { + if (TryGPUOffloadingVendor(dpyInfo, vendorNames[i], deviceUUIDs[i])) { + break; + } + } +} + __GLXvendorInfo *__glXLookupVendorByScreen(Display *dpy, const int screen) { __GLXvendorInfo *vendor = NULL; @@ -539,6 +631,12 @@ __GLXvendorInfo *__glXLookupVendorByScreen(Display *dpy, const int screen) } __glvndPthreadFuncs.rwlock_wrlock(&dpyInfo->vendorLock); + + if (!dpyInfo->offloadInitDone) { + dpyInfo->offloadInitDone = True; + CheckGPUOffloading(dpyInfo); + } + vendor = dpyInfo->vendors[screen]; if (!vendor) { @@ -1087,6 +1185,9 @@ void __glXMappingTeardown(Bool doReset) /* Free any generated entrypoints */ glvndFreeEntrypoints(); + + glvndProfileFree(appProfile); + appProfile = NULL; } } diff --git a/src/GLX/libglxmapping.h b/src/GLX/libglxmapping.h index 3ad1886e0e850987648cf5a4ea381f10f1d95d48..3bc5da53979ef4296be0a4c1e1f2e77115306a9d 100644 --- a/src/GLX/libglxmapping.h +++ b/src/GLX/libglxmapping.h @@ -67,6 +67,12 @@ typedef struct __GLXdisplayInfoRec { * Do not access this directly. Instead, call \c __glXLookupVendorByScreen. */ __GLXvendorInfo **vendors; + + /** + * Keeps track of whether we've checked for GPU offloading support for + * this display. + */ + Bool offloadInitDone; glvnd_rwlock_t vendorLock; DEFINE_LKDHASH(__GLXvendorXIDMappingHash, xidVendorHash); diff --git a/src/GLX/meson.build b/src/GLX/meson.build index 98f4d1317572837040f5ee8a04256302457cbbb0..05aee7d5d5843e55694142baafd6b1a702cbe506 100644 --- a/src/GLX/meson.build +++ b/src/GLX/meson.build @@ -44,6 +44,7 @@ libGLX = shared_library( dep_dl, dep_x11, dep_glx, idep_gldispatch, idep_trace, idep_glvnd_pthread, idep_utils_misc, idep_app_error_check, idep_winsys_dispatch, + idep_AppProfile, ], gnu_symbol_visibility : 'hidden', install : true, diff --git a/src/Makefile.am b/src/Makefile.am index c9551c0d55eb93abb480023a83ba9a3df941fdad..2298d56d5a3786ab96c2a0379e49dc3523a0d770 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,5 +1,6 @@ SUBDIRS = SUBDIRS += util +SUBDIRS += app_profile SUBDIRS += GLdispatch SUBDIRS += OpenGL @@ -12,6 +13,10 @@ SUBDIRS += GLX SUBDIRS += GL endif +if ENABLE_VULKAN +SUBDIRS += vulkanconfig +endif + if ENABLE_GLES1 SUBDIRS += GLESv1 endif diff --git a/src/app_profile/Makefile.am b/src/app_profile/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..71eba647bb62f1a354976aa46fbe42deaf3e4e1e --- /dev/null +++ b/src/app_profile/Makefile.am @@ -0,0 +1,56 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and/or associated documentation files (the +# "Materials"), to deal in the Materials without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Materials, and to +# permit persons to whom the Materials are furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# unaltered in all copies or substantial portions of the Materials. +# Any additions, deletions, or changes to the original source files +# must be clearly indicated in accompanying documentation. +# +# THE MATERIALS ARE 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 +# MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +if ENABLE_APP_PROFILE + +lib_LTLIBRARIES = libGlvndAppProfile.la + +# Warning settings +# Include paths +libGlvndAppProfile_la_CFLAGS = -I$(top_srcdir)/include +libGlvndAppProfile_la_CFLAGS += -I$(top_srcdir)/src/util +libGlvndAppProfile_la_CFLAGS += \ + -DSYSCONFDIR=\"@sysconfdir@\" \ + -DDATADIR=\"@datadir@\" + +# Required libraries +libGlvndAppProfile_la_LIBADD = $(top_builddir)/src/util/libutils_misc.la + +libGlvndAppProfile_la_LDFLAGS = -shared -Wl,-Bsymbolic -version-info 0 $(LINKER_FLAG_NO_UNDEFINED) + +libGlvndAppProfile_la_SOURCES = \ + app_profile.c \ + app_profile_config.c \ + toml.c \ + toml.h \ + app_profile.h \ + app_profile_internal.h + +else # ENABLE_APP_PROFILE + +noinst_LTLIBRARIES = libGlvndAppProfile.la +libGlvndAppProfile_la_SOURCES = \ + app_profile_stub.c \ + app_profile_internal.h + +endif # ENABLE_APP_PROFILE diff --git a/src/app_profile/app_profile.c b/src/app_profile/app_profile.c new file mode 100644 index 0000000000000000000000000000000000000000..e9b447c027ff61fe46aa5fc5be703de98e67c42b --- /dev/null +++ b/src/app_profile/app_profile.c @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#include "app_profile_internal.h" + +#include +#include +#include +#include + +#include "compiler.h" +#include "utils_misc.h" + +PUBLIC void glvndProfileGetVersion(int *major, int *minor) +{ + if (major != NULL) { + *major = PROFILE_VERSION_MAJOR; + } + if (minor != NULL) { + *minor = PROFILE_VERSION_MINOR; + } +} + +/** + * Parses a UUID from a string. + * + * This will accept any string that has exactly 32 hexadecimal digits in it. + * Any non-digit characters are ignored, so spacing or separators don't matter. + */ +static int ParseUUID(const char *str, uint8_t *uuid) +{ + uint8_t digits[32]; + int count = 0; + const char *ptr; + int i; + + // Extract the values of each hex digit + for (ptr = str; *ptr != '\x00' && count < 32; ptr++) { + if (*ptr >= '0' && *ptr <= '9') { + digits[count++] = *ptr - '0'; + } else if (*ptr >= 'a' && *ptr <= 'f') { + digits[count++] = 10 + *ptr - 'a'; + } else if (*ptr >= 'A' && *ptr <= 'F') { + digits[count++] = 10 + *ptr - 'A'; + } + } + if (count != 32) { + // There are too few digits in the string + return -1; + } + + // Make sure that we don't have any extra digits + for ( ; *ptr != '\x00'; ptr++) { + if (isxdigit(*ptr)) { + return -1; + } + } + + // Fill in the binary UUID value + for (i=0; i<16; i++) { + uint8_t *pair = &digits[i * 2]; + uuid[i] = pair[0] << 4 | pair[1]; + } + + return 0; +} + +/** + * Parses the device ID in the __GLVND_PROFILE_DEVICE environment variable. + */ +static int ParseDeviceID(GLVNDProfile *profile, const char *env) +{ + char **strings = SplitString(env, NULL, ":"); + int count = 0; + int i; + + if (strings == NULL) { + return -1; + } + + for (i=0; strings[i] != NULL; i++) { + char *str = strings[i]; + + if (AddDeviceID(profile, str) < 0) { + count = -1; + break; + } + count++; + } + + free(strings); + return count; +} + +PUBLIC GLVNDProfile *glvndProfileLoad(const uintptr_t *hints) +{ + const char *env; + GLVNDProfile *profile; + + // If we're running setuid, then don't read anything. + if (getuid() != geteuid() || getgid() != getegid()) { + return NULL; + } + + profile = calloc(1, sizeof(GLVNDProfile)); + if (profile == NULL) { + return NULL; + } + + // First, check to see if the user has explicitly configured the device. + env = getenv("__GLVND_PROFILE_DEVICE"); + if (env != NULL) { + int ret = ParseDeviceID(profile, env); + if (ret < 0) { + glvndProfileFree(profile); + return NULL; + } + } else { + if (ReadConfigFile(profile, hints) != 0) { + glvndProfileFree(profile); + return NULL; + } + } + + env = getenv("__GLVND_PROFILE_FILTER_DEVICE"); + if (env != NULL) { + profile->filterDevices = (atoi(env) != 0); + } + + return profile; +} + +PUBLIC void glvndProfileFree(GLVNDProfile *profile) +{ + if (profile != NULL) { + int i; + for (i=0; ideviceCount; i++) { + free(profile->devices[i]); + } + free(profile->devices); + free(profile); + } +} + +PUBLIC int glvndProfileGetAttribute(GLVNDProfile *profile, int name, int max, + size_t *valueSizes, uintptr_t *values) +{ + int count, i; + + if (profile == NULL) { + return -1; + } + + if (name == GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID) { + count = (max < profile->deviceCount ? max : profile->deviceCount); + + if (values != NULL) { + for (i=0; idevices[i]->uuid; + } + } + if (valueSizes != NULL) { + for (i=0; idevices[i]->uuid); + } + } + + return profile->deviceCount; + } else if (name == GLVND_PROFILE_ATTRIB_OFFLOAD_VENDOR_NAME) { + count = (max < profile->deviceCount ? max : profile->deviceCount); + if (values != NULL) { + for (i=0; idevices[i]->vendor; + } + } + if (valueSizes != NULL) { + for (i=0; idevices[i]->vendor); + } + } + + return profile->deviceCount; + } else if (name == GLVND_PROFILE_ATTRIB_FILTER_DEVICES) { + if (max > 0) { + if (values != NULL) { + values[0] = (uintptr_t) profile->filterDevices; + } + if (valueSizes != NULL) { + valueSizes[0] = 0; + } + } + return 1; + } else { + return -1; + } +} + +int AddDeviceID(GLVNDProfile *profile, const char *deviceString) +{ + GLVNDProfileDevice **buf; + GLVNDProfileDevice *device; + const char *sep; + size_t vendorLen; + uint8_t uuid[16]; + int i; + + sep = strchr(deviceString, '/'); + if (sep == NULL || sep == deviceString) { + return 0; + } + + vendorLen = sep - deviceString; + if (ParseUUID(sep + 1, uuid) != 0) { + return 0; + } + + for (i=0; ideviceCount; i++) { + if (strncmp(profile->devices[i]->vendor, deviceString, vendorLen) == 0 + && memcmp(profile->devices[i]->uuid, uuid, sizeof(profile->devices[i]->uuid)) == 0) { + // The device is already in the list, so just return. + return 0; + } + } + + buf = realloc(profile->devices, (profile->deviceCount + 1) * sizeof(GLVNDProfileDevice *)); + if (buf == NULL) { + return -1; + } + profile->devices = buf; + + device = malloc(sizeof(GLVNDProfileDevice) + vendorLen + 1); + if (device == NULL) { + return -1; + } + device->vendor = (char *) (device + 1); + memcpy(device->vendor, deviceString, vendorLen); + device->vendor[vendorLen] = '\x00'; + memcpy(device->uuid, uuid, sizeof(device->uuid)); + + profile->devices[profile->deviceCount] = device; + profile->deviceCount++; + return 0; +} + diff --git a/src/app_profile/app_profile.h b/src/app_profile/app_profile.h new file mode 100644 index 0000000000000000000000000000000000000000..9f2f49fd5a778dd51264f61a09a29a483d1d648c --- /dev/null +++ b/src/app_profile/app_profile.h @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#ifndef APP_PROFILE_H +#define APP_PROFILE_H + +/** + * \file + * + * An application profile interface for configuring GPU offloading. + * + * This library is used by API-specific libraries (currently, libEGL, libGLX, + * and a Vulkan layer) as a common interface for reading configuration + * attributes from an application profile. Using a common library like this + * ensures that a user can configure an application without needing to know or + * care which API the application is going to use. + * + * Currently, the only attributes defined are used as a vendor-agnostic way to + * configure GPU offloading, but other attributes may be added in the future. + */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define PROFILE_VERSION_MAJOR 0 +#define PROFILE_VERSION_MINOR 0 + +/** + * Hints that can be passed to \p glvndProfileLoad. The hints are passed as an + * array of (name, value) pairs, ending with zero. + */ +enum +{ + // Start the attributes with 1, because 0 is used to terminate the array. + + /** + * Specifies the name of the executable to look up. If not specified, then + * the library will try to find this on its own. + */ + GLVND_PROFILE_HINT_EXECUTABLE_NAME = 1, + + /** + * Specifies which API library is loading the profile. This should be a + * string, such as "glx", "egl", or "vulkan". + */ + GLVND_PROFILE_HINT_API_NAME, +}; + +/** + * Attribute names for \c glvndProfileGetAttribute. Each attribute can be an + * integer, a string, or some other pointer. + */ +enum +{ + /** + * (String) The name of the vendor to use for GPU offloading. + * + * If two or more drivers can support the same physical device, then they + * may use the same device UUID. In that case, the vendor name is used to + * select which driver to use. + * + * For EGL, this name is the same as the EGL_DRIVER_NAME_EXT string, as + * defined by the EGL_EXT_device_persistent_id extension. + * + * For GLX, this is the name of the vendor library to load. + */ + GLVND_PROFILE_ATTRIB_OFFLOAD_VENDOR_NAME, + + /** + * (Binary) The UUID of the device to use for GPU offloading. + * + * This attribute specifies the UUID of the device to use for offloading as + * a 16-byte binary value. + * + * In EGL, this value will match the EGL_DEVICE_UUID_EXT value defined in + * the EGL_EXT_device_persistent_id extension. + * + * In Vulkan, this value will match the value of + * VkPhysicalDeviceIDProperties::deviceUUID. + * + * Note that the number of valus for + * GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID and + * GLVND_PROFILE_ATTRIB_OFFLOAD_VENDOR_NAME will always be equal. + */ + GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, + + /** + * (Integer) If this is nonzero, then caller should filter out any devices + * besides those in the profile, to force the application to choose the + * selected device. + */ + GLVND_PROFILE_ATTRIB_FILTER_DEVICES, +}; + +/** + * An opaque type to hold an application profile. + */ +typedef struct GLVNDProfileRec GLVNDProfile; + +/** + * Returns the version number of the app profile library. + */ +void glvndProfileGetVersion(int *major, int *minor); + +/** + * Loads the application profile for the current process. + * + * \param hints A zero-terminated array of (name, value) pairs, or NULL. See + * the descriptions for the individual \c PROFILE_HINT_* values for the + * type and expected values for each hint. + * + * \return A GLVNDProfile pointer, or NULL if there was some internal error. + * + * \note This function may still return a non-NULL value even if GPU offloading + * is disabled. + */ +GLVNDProfile *glvndProfileLoad(const uintptr_t *hints); + +/** + * Frees a GLVNDProfile structure. + */ +void glvndProfileFree(GLVNDProfile *profile); + +/** + * Returns an attribute for a profile. + * + * For integer attributes (or anything that's otherwise not dereferencable), + * this function will return zero or more values in the \p values parameter. + * The \p valueSizes parameter will return zero. + * + * For string, binary, or other pointer attributes, the \p valueSizes + * parameter will return the size of each value. For strings, this size + * includes the nul terminator. + * + * \param profile The profile structure. + * \param name The attribute to look up. + * \param max The maximum number of values to return. + * \param[out] valueSizes For pointer attributes, returns the size of each + * value in bytes. + * \param[out] values Returns the values of the attribute, or NULL to not return + * the values. + * + * \return The number of values that would be returned, which may be greater + * than \p max. If the attribute is not defined, then this returns -1. + */ +int glvndProfileGetAttribute(GLVNDProfile *profile, int name, int max, + size_t *valueSizes, uintptr_t *values); + +#ifdef __cplusplus +} +#endif + +#endif // APP_PROFILE_H diff --git a/src/app_profile/app_profile_config.c b/src/app_profile/app_profile_config.c new file mode 100644 index 0000000000000000000000000000000000000000..ceb97b9158d57fdd93119fb56e725e5ed44d3b2e --- /dev/null +++ b/src/app_profile/app_profile_config.c @@ -0,0 +1,843 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include + +#include "app_profile_internal.h" +#include "utils_misc.h" +#include "toml.h" + +#define PROFILE_FORMAT_VERSION_MAJOR 1 +#define PROFILE_FORMAT_VERSION_MINOR 0 + +/// The maximum length of the value in /proc/self/comm. +#define COMM_LENGTH 16 + +/** + * The directory relative to $XDG_CONFIG_HOME to look for user-specific config + * files. + */ +static const char *USER_PROFILE_DIR = "glvnd/profiles.d"; + +/** + * System-wide directories to look for config files. + * + * This list uses the same $SYSCONF/glvnd and $DATADIR/glvnd directories that + * we use for the EGL JSON files. + */ +static const char *PROFILE_DIRS[] = +{ + SYSCONFDIR "/glvnd/profiles.d", + DATADIR "/glvnd/profiles.d", +}; +static const int PROFILE_DIR_COUNT = sizeof(PROFILE_DIRS) / sizeof(PROFILE_DIRS[0]); + +/** + * The pattern to use with fnmatch(3) to identify config files. + */ +static const char *CONFIG_FILE_PATTERN = "*.toml"; + +/** + * Returns codes for the ConfigFileCallback callback. + */ +typedef enum +{ + /** + * Indicates that we should stop searching any more config files and return + * success. + */ + PARSE_SUCCESS, + + /** + * Indicates that we should continue on to the next config file or + * directory. + */ + PARSE_CONTINUE, + + /** + * Indicates that we should stop searching any more config files and return + * failure. + */ + PARSE_ERROR, +} ParseFileResult; + +typedef struct +{ + GLVNDProfile *profile; + char *configHome; + const char **configDirs; + + const char *api; + char *exe; + char comm[COMM_LENGTH]; + + char *cmdlineBuf; + const char **cmdline; + size_t cmdlineCount; + + char *userConfigDirBuf; +} ParserState; + +/** + * A callback used to process each config file in \c ScanConfigFiles. + * + * \param parser The parser state. + * \param path The full path of the file to parse. + * \param root The root table from the config file. + * \return A ParseFileResult value. ScanConfigFiles will stop scanning if + * the callback returns a value other than PARSE_CONTINUE. + */ +typedef ParseFileResult (*ConfigFileCallback) (ParserState *parser, const char *path, toml_table_t *root, void *param); + +/** + * Removes any trailing slashes from \p path. + * + * This will not reduce the path to an empty string, so it's safe to pass the + * root directory "/". + */ +static void TrimSlashes(char *path) +{ + size_t len = strlen(path); + while (len > 1 && path[len - 1] == '/') { + path[--len] = '\x00'; + } +} + +/** + * Looks up or constructs $XDG_CONFIG_HOME. + */ +static int GetUserConfigDir(char **path) +{ + const char *env; + + env = getenv("XDG_CONFIG_HOME"); + if (env != NULL) { + *path = strdup(env); + if (path == NULL) { + return -1; + } + TrimSlashes(*path); + return 0; + } + + env = getenv("HOME"); + if (env != NULL) { + if (glvnd_asprintf(path, "%s/.config", env) < 0) { + *path = NULL; + return -1; + } + TrimSlashes(*path); + return 0; + } + + *path = NULL; + return 0; +} + +/** + * Fills in the default list of directories to look for config files. + */ +static int GetDefaultConfigDirs(ParserState *parser) +{ + int i; + int index = 0; + int count = PROFILE_DIR_COUNT; + + if (parser->configHome != NULL) { + if (glvnd_asprintf(&parser->userConfigDirBuf, "%s/%s", parser->configHome, USER_PROFILE_DIR) < 0) { + parser->userConfigDirBuf = NULL; + return -1; + } + count++; + } + + // Allocate enough space for the directories plus a NULL terminator. + parser->configDirs = malloc(sizeof(const char *) * (count + 1)); + if (parser->configDirs == NULL) { + return -1; + } + + if (parser->userConfigDirBuf != NULL) { + parser->configDirs[index++] = parser->userConfigDirBuf; + } + + for (i=0; iconfigDirs[index++] = PROFILE_DIRS[i]; + } + parser->configDirs[index] = NULL; + parser->configDirs = parser->configDirs; + + return 0; +} + +/** + * Resolves a symbolic link. + * + * \param path The path to resolve. + * \return The resolved path, or NULL if it couldn't be resolved. The string is + * allocated with malloc, so the caller must free it. + */ +static char *ResolveSymlink(const char *path) +{ + ssize_t size = 256; + char *buf = NULL; + + while (size < INT_MAX / 2) { + ssize_t n; + buf = malloc(size); + if (buf == NULL) { + return NULL; + } + + n = readlink(path, buf, size - 1); + if (n < 0) { + free(buf); + return NULL; + } + + // If readlink didn't use up the whole buffer, then the buffer was big + // enough. + if (n < size - 1) { + buf[n] = '\x00'; + return buf; + } + + // Otherwise, free the buffer and we'll try again with a bigger one. + free(buf); + size *= 2; + } + + return NULL; +} + +static size_t ReadFileInto(const char *filename, char *buf, size_t bufSize) +{ + FILE *f; + size_t n; + + f = fopen(filename, "r"); + if (f == NULL) { + return 0; + } + + n = fread(buf, 1, bufSize - 1, f); + fclose(f); + + buf[n] = '\x00'; + return n; +} + +/** + * Allocates a buffer big enough to read an entire file. The returned buffer + * will have one extra nul character appended to the end. + * + * \param filename The name of the file to read + * \param[out] ret_size Returns the size of the file. This does not include the + * extra nul byte added to the buffer. + * \return The buffer, or NULL on failure. + */ +static char *ReadFile(const char *filename, size_t *ret_size) +{ + FILE *f; + static const size_t INITIAL_SIZE = 1024; + char *buf = NULL; + size_t size = 0; + size_t allocSize = INITIAL_SIZE; + + f = fopen(filename, "rb"); + if (f == NULL) { + return NULL; + } + + while (1) { + size_t n; + char *newBuf; + + // Allocate one extra byte for a nul terminator + newBuf = realloc(buf, allocSize + 1); + if (newBuf == NULL) { + free(buf); + return NULL; + } + buf = newBuf; + + n = fread(buf + size, 1, allocSize - size, f); + size += n; + if (n < allocSize - size) { + break; + } + + // Double the buffer size and keep reading + allocSize *= 2; + } + buf[size] = '\x00'; + + fclose(f); + + if (ret_size != NULL) { + *ret_size = size; + } + return buf; +} + +/** + * Splits the contents of /proc/self/cmdline into tokens. + * + * \param data The contents of /proc/self/cmdline, which must be + * nul-terminated. + * \param size The size of the buffer. + * \param[out] ret_count Returns the number of tokens. + * \return A NULL-terminated array of tokens. The caller must free the array. + */ +static const char **SplitCommandLine(const char *data, size_t size, size_t *ret_count) +{ + size_t count = 0; + const char **cmdline; + size_t i; + + // Count up the number of nul characters to find the number of tokens. + for (i=0; i 0) { + count = 0; + cmdline[count++] = data; + for (i=1; icmdline = NULL; + parser->cmdlineCount = 0; + + parser->cmdlineBuf = ReadFile("/proc/self/cmdline", &size); + if (parser->cmdlineBuf == NULL) { + return -1; + } + if (size == 0) { + free(parser->cmdlineBuf); + parser->cmdlineBuf = NULL; + return -1; + } + + // Make sure that the string ends with a nul byte. ReadFile will append an + // extra nul to the end, so we can just increment size if we need to. + if (parser->cmdlineBuf[size - 1] != '\x00') { + size++; + } + + parser->cmdline = SplitCommandLine(parser->cmdlineBuf, size, &parser->cmdlineCount); + if (parser->cmdline == NULL) { + free(parser->cmdlineBuf); + parser->cmdlineBuf = NULL; + return -1; + } + return 0; +} + +static int InitParserState(ParserState *parser, GLVNDProfile *profile, const uintptr_t *hints) +{ + const char *env; + size_t len; + + parser->profile = profile; + + if (hints != NULL) { + int i; + for (i = 0; hints[i] != 0; i++) { + if (hints[i] == GLVND_PROFILE_HINT_EXECUTABLE_NAME) { + parser->exe = strdup((const char *) hints[i + 1]); + if (parser->exe == NULL) { + return -1; + } + } + else if (hints[i] == GLVND_PROFILE_HINT_API_NAME) { + parser->api = (const char *) hints[i + 1]; + } + } + } + + ReadCommandLine(parser); + + if (parser->exe == NULL) { + parser->exe = ResolveSymlink("/proc/self/exe"); + } + len = ReadFileInto("/proc/self/comm", parser->comm, sizeof(parser->comm)); + if (len > 0) { + if (parser->comm[len - 1] == '\n') { + parser->comm[--len] = '\x00'; + } + } + + if (GetUserConfigDir(&parser->configHome) != 0) { + return -1; + } + + env = getenv("__GLVND_PROFILE_DIRS"); + if (env != NULL) { + int i; + char **dirs = SplitString(env, NULL, ":"); + if (dirs == NULL) { + return -1; + } + // Trim any trailing '/' characters on these + for (i=0; dirs[i] != NULL; i++) { + TrimSlashes(dirs[i]); + } + parser->configDirs = (const char **) dirs; + } else { + if (GetDefaultConfigDirs(parser) != 0) { + return -1; + } + } + + return 0; +} + +static void FreeParserState(ParserState *parser) +{ + free(parser->configHome); + free(parser->userConfigDirBuf); + free(parser->configDirs); + free(parser->exe); + free(parser->cmdlineBuf); + free(parser->cmdline); +} + +static int ScandirFilter(const struct dirent *ent) +{ +#if defined(HAVE_DIRENT_DTYPE) + // Ignore the entry if we know that it's not a regular file or symlink. + if (ent->d_type != DT_REG && ent->d_type != DT_LNK && ent->d_type != DT_UNKNOWN) { + return 0; + } +#endif + + // Otherwise, select any JSON files. + if (fnmatch(CONFIG_FILE_PATTERN, ent->d_name, 0) == 0) { + return 1; + } else { + return 0; + } +} + +static int CompareFilenames(const struct dirent **ent1, const struct dirent **ent2) +{ + return strcmp((*ent1)->d_name, (*ent2)->d_name); +} + +static toml_table_t *ReadTOML(ParserState *parser, const char *path) +{ + FILE *f; + toml_table_t *root; + toml_datum_t data; + int major, minor, n; + + f = fopen(path, "r"); + if (f == NULL) { + return NULL; + } + + root = toml_parse_file(f, NULL, 0); + fclose(f); + if (root == NULL) { + return NULL; + } + + // Check the version number in the config file. The major version number + // must match, and the minor version can be the current or any previous + // version. + data = toml_string_in(root, "version"); + if (!data.ok) { + // The version number is missing or the wrong type. + toml_free(root); + return NULL; + } + n = sscanf(data.u.s, "%d.%d", &major, &minor); + free(data.u.s); + if (n != 2 || major != PROFILE_FORMAT_VERSION_MAJOR + || minor > PROFILE_FORMAT_VERSION_MINOR) { + toml_free(root); + return NULL; + } + + return root; +} + +/** + * Scans the config directories for config files. + * + * For each file it finds, it will call \p callback. It will stop if when the + * callback returns a value other than \c PARSE_CONTINUE. + * + * \param parse The parser state. + * \param callback The callback function to call. If the callback returns + * any value other than \c PARSE_CONTINUE, then we'll stop scanning and + * return. + * \return Zero on success. Non-zero on error, including if the callback + * returns \c PARSE_ERROR. + */ +static int ScanConfigFiles(ParserState *parser, ConfigFileCallback callback, void *param) +{ + int i; + char *path; + ParseFileResult result = PARSE_CONTINUE; + + for (i = 0; parser->configDirs[i] != NULL && result == PARSE_CONTINUE; i++) { + int j, count; + struct dirent **entries = NULL; + + count = scandir(parser->configDirs[i], &entries, ScandirFilter, CompareFilenames); + if (count <= 0) { + continue; + } + + for (j = 0; j < count && result == PARSE_CONTINUE; j++) { + if (glvnd_asprintf(&path, "%s/%s", parser->configDirs[i], entries[j]->d_name) >= 0) { + // If the file isn't readable, then just ignore it. + toml_table_t *root = ReadTOML(parser, path); + if (root != NULL) { + result = callback(parser, path, root, param); + toml_free(root); + } + free(path); + } else { + result = PARSE_ERROR; + } + } + for (j=0; jprofile, val.u.s) != 0) { + free(val.u.s); + return -1; + } + free(val.u.s); + } + } + return 0; +} + +static ParseFileResult ParseConfigAlias(ParserState *parser, const char *path, toml_table_t *root, void *param) +{ + const char *aliasName = (const char *) param; + toml_table_t *alias; + toml_array_t *array; + + alias = toml_table_in(root, "alias"); + if (alias == NULL) { + return PARSE_CONTINUE; + } + + alias = toml_table_in(alias, aliasName); + if (alias == NULL) { + return PARSE_CONTINUE; + } + + array = toml_array_in(alias, "devices"); + if (array != NULL) { + if (ParseDeviceArray(parser, array) != 0) { + return PARSE_ERROR; + } + } + + // Note that we could continue searching the rest of the config files here. + // If we did, then we'd concatenate the device lists from each file and + // remove any duplicates. + return PARSE_SUCCESS; +} + +/** + * A helper function to match an array of strings. + * + * \param array The array to match. + * \param matchValue The value to match to the profile. + * \param useFnmatch If non-zero, then use fnmatch instead of strcmp. + * \param matchFlags The flags to pass to fnmatch. + * \return Nonzero if the string matches, zero if it does not. + */ +static int MatchStringArray(toml_array_t *array, const char *matchValue, int useFnmatch, int matchFlags) +{ + int i; + + if (toml_array_kind(array) != 'v' || toml_array_type(array) != 's') { + // This isn't an array of strings. That's invalid, so treat it as a + // mismatch. + return 0; + } + + if (matchValue == NULL || matchValue[0] == '\x00') { + // We don't have whatever value we're supposed to match, so treat this + // as a mismatch. + return 0; + } + + for (i = 0; i < toml_array_nelem(array); i++) { + toml_datum_t val = toml_string_at(array, i); + int result = 0; + + if (!val.ok) { + return 0; + } + + if (useFnmatch) { + result = (fnmatch(val.u.s, matchValue, matchFlags) == 0); + } else { + result = (strcmp(val.u.s, matchValue) == 0); + } + free(val.u.s); + + if (result != 0) { + return 1; + } + } + + return 0; +} + +static int CheckProfileMatchCmdline(ParserState *parser, toml_table_t *cmdlineNode) +{ + int64_t index = 0; + toml_datum_t val; + toml_array_t *patterns; + int flags = 0; + + if (parser->cmdlineCount == 0) { + return 0; + } + + val = toml_int_in(cmdlineNode, "index"); + if (val.ok) { + index = val.u.i; + } + if (index < 0 || index >= parser->cmdlineCount) { + return 0; + } + +#if HAVE_FNM_CASEFOLD + val = toml_bool_in(cmdlineNode, "ignore_case"); + if (val.ok) { + if (val.u.b) { + flags |= FNM_CASEFOLD; + } + } +#endif // HAVE_FNM_CASEFOLD + + patterns = toml_array_in(cmdlineNode, "patterns"); + if (patterns == NULL) { + return 0; + } + + return MatchStringArray(patterns, parser->cmdline[index], 1, flags); +} + +/** + * Checks to see if a profile matches the current process. + * + * \return 1 if the profile matches. Zero if it doesn't match. + */ +static int CheckProfileMatch(ParserState *parser, toml_table_t *profileNode) +{ + toml_table_t *matchNode = toml_table_in(profileNode, "match"); + int foundAny = 0; + toml_array_t *array; + + if (matchNode == NULL) { + return 0; + } + + array = toml_array_in(matchNode, "exe"); + if (array != NULL) { + foundAny = 1; + if (!MatchStringArray(array, parser->exe, 1, 0)) { + return 0; + } + } + + array = toml_array_in(matchNode, "comm"); + if (array != NULL) { + foundAny = 1; + if (!MatchStringArray(array, parser->comm, 1, 0)) { + return 0; + } + } + + array = toml_array_in(matchNode, "api"); + if (array != NULL) { + foundAny = 1; + if (!MatchStringArray(array, parser->api, 0, 0)) { + return 0; + } + } + + array = toml_array_in(matchNode, "cmdline"); + if (array != NULL) { + int i; + foundAny = 1; + for (i = 0; i < toml_array_nelem(array); i++) { + toml_table_t *cmdlineNode = toml_table_at(array, i); + if (cmdlineNode == NULL) { + return 0; + } + if (!CheckProfileMatchCmdline(parser, cmdlineNode)) { + return 0; + } + } + } + + if (!foundAny) { + return 0; + } + + return 1; +} + +/** + * Fills in the profile data from the config file. + * + * \return Zero on success, non-zero on error. + */ +static int GetProfileData(ParserState *parser, toml_table_t *profileNode) +{ + toml_array_t *array; + toml_datum_t val; + + array = toml_array_in(profileNode, "devices"); + if (array != NULL) { + if (ParseDeviceArray(parser, array) != 0) { + return -1; + } + } else { + // See if the profile defines an alias. + val = toml_string_in(profileNode, "alias"); + if (val.ok) { + if (ScanConfigFiles(parser, ParseConfigAlias, val.u.s) != 0) { + free(val.u.s); + return -1; + } + free(val.u.s); + } + } + + val = toml_bool_in(profileNode, "filter_devices"); + if (val.ok) { + parser->profile->filterDevices = (val.u.b != 0); + } + + return 0; +} + +static ParseFileResult ParseConfigProfile(ParserState *parser, const char *path, toml_table_t *root, void *param) +{ + toml_array_t *profileList = toml_array_in(root, "profile"); + if (profileList != NULL && toml_array_kind(profileList) == 't') { + int i; + for (i=0; i +#include +#include +#include +#include +#include +#include +#include + +static void *(*ppmalloc)(size_t) = malloc; +static void (*ppfree)(void *) = free; + +void toml_set_memutil(void *(*xxmalloc)(size_t), void (*xxfree)(void *)) { + if (xxmalloc) + ppmalloc = xxmalloc; + if (xxfree) + ppfree = xxfree; +} + +#define MALLOC(a) ppmalloc(a) +#define FREE(a) ppfree(a) + +#define malloc(x) error - forbidden - use MALLOC instead +#define free(x) error - forbidden - use FREE instead +#define calloc(x, y) error - forbidden - use CALLOC instead + +static void *CALLOC(size_t nmemb, size_t sz) { + int nb = sz * nmemb; + void *p = MALLOC(nb); + if (p) { + memset(p, 0, nb); + } + return p; +} + +// some old platforms define strdup macro -- drop it. +#undef strdup +#define strdup(x) error - forbidden - use STRDUP instead + +static char *STRDUP(const char *s) { + int len = strlen(s); + char *p = MALLOC(len + 1); + if (p) { + memcpy(p, s, len); + p[len] = 0; + } + return p; +} + +// some old platforms define strndup macro -- drop it. +#undef strndup +#define strndup(x) error - forbiden - use STRNDUP instead + +static char *STRNDUP(const char *s, size_t n) { + size_t len = strnlen(s, n); + char *p = MALLOC(len + 1); + if (p) { + memcpy(p, s, len); + p[len] = 0; + } + return p; +} + +/** + * Convert a char in utf8 into UCS, and store it in *ret. + * Return #bytes consumed or -1 on failure. + */ +int toml_utf8_to_ucs(const char *orig, int len, int64_t *ret) { + const unsigned char *buf = (const unsigned char *)orig; + unsigned i = *buf++; + int64_t v; + + /* 0x00000000 - 0x0000007F: + 0xxxxxxx + */ + if (0 == (i >> 7)) { + if (len < 1) + return -1; + v = i; + return *ret = v, 1; + } + /* 0x00000080 - 0x000007FF: + 110xxxxx 10xxxxxx + */ + if (0x6 == (i >> 5)) { + if (len < 2) + return -1; + v = i & 0x1f; + for (int j = 0; j < 1; j++) { + i = *buf++; + if (0x2 != (i >> 6)) + return -1; + v = (v << 6) | (i & 0x3f); + } + return *ret = v, (const char *)buf - orig; + } + + /* 0x00000800 - 0x0000FFFF: + 1110xxxx 10xxxxxx 10xxxxxx + */ + if (0xE == (i >> 4)) { + if (len < 3) + return -1; + v = i & 0x0F; + for (int j = 0; j < 2; j++) { + i = *buf++; + if (0x2 != (i >> 6)) + return -1; + v = (v << 6) | (i & 0x3f); + } + return *ret = v, (const char *)buf - orig; + } + + /* 0x00010000 - 0x001FFFFF: + 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + if (0x1E == (i >> 3)) { + if (len < 4) + return -1; + v = i & 0x07; + for (int j = 0; j < 3; j++) { + i = *buf++; + if (0x2 != (i >> 6)) + return -1; + v = (v << 6) | (i & 0x3f); + } + return *ret = v, (const char *)buf - orig; + } + + /* 0x00200000 - 0x03FFFFFF: + 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + if (0x3E == (i >> 2)) { + if (len < 5) + return -1; + v = i & 0x03; + for (int j = 0; j < 4; j++) { + i = *buf++; + if (0x2 != (i >> 6)) + return -1; + v = (v << 6) | (i & 0x3f); + } + return *ret = v, (const char *)buf - orig; + } + + /* 0x04000000 - 0x7FFFFFFF: + 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + if (0x7e == (i >> 1)) { + if (len < 6) + return -1; + v = i & 0x01; + for (int j = 0; j < 5; j++) { + i = *buf++; + if (0x2 != (i >> 6)) + return -1; + v = (v << 6) | (i & 0x3f); + } + return *ret = v, (const char *)buf - orig; + } + return -1; +} + +/** + * Convert a UCS char to utf8 code, and return it in buf. + * Return #bytes used in buf to encode the char, or + * -1 on error. + */ +int toml_ucs_to_utf8(int64_t code, char buf[6]) { + /* http://stackoverflow.com/questions/6240055/manually-converting-unicode-codepoints-into-utf-8-and-utf-16 + */ + /* The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well + * as 0xfffe and 0xffff (UCS noncharacters) should not appear in + * conforming UTF-8 streams. + */ + if (0xd800 <= code && code <= 0xdfff) + return -1; + if (0xfffe <= code && code <= 0xffff) + return -1; + + /* 0x00000000 - 0x0000007F: + 0xxxxxxx + */ + if (code < 0) + return -1; + if (code <= 0x7F) { + buf[0] = (unsigned char)code; + return 1; + } + + /* 0x00000080 - 0x000007FF: + 110xxxxx 10xxxxxx + */ + if (code <= 0x000007FF) { + buf[0] = (unsigned char) (0xc0 | (code >> 6)); + buf[1] = (unsigned char) (0x80 | (code & 0x3f)); + return 2; + } + + /* 0x00000800 - 0x0000FFFF: + 1110xxxx 10xxxxxx 10xxxxxx + */ + if (code <= 0x0000FFFF) { + buf[0] = (unsigned char) (0xe0 | (code >> 12)); + buf[1] = (unsigned char) (0x80 | ((code >> 6) & 0x3f)); + buf[2] = (unsigned char) (0x80 | (code & 0x3f)); + return 3; + } + + /* 0x00010000 - 0x001FFFFF: + 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + if (code <= 0x001FFFFF) { + buf[0] = (unsigned char) (0xf0 | (code >> 18)); + buf[1] = (unsigned char) (0x80 | ((code >> 12) & 0x3f)); + buf[2] = (unsigned char) (0x80 | ((code >> 6) & 0x3f)); + buf[3] = (unsigned char) (0x80 | (code & 0x3f)); + return 4; + } + + /* 0x00200000 - 0x03FFFFFF: + 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + if (code <= 0x03FFFFFF) { + buf[0] = (unsigned char) (0xf8 | (code >> 24)); + buf[1] = (unsigned char) (0x80 | ((code >> 18) & 0x3f)); + buf[2] = (unsigned char) (0x80 | ((code >> 12) & 0x3f)); + buf[3] = (unsigned char) (0x80 | ((code >> 6) & 0x3f)); + buf[4] = (unsigned char) (0x80 | (code & 0x3f)); + return 5; + } + + /* 0x04000000 - 0x7FFFFFFF: + 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + if (code <= 0x7FFFFFFF) { + buf[0] = (unsigned char) (0xfc | (code >> 30)); + buf[1] = (unsigned char) (0x80 | ((code >> 24) & 0x3f)); + buf[2] = (unsigned char) (0x80 | ((code >> 18) & 0x3f)); + buf[3] = (unsigned char) (0x80 | ((code >> 12) & 0x3f)); + buf[4] = (unsigned char) (0x80 | ((code >> 6) & 0x3f)); + buf[5] = (unsigned char) (0x80 | (code & 0x3f)); + return 6; + } + + return -1; +} + +/* + * TOML has 3 data structures: value, array, table. + * Each of them can have identification key. + */ +typedef struct toml_keyval_t toml_keyval_t; +struct toml_keyval_t { + const char *key; /* key to this value */ + const char *val; /* the raw value */ +}; + +typedef struct toml_arritem_t toml_arritem_t; +struct toml_arritem_t { + int valtype; /* for value kind: 'i'nt, 'd'ouble, 'b'ool, 's'tring, 't'ime, + 'D'ate, 'T'imestamp */ + char *val; + toml_array_t *arr; + toml_table_t *tab; +}; + +struct toml_array_t { + const char *key; /* key to this array */ + int kind; /* element kind: 'v'alue, 'a'rray, or 't'able, 'm'ixed */ + int type; /* for value kind: 'i'nt, 'd'ouble, 'b'ool, 's'tring, 't'ime, + 'D'ate, 'T'imestamp, 'm'ixed */ + + int nitem; /* number of elements */ + toml_arritem_t *item; +}; + +struct toml_table_t { + const char *key; /* key to this table */ + bool implicit; /* table was created implicitly */ + bool readonly; /* no more modification allowed */ + + /* key-values in the table */ + int nkval; + toml_keyval_t **kval; + + /* arrays in the table */ + int narr; + toml_array_t **arr; + + /* tables in the table */ + int ntab; + toml_table_t **tab; +}; + +static inline void xfree(const void *x) { + if (x) + FREE((void *)(intptr_t)x); +} + +enum tokentype_t { + INVALID, + DOT, + COMMA, + EQUAL, + LBRACE, + RBRACE, + NEWLINE, + LBRACKET, + RBRACKET, + STRING, +}; +typedef enum tokentype_t tokentype_t; + +typedef struct token_t token_t; +struct token_t { + tokentype_t tok; + int lineno; + char *ptr; /* points into context->start */ + int len; + int eof; +}; + +typedef struct context_t context_t; +struct context_t { + char *start; + char *stop; + char *errbuf; + int errbufsz; + + token_t tok; + toml_table_t *root; + toml_table_t *curtab; + + struct { + int top; + char *key[10]; + token_t tok[10]; + } tpath; +}; + +#define STRINGIFY(x) #x +#define TOSTRING(x) STRINGIFY(x) +#define FLINE __FILE__ ":" TOSTRING(__LINE__) + +static int next_token(context_t *ctx, int dotisspecial); + +/* + Error reporting. Call when an error is detected. Always return -1. +*/ +static int e_outofmemory(context_t *ctx, const char *fline) { + snprintf(ctx->errbuf, ctx->errbufsz, "ERROR: out of memory (%s)", fline); + return -1; +} + +static int e_internal(context_t *ctx, const char *fline) { + snprintf(ctx->errbuf, ctx->errbufsz, "internal error (%s)", fline); + return -1; +} + +static int e_syntax(context_t *ctx, int lineno, const char *msg) { + snprintf(ctx->errbuf, ctx->errbufsz, "line %d: %s", lineno, msg); + return -1; +} + +static int e_badkey(context_t *ctx, int lineno) { + snprintf(ctx->errbuf, ctx->errbufsz, "line %d: bad key", lineno); + return -1; +} + +static int e_keyexists(context_t *ctx, int lineno) { + snprintf(ctx->errbuf, ctx->errbufsz, "line %d: key exists", lineno); + return -1; +} + +static int e_forbid(context_t *ctx, int lineno, const char *msg) { + snprintf(ctx->errbuf, ctx->errbufsz, "line %d: %s", lineno, msg); + return -1; +} + +static void *expand(void *p, int sz, int newsz) { + void *s = MALLOC(newsz); + if (!s) + return 0; + + memcpy(s, p, sz); + FREE(p); + return s; +} + +static void **expand_ptrarr(void **p, int n) { + void **s = MALLOC((n + 1) * sizeof(void *)); + if (!s) + return 0; + + s[n] = 0; + memcpy(s, p, n * sizeof(void *)); + FREE(p); + return s; +} + +static toml_arritem_t *expand_arritem(toml_arritem_t *p, int n) { + toml_arritem_t *pp = expand(p, n * sizeof(*p), (n + 1) * sizeof(*p)); + if (!pp) + return 0; + + memset(&pp[n], 0, sizeof(pp[n])); + return pp; +} + +static char *norm_lit_str(const char *src, int srclen, int multiline, + char *errbuf, int errbufsz) { + char *dst = 0; /* will write to dst[] and return it */ + int max = 0; /* max size of dst[] */ + int off = 0; /* cur offset in dst[] */ + const char *sp = src; + const char *sq = src + srclen; + int ch; + + /* scan forward on src */ + for (;;) { + if (off >= max - 10) { /* have some slack for misc stuff */ + int newmax = max + 50; + char *x = expand(dst, max, newmax); + if (!x) { + xfree(dst); + snprintf(errbuf, errbufsz, "out of memory"); + return 0; + } + dst = x; + max = newmax; + } + + /* finished? */ + if (sp >= sq) + break; + + ch = *sp++; + /* control characters other than tab is not allowed */ + if ((0 <= ch && ch <= 0x08) || (0x0a <= ch && ch <= 0x1f) || (ch == 0x7f)) { + if (!(multiline && (ch == '\r' || ch == '\n'))) { + xfree(dst); + snprintf(errbuf, errbufsz, "invalid char U+%04x", ch); + return 0; + } + } + + // a plain copy suffice + dst[off++] = ch; + } + + dst[off++] = 0; + return dst; +} + +/* + * Convert src to raw unescaped utf-8 string. + * Returns NULL if error with errmsg in errbuf. + */ +static char *norm_basic_str(const char *src, int srclen, int multiline, + char *errbuf, int errbufsz) { + char *dst = 0; /* will write to dst[] and return it */ + int max = 0; /* max size of dst[] */ + int off = 0; /* cur offset in dst[] */ + const char *sp = src; + const char *sq = src + srclen; + int ch; + + /* scan forward on src */ + for (;;) { + if (off >= max - 10) { /* have some slack for misc stuff */ + int newmax = max + 50; + char *x = expand(dst, max, newmax); + if (!x) { + xfree(dst); + snprintf(errbuf, errbufsz, "out of memory"); + return 0; + } + dst = x; + max = newmax; + } + + /* finished? */ + if (sp >= sq) + break; + + ch = *sp++; + if (ch != '\\') { + /* these chars must be escaped: U+0000 to U+0008, U+000A to U+001F, U+007F + */ + if ((0 <= ch && ch <= 0x08) || (0x0a <= ch && ch <= 0x1f) || + (ch == 0x7f)) { + if (!(multiline && (ch == '\r' || ch == '\n'))) { + xfree(dst); + snprintf(errbuf, errbufsz, "invalid char U+%04x", ch); + return 0; + } + } + + // a plain copy suffice + dst[off++] = ch; + continue; + } + + /* ch was backslash. we expect the escape char. */ + if (sp >= sq) { + snprintf(errbuf, errbufsz, "last backslash is invalid"); + xfree(dst); + return 0; + } + + /* for multi-line, we want to kill line-ending-backslash ... */ + if (multiline) { + + // if there is only whitespace after the backslash ... + if (sp[strspn(sp, " \t\r")] == '\n') { + /* skip all the following whitespaces */ + sp += strspn(sp, " \t\r\n"); + continue; + } + } + + /* get the escaped char */ + ch = *sp++; + switch (ch) { + case 'u': + case 'U': { + int64_t ucs = 0; + int nhex = (ch == 'u' ? 4 : 8); + for (int i = 0; i < nhex; i++) { + if (sp >= sq) { + snprintf(errbuf, errbufsz, "\\%c expects %d hex chars", ch, nhex); + xfree(dst); + return 0; + } + ch = *sp++; + int v = ('0' <= ch && ch <= '9') + ? ch - '0' + : (('A' <= ch && ch <= 'F') ? ch - 'A' + 10 : -1); + if (-1 == v) { + snprintf(errbuf, errbufsz, "invalid hex chars for \\u or \\U"); + xfree(dst); + return 0; + } + ucs = ucs * 16 + v; + } + int n = toml_ucs_to_utf8(ucs, &dst[off]); + if (-1 == n) { + snprintf(errbuf, errbufsz, "illegal ucs code in \\u or \\U"); + xfree(dst); + return 0; + } + off += n; + } + continue; + + case 'b': + ch = '\b'; + break; + case 't': + ch = '\t'; + break; + case 'n': + ch = '\n'; + break; + case 'f': + ch = '\f'; + break; + case 'r': + ch = '\r'; + break; + case '"': + ch = '"'; + break; + case '\\': + ch = '\\'; + break; + default: + snprintf(errbuf, errbufsz, "illegal escape char \\%c", ch); + xfree(dst); + return 0; + } + + dst[off++] = ch; + } + + // Cap with NUL and return it. + dst[off++] = 0; + return dst; +} + +/* Normalize a key. Convert all special chars to raw unescaped utf-8 chars. */ +static char *normalize_key(context_t *ctx, token_t strtok) { + const char *sp = strtok.ptr; + const char *sq = strtok.ptr + strtok.len; + int lineno = strtok.lineno; + char *ret; + int ch = *sp; + char ebuf[80]; + + /* handle quoted string */ + if (ch == '\'' || ch == '\"') { + /* if ''' or """, take 3 chars off front and back. Else, take 1 char off. */ + int multiline = 0; + if (sp[1] == ch && sp[2] == ch) { + sp += 3, sq -= 3; + multiline = 1; + } else + sp++, sq--; + + if (ch == '\'') { + /* for single quote, take it verbatim. */ + if (!(ret = STRNDUP(sp, sq - sp))) { + e_outofmemory(ctx, FLINE); + return 0; + } + } else { + /* for double quote, we need to normalize */ + ret = norm_basic_str(sp, sq - sp, multiline, ebuf, sizeof(ebuf)); + if (!ret) { + e_syntax(ctx, lineno, ebuf); + return 0; + } + } + + /* newlines are not allowed in keys */ + if (strchr(ret, '\n')) { + xfree(ret); + e_badkey(ctx, lineno); + return 0; + } + return ret; + } + + /* for bare-key allow only this regex: [A-Za-z0-9_-]+ */ + const char *xp; + for (xp = sp; xp != sq; xp++) { + int k = *xp; + if (isalnum(k)) + continue; + if (k == '_' || k == '-') + continue; + e_badkey(ctx, lineno); + return 0; + } + + /* dup and return it */ + if (!(ret = STRNDUP(sp, sq - sp))) { + e_outofmemory(ctx, FLINE); + return 0; + } + return ret; +} + +/* + * Look up key in tab. Return 0 if not found, or + * 'v'alue, 'a'rray or 't'able depending on the element. + */ +static int check_key(toml_table_t *tab, const char *key, + toml_keyval_t **ret_val, toml_array_t **ret_arr, + toml_table_t **ret_tab) { + int i; + void *dummy; + + if (!ret_tab) + ret_tab = (toml_table_t **)&dummy; + if (!ret_arr) + ret_arr = (toml_array_t **)&dummy; + if (!ret_val) + ret_val = (toml_keyval_t **)&dummy; + + *ret_tab = 0; + *ret_arr = 0; + *ret_val = 0; + + for (i = 0; i < tab->nkval; i++) { + if (0 == strcmp(key, tab->kval[i]->key)) { + *ret_val = tab->kval[i]; + return 'v'; + } + } + for (i = 0; i < tab->narr; i++) { + if (0 == strcmp(key, tab->arr[i]->key)) { + *ret_arr = tab->arr[i]; + return 'a'; + } + } + for (i = 0; i < tab->ntab; i++) { + if (0 == strcmp(key, tab->tab[i]->key)) { + *ret_tab = tab->tab[i]; + return 't'; + } + } + return 0; +} + +static int key_kind(toml_table_t *tab, const char *key) { + return check_key(tab, key, 0, 0, 0); +} + +/* Create a keyval in the table. + */ +static toml_keyval_t *create_keyval_in_table(context_t *ctx, toml_table_t *tab, + token_t keytok) { + /* first, normalize the key to be used for lookup. + * remember to free it if we error out. + */ + char *newkey = normalize_key(ctx, keytok); + if (!newkey) + return 0; + + /* if key exists: error out. */ + toml_keyval_t *dest = 0; + if (key_kind(tab, newkey)) { + xfree(newkey); + e_keyexists(ctx, keytok.lineno); + return 0; + } + + /* make a new entry */ + int n = tab->nkval; + toml_keyval_t **base; + if (0 == (base = (toml_keyval_t **)expand_ptrarr((void **)tab->kval, n))) { + xfree(newkey); + e_outofmemory(ctx, FLINE); + return 0; + } + tab->kval = base; + + if (0 == (base[n] = (toml_keyval_t *)CALLOC(1, sizeof(*base[n])))) { + xfree(newkey); + e_outofmemory(ctx, FLINE); + return 0; + } + dest = tab->kval[tab->nkval++]; + + /* save the key in the new value struct */ + dest->key = newkey; + return dest; +} + +/* Create a table in the table. + */ +static toml_table_t *create_keytable_in_table(context_t *ctx, toml_table_t *tab, + token_t keytok) { + /* first, normalize the key to be used for lookup. + * remember to free it if we error out. + */ + char *newkey = normalize_key(ctx, keytok); + if (!newkey) + return 0; + + /* if key exists: error out */ + toml_table_t *dest = 0; + if (check_key(tab, newkey, 0, 0, &dest)) { + xfree(newkey); /* don't need this anymore */ + + /* special case: if table exists, but was created implicitly ... */ + if (dest && dest->implicit) { + /* we make it explicit now, and simply return it. */ + dest->implicit = false; + return dest; + } + e_keyexists(ctx, keytok.lineno); + return 0; + } + + /* create a new table entry */ + int n = tab->ntab; + toml_table_t **base; + if (0 == (base = (toml_table_t **)expand_ptrarr((void **)tab->tab, n))) { + xfree(newkey); + e_outofmemory(ctx, FLINE); + return 0; + } + tab->tab = base; + + if (0 == (base[n] = (toml_table_t *)CALLOC(1, sizeof(*base[n])))) { + xfree(newkey); + e_outofmemory(ctx, FLINE); + return 0; + } + dest = tab->tab[tab->ntab++]; + + /* save the key in the new table struct */ + dest->key = newkey; + return dest; +} + +/* Create an array in the table. + */ +static toml_array_t *create_keyarray_in_table(context_t *ctx, toml_table_t *tab, + token_t keytok, char kind) { + /* first, normalize the key to be used for lookup. + * remember to free it if we error out. + */ + char *newkey = normalize_key(ctx, keytok); + if (!newkey) + return 0; + + /* if key exists: error out */ + if (key_kind(tab, newkey)) { + xfree(newkey); /* don't need this anymore */ + e_keyexists(ctx, keytok.lineno); + return 0; + } + + /* make a new array entry */ + int n = tab->narr; + toml_array_t **base; + if (0 == (base = (toml_array_t **)expand_ptrarr((void **)tab->arr, n))) { + xfree(newkey); + e_outofmemory(ctx, FLINE); + return 0; + } + tab->arr = base; + + if (0 == (base[n] = (toml_array_t *)CALLOC(1, sizeof(*base[n])))) { + xfree(newkey); + e_outofmemory(ctx, FLINE); + return 0; + } + toml_array_t *dest = tab->arr[tab->narr++]; + + /* save the key in the new array struct */ + dest->key = newkey; + dest->kind = kind; + return dest; +} + +static toml_arritem_t *create_value_in_array(context_t *ctx, + toml_array_t *parent) { + const int n = parent->nitem; + toml_arritem_t *base = expand_arritem(parent->item, n); + if (!base) { + e_outofmemory(ctx, FLINE); + return 0; + } + parent->item = base; + parent->nitem++; + return &parent->item[n]; +} + +/* Create an array in an array + */ +static toml_array_t *create_array_in_array(context_t *ctx, + toml_array_t *parent) { + const int n = parent->nitem; + toml_arritem_t *base = expand_arritem(parent->item, n); + if (!base) { + e_outofmemory(ctx, FLINE); + return 0; + } + toml_array_t *ret = (toml_array_t *)CALLOC(1, sizeof(toml_array_t)); + if (!ret) { + e_outofmemory(ctx, FLINE); + return 0; + } + base[n].arr = ret; + parent->item = base; + parent->nitem++; + return ret; +} + +/* Create a table in an array + */ +static toml_table_t *create_table_in_array(context_t *ctx, + toml_array_t *parent) { + int n = parent->nitem; + toml_arritem_t *base = expand_arritem(parent->item, n); + if (!base) { + e_outofmemory(ctx, FLINE); + return 0; + } + toml_table_t *ret = (toml_table_t *)CALLOC(1, sizeof(toml_table_t)); + if (!ret) { + e_outofmemory(ctx, FLINE); + return 0; + } + base[n].tab = ret; + parent->item = base; + parent->nitem++; + return ret; +} + +static int skip_newlines(context_t *ctx, int isdotspecial) { + while (ctx->tok.tok == NEWLINE) { + if (next_token(ctx, isdotspecial)) + return -1; + if (ctx->tok.eof) + break; + } + return 0; +} + +static int parse_keyval(context_t *ctx, toml_table_t *tab); + +static inline int eat_token(context_t *ctx, tokentype_t typ, int isdotspecial, + const char *fline) { + if (ctx->tok.tok != typ) + return e_internal(ctx, fline); + + if (next_token(ctx, isdotspecial)) + return -1; + + return 0; +} + +/* We are at '{ ... }'. + * Parse the table. + */ +static int parse_inline_table(context_t *ctx, toml_table_t *tab) { + if (eat_token(ctx, LBRACE, 1, FLINE)) + return -1; + + for (;;) { + if (ctx->tok.tok == NEWLINE) + return e_syntax(ctx, ctx->tok.lineno, + "newline not allowed in inline table"); + + /* until } */ + if (ctx->tok.tok == RBRACE) + break; + + if (ctx->tok.tok != STRING) + return e_syntax(ctx, ctx->tok.lineno, "expect a string"); + + if (parse_keyval(ctx, tab)) + return -1; + + if (ctx->tok.tok == NEWLINE) + return e_syntax(ctx, ctx->tok.lineno, + "newline not allowed in inline table"); + + /* on comma, continue to scan for next keyval */ + if (ctx->tok.tok == COMMA) { + if (eat_token(ctx, COMMA, 1, FLINE)) + return -1; + continue; + } + break; + } + + if (eat_token(ctx, RBRACE, 1, FLINE)) + return -1; + + tab->readonly = 1; + + return 0; +} + +static int valtype(const char *val) { + toml_timestamp_t ts; + if (*val == '\'' || *val == '"') + return 's'; + if (0 == toml_rtob(val, 0)) + return 'b'; + if (0 == toml_rtoi(val, 0)) + return 'i'; + if (0 == toml_rtod(val, 0)) + return 'd'; + if (0 == toml_rtots(val, &ts)) { + if (ts.year && ts.hour) + return 'T'; /* timestamp */ + if (ts.year) + return 'D'; /* date */ + return 't'; /* time */ + } + return 'u'; /* unknown */ +} + +/* We are at '[...]' */ +static int parse_array(context_t *ctx, toml_array_t *arr) { + if (eat_token(ctx, LBRACKET, 0, FLINE)) + return -1; + + for (;;) { + if (skip_newlines(ctx, 0)) + return -1; + + /* until ] */ + if (ctx->tok.tok == RBRACKET) + break; + + switch (ctx->tok.tok) { + case STRING: { + /* set array kind if this will be the first entry */ + if (arr->kind == 0) + arr->kind = 'v'; + else if (arr->kind != 'v') + arr->kind = 'm'; + + char *val = ctx->tok.ptr; + int vlen = ctx->tok.len; + + /* make a new value in array */ + toml_arritem_t *newval = create_value_in_array(ctx, arr); + if (!newval) + return e_outofmemory(ctx, FLINE); + + if (!(newval->val = STRNDUP(val, vlen))) + return e_outofmemory(ctx, FLINE); + + newval->valtype = valtype(newval->val); + + /* set array type if this is the first entry */ + if (arr->nitem == 1) + arr->type = newval->valtype; + else if (arr->type != newval->valtype) + arr->type = 'm'; /* mixed */ + + if (eat_token(ctx, STRING, 0, FLINE)) + return -1; + break; + } + + case LBRACKET: { /* [ [array], [array] ... ] */ + /* set the array kind if this will be the first entry */ + if (arr->kind == 0) + arr->kind = 'a'; + else if (arr->kind != 'a') + arr->kind = 'm'; + + toml_array_t *subarr = create_array_in_array(ctx, arr); + if (!subarr) + return -1; + if (parse_array(ctx, subarr)) + return -1; + break; + } + + case LBRACE: { /* [ {table}, {table} ... ] */ + /* set the array kind if this will be the first entry */ + if (arr->kind == 0) + arr->kind = 't'; + else if (arr->kind != 't') + arr->kind = 'm'; + + toml_table_t *subtab = create_table_in_array(ctx, arr); + if (!subtab) + return -1; + if (parse_inline_table(ctx, subtab)) + return -1; + break; + } + + default: + return e_syntax(ctx, ctx->tok.lineno, "syntax error"); + } + + if (skip_newlines(ctx, 0)) + return -1; + + /* on comma, continue to scan for next element */ + if (ctx->tok.tok == COMMA) { + if (eat_token(ctx, COMMA, 0, FLINE)) + return -1; + continue; + } + break; + } + + if (eat_token(ctx, RBRACKET, 1, FLINE)) + return -1; + return 0; +} + +/* handle lines like these: + key = "value" + key = [ array ] + key = { table } +*/ +static int parse_keyval(context_t *ctx, toml_table_t *tab) { + if (tab->readonly) { + return e_forbid(ctx, ctx->tok.lineno, + "cannot insert new entry into existing table"); + } + + token_t key = ctx->tok; + if (eat_token(ctx, STRING, 1, FLINE)) + return -1; + + if (ctx->tok.tok == DOT) { + /* handle inline dotted key. + e.g. + physical.color = "orange" + physical.shape = "round" + */ + toml_table_t *subtab = 0; + { + char *subtabstr = normalize_key(ctx, key); + if (!subtabstr) + return -1; + + subtab = toml_table_in(tab, subtabstr); + xfree(subtabstr); + } + if (!subtab) { + subtab = create_keytable_in_table(ctx, tab, key); + if (!subtab) + return -1; + } + if (next_token(ctx, 1)) + return -1; + if (parse_keyval(ctx, subtab)) + return -1; + return 0; + } + + if (ctx->tok.tok != EQUAL) { + return e_syntax(ctx, ctx->tok.lineno, "missing ="); + } + + if (next_token(ctx, 0)) + return -1; + + switch (ctx->tok.tok) { + case STRING: { /* key = "value" */ + toml_keyval_t *keyval = create_keyval_in_table(ctx, tab, key); + if (!keyval) + return -1; + token_t val = ctx->tok; + + assert(keyval->val == 0); + if (!(keyval->val = STRNDUP(val.ptr, val.len))) + return e_outofmemory(ctx, FLINE); + + if (next_token(ctx, 1)) + return -1; + + return 0; + } + + case LBRACKET: { /* key = [ array ] */ + toml_array_t *arr = create_keyarray_in_table(ctx, tab, key, 0); + if (!arr) + return -1; + if (parse_array(ctx, arr)) + return -1; + return 0; + } + + case LBRACE: { /* key = { table } */ + toml_table_t *nxttab = create_keytable_in_table(ctx, tab, key); + if (!nxttab) + return -1; + if (parse_inline_table(ctx, nxttab)) + return -1; + return 0; + } + + default: + return e_syntax(ctx, ctx->tok.lineno, "syntax error"); + } + return 0; +} + +typedef struct tabpath_t tabpath_t; +struct tabpath_t { + int cnt; + token_t key[10]; +}; + +/* at [x.y.z] or [[x.y.z]] + * Scan forward and fill tabpath until it enters ] or ]] + * There will be at least one entry on return. + */ +static int fill_tabpath(context_t *ctx) { + int lineno = ctx->tok.lineno; + int i; + + /* clear tpath */ + for (i = 0; i < ctx->tpath.top; i++) { + char **p = &ctx->tpath.key[i]; + xfree(*p); + *p = 0; + } + ctx->tpath.top = 0; + + for (;;) { + if (ctx->tpath.top >= 10) + return e_syntax(ctx, lineno, + "table path is too deep; max allowed is 10."); + + if (ctx->tok.tok != STRING) + return e_syntax(ctx, lineno, "invalid or missing key"); + + char *key = normalize_key(ctx, ctx->tok); + if (!key) + return -1; + ctx->tpath.tok[ctx->tpath.top] = ctx->tok; + ctx->tpath.key[ctx->tpath.top] = key; + ctx->tpath.top++; + + if (next_token(ctx, 1)) + return -1; + + if (ctx->tok.tok == RBRACKET) + break; + + if (ctx->tok.tok != DOT) + return e_syntax(ctx, lineno, "invalid key"); + + if (next_token(ctx, 1)) + return -1; + } + + if (ctx->tpath.top <= 0) + return e_syntax(ctx, lineno, "empty table selector"); + + return 0; +} + +/* Walk tabpath from the root, and create new tables on the way. + * Sets ctx->curtab to the final table. + */ +static int walk_tabpath(context_t *ctx) { + /* start from root */ + toml_table_t *curtab = ctx->root; + + for (int i = 0; i < ctx->tpath.top; i++) { + const char *key = ctx->tpath.key[i]; + + toml_keyval_t *nextval = 0; + toml_array_t *nextarr = 0; + toml_table_t *nexttab = 0; + switch (check_key(curtab, key, &nextval, &nextarr, &nexttab)) { + case 't': + /* found a table. nexttab is where we will go next. */ + break; + + case 'a': + /* found an array. nexttab is the last table in the array. */ + if (nextarr->kind != 't') + return e_internal(ctx, FLINE); + + if (nextarr->nitem == 0) + return e_internal(ctx, FLINE); + + nexttab = nextarr->item[nextarr->nitem - 1].tab; + break; + + case 'v': + return e_keyexists(ctx, ctx->tpath.tok[i].lineno); + + default: { /* Not found. Let's create an implicit table. */ + int n = curtab->ntab; + toml_table_t **base = + (toml_table_t **)expand_ptrarr((void **)curtab->tab, n); + if (0 == base) + return e_outofmemory(ctx, FLINE); + + curtab->tab = base; + + if (0 == (base[n] = (toml_table_t *)CALLOC(1, sizeof(*base[n])))) + return e_outofmemory(ctx, FLINE); + + if (0 == (base[n]->key = STRDUP(key))) + return e_outofmemory(ctx, FLINE); + + nexttab = curtab->tab[curtab->ntab++]; + + /* tabs created by walk_tabpath are considered implicit */ + nexttab->implicit = true; + } break; + } + + /* switch to next tab */ + curtab = nexttab; + } + + /* save it */ + ctx->curtab = curtab; + + return 0; +} + +/* handle lines like [x.y.z] or [[x.y.z]] */ +static int parse_select(context_t *ctx) { + assert(ctx->tok.tok == LBRACKET); + + /* true if [[ */ + int llb = (ctx->tok.ptr + 1 < ctx->stop && ctx->tok.ptr[1] == '['); + /* need to detect '[[' on our own because next_token() will skip whitespace, + and '[ [' would be taken as '[[', which is wrong. */ + + /* eat [ or [[ */ + if (eat_token(ctx, LBRACKET, 1, FLINE)) + return -1; + if (llb) { + assert(ctx->tok.tok == LBRACKET); + if (eat_token(ctx, LBRACKET, 1, FLINE)) + return -1; + } + + if (fill_tabpath(ctx)) + return -1; + + /* For [x.y.z] or [[x.y.z]], remove z from tpath. + */ + token_t z = ctx->tpath.tok[ctx->tpath.top - 1]; + xfree(ctx->tpath.key[ctx->tpath.top - 1]); + ctx->tpath.top--; + + /* set up ctx->curtab */ + if (walk_tabpath(ctx)) + return -1; + + if (!llb) { + /* [x.y.z] -> create z = {} in x.y */ + toml_table_t *curtab = create_keytable_in_table(ctx, ctx->curtab, z); + if (!curtab) + return -1; + ctx->curtab = curtab; + } else { + /* [[x.y.z]] -> create z = [] in x.y */ + toml_array_t *arr = 0; + { + char *zstr = normalize_key(ctx, z); + if (!zstr) + return -1; + arr = toml_array_in(ctx->curtab, zstr); + xfree(zstr); + } + if (!arr) { + arr = create_keyarray_in_table(ctx, ctx->curtab, z, 't'); + if (!arr) + return -1; + } + if (arr->kind != 't') + return e_syntax(ctx, z.lineno, "array mismatch"); + + /* add to z[] */ + toml_table_t *dest; + { + toml_table_t *t = create_table_in_array(ctx, arr); + if (!t) + return -1; + + if (0 == (t->key = STRDUP("__anon__"))) + return e_outofmemory(ctx, FLINE); + + dest = t; + } + + ctx->curtab = dest; + } + + if (ctx->tok.tok != RBRACKET) { + return e_syntax(ctx, ctx->tok.lineno, "expects ]"); + } + if (llb) { + if (!(ctx->tok.ptr + 1 < ctx->stop && ctx->tok.ptr[1] == ']')) { + return e_syntax(ctx, ctx->tok.lineno, "expects ]]"); + } + if (eat_token(ctx, RBRACKET, 1, FLINE)) + return -1; + } + + if (eat_token(ctx, RBRACKET, 1, FLINE)) + return -1; + + if (ctx->tok.tok != NEWLINE) + return e_syntax(ctx, ctx->tok.lineno, "extra chars after ] or ]]"); + + return 0; +} + +toml_table_t *toml_parse(char *conf, char *errbuf, int errbufsz) { + context_t ctx; + + // clear errbuf + if (errbufsz <= 0) + errbufsz = 0; + if (errbufsz > 0) + errbuf[0] = 0; + + // init context + memset(&ctx, 0, sizeof(ctx)); + ctx.start = conf; + ctx.stop = ctx.start + strlen(conf); + ctx.errbuf = errbuf; + ctx.errbufsz = errbufsz; + + // start with an artificial newline of length 0 + ctx.tok.tok = NEWLINE; + ctx.tok.lineno = 1; + ctx.tok.ptr = conf; + ctx.tok.len = 0; + + // make a root table + if (0 == (ctx.root = CALLOC(1, sizeof(*ctx.root)))) { + e_outofmemory(&ctx, FLINE); + // Do not goto fail, root table not set up yet + return 0; + } + + // set root as default table + ctx.curtab = ctx.root; + + /* Scan forward until EOF */ + for (token_t tok = ctx.tok; !tok.eof; tok = ctx.tok) { + switch (tok.tok) { + + case NEWLINE: + if (next_token(&ctx, 1)) + goto fail; + break; + + case STRING: + if (parse_keyval(&ctx, ctx.curtab)) + goto fail; + + if (ctx.tok.tok != NEWLINE) { + e_syntax(&ctx, ctx.tok.lineno, "extra chars after value"); + goto fail; + } + + if (eat_token(&ctx, NEWLINE, 1, FLINE)) + goto fail; + break; + + case LBRACKET: /* [ x.y.z ] or [[ x.y.z ]] */ + if (parse_select(&ctx)) + goto fail; + break; + + default: + e_syntax(&ctx, tok.lineno, "syntax error"); + goto fail; + } + } + + /* success */ + for (int i = 0; i < ctx.tpath.top; i++) + xfree(ctx.tpath.key[i]); + return ctx.root; + +fail: + // Something bad has happened. Free resources and return error. + for (int i = 0; i < ctx.tpath.top; i++) + xfree(ctx.tpath.key[i]); + toml_free(ctx.root); + return 0; +} + +toml_table_t *toml_parse_file(FILE *fp, char *errbuf, int errbufsz) { + int bufsz = 0; + char *buf = 0; + int off = 0; + + /* read from fp into buf */ + while (!feof(fp)) { + + if (off == bufsz) { + int xsz = bufsz + 1000; + char *x = expand(buf, bufsz, xsz); + if (!x) { + snprintf(errbuf, errbufsz, "out of memory"); + xfree(buf); + return 0; + } + buf = x; + bufsz = xsz; + } + + errno = 0; + int n = fread(buf + off, 1, bufsz - off, fp); + if (ferror(fp)) { + snprintf(errbuf, errbufsz, "%s", + errno ? strerror(errno) : "Error reading file"); + xfree(buf); + return 0; + } + off += n; + } + + /* tag on a NUL to cap the string */ + if (off == bufsz) { + int xsz = bufsz + 1; + char *x = expand(buf, bufsz, xsz); + if (!x) { + snprintf(errbuf, errbufsz, "out of memory"); + xfree(buf); + return 0; + } + buf = x; + bufsz = xsz; + } + buf[off] = 0; + + /* parse it, cleanup and finish */ + toml_table_t *ret = toml_parse(buf, errbuf, errbufsz); + xfree(buf); + return ret; +} + +static void xfree_kval(toml_keyval_t *p) { + if (!p) + return; + xfree(p->key); + xfree(p->val); + xfree(p); +} + +static void xfree_tab(toml_table_t *p); + +static void xfree_arr(toml_array_t *p) { + if (!p) + return; + + xfree(p->key); + const int n = p->nitem; + for (int i = 0; i < n; i++) { + toml_arritem_t *a = &p->item[i]; + if (a->val) + xfree(a->val); + else if (a->arr) + xfree_arr(a->arr); + else if (a->tab) + xfree_tab(a->tab); + } + xfree(p->item); + xfree(p); +} + +static void xfree_tab(toml_table_t *p) { + int i; + + if (!p) + return; + + xfree(p->key); + + for (i = 0; i < p->nkval; i++) + xfree_kval(p->kval[i]); + xfree(p->kval); + + for (i = 0; i < p->narr; i++) + xfree_arr(p->arr[i]); + xfree(p->arr); + + for (i = 0; i < p->ntab; i++) + xfree_tab(p->tab[i]); + xfree(p->tab); + + xfree(p); +} + +void toml_free(toml_table_t *tab) { xfree_tab(tab); } + +static void set_token(context_t *ctx, tokentype_t tok, int lineno, char *ptr, + int len) { + token_t t; + t.tok = tok; + t.lineno = lineno; + t.ptr = ptr; + t.len = len; + t.eof = 0; + ctx->tok = t; +} + +static void set_eof(context_t *ctx, int lineno) { + set_token(ctx, NEWLINE, lineno, ctx->stop, 0); + ctx->tok.eof = 1; +} + +/* Scan p for n digits compositing entirely of [0-9] */ +static int scan_digits(const char *p, int n) { + int ret = 0; + for (; n > 0 && isdigit(*p); n--, p++) { + ret = 10 * ret + (*p - '0'); + } + return n ? -1 : ret; +} + +static int scan_date(const char *p, int *YY, int *MM, int *DD) { + int year, month, day; + year = scan_digits(p, 4); + month = (year >= 0 && p[4] == '-') ? scan_digits(p + 5, 2) : -1; + day = (month >= 0 && p[7] == '-') ? scan_digits(p + 8, 2) : -1; + if (YY) + *YY = year; + if (MM) + *MM = month; + if (DD) + *DD = day; + return (year >= 0 && month >= 0 && day >= 0) ? 0 : -1; +} + +static int scan_time(const char *p, int *hh, int *mm, int *ss) { + int hour, minute, second; + hour = scan_digits(p, 2); + minute = (hour >= 0 && p[2] == ':') ? scan_digits(p + 3, 2) : -1; + second = (minute >= 0 && p[5] == ':') ? scan_digits(p + 6, 2) : -1; + if (hh) + *hh = hour; + if (mm) + *mm = minute; + if (ss) + *ss = second; + return (hour >= 0 && minute >= 0 && second >= 0) ? 0 : -1; +} + +static int scan_string(context_t *ctx, char *p, int lineno, int dotisspecial) { + char *orig = p; + if (0 == strncmp(p, "'''", 3)) { + char *q = p + 3; + + while (1) { + q = strstr(q, "'''"); + if (0 == q) { + return e_syntax(ctx, lineno, "unterminated triple-s-quote"); + } + while (q[3] == '\'') + q++; + break; + } + + set_token(ctx, STRING, lineno, orig, q + 3 - orig); + return 0; + } + + if (0 == strncmp(p, "\"\"\"", 3)) { + char *q = p + 3; + + while (1) { + q = strstr(q, "\"\"\""); + if (0 == q) { + return e_syntax(ctx, lineno, "unterminated triple-d-quote"); + } + if (q[-1] == '\\') { + q++; + continue; + } + while (q[3] == '\"') + q++; + break; + } + + // the string is [p+3, q-1] + + int hexreq = 0; /* #hex required */ + int escape = 0; + for (p += 3; p < q; p++) { + if (escape) { + escape = 0; + if (strchr("btnfr\"\\", *p)) + continue; + if (*p == 'u') { + hexreq = 4; + continue; + } + if (*p == 'U') { + hexreq = 8; + continue; + } + if (p[strspn(p, " \t\r")] == '\n') + continue; /* allow for line ending backslash */ + return e_syntax(ctx, lineno, "bad escape char"); + } + if (hexreq) { + hexreq--; + if (strchr("0123456789ABCDEF", *p)) + continue; + return e_syntax(ctx, lineno, "expect hex char"); + } + if (*p == '\\') { + escape = 1; + continue; + } + } + if (escape) + return e_syntax(ctx, lineno, "expect an escape char"); + if (hexreq) + return e_syntax(ctx, lineno, "expected more hex char"); + + set_token(ctx, STRING, lineno, orig, q + 3 - orig); + return 0; + } + + if ('\'' == *p) { + for (p++; *p && *p != '\n' && *p != '\''; p++) + ; + if (*p != '\'') { + return e_syntax(ctx, lineno, "unterminated s-quote"); + } + + set_token(ctx, STRING, lineno, orig, p + 1 - orig); + return 0; + } + + if ('\"' == *p) { + int hexreq = 0; /* #hex required */ + int escape = 0; + for (p++; *p; p++) { + if (escape) { + escape = 0; + if (strchr("btnfr\"\\", *p)) + continue; + if (*p == 'u') { + hexreq = 4; + continue; + } + if (*p == 'U') { + hexreq = 8; + continue; + } + return e_syntax(ctx, lineno, "bad escape char"); + } + if (hexreq) { + hexreq--; + if (strchr("0123456789ABCDEF", *p)) + continue; + return e_syntax(ctx, lineno, "expect hex char"); + } + if (*p == '\\') { + escape = 1; + continue; + } + if (*p == '\'') { + if (p[1] == '\'' && p[2] == '\'') { + return e_syntax(ctx, lineno, "triple-s-quote inside string lit"); + } + continue; + } + if (*p == '\n') + break; + if (*p == '"') + break; + } + if (*p != '"') { + return e_syntax(ctx, lineno, "unterminated quote"); + } + + set_token(ctx, STRING, lineno, orig, p + 1 - orig); + return 0; + } + + /* check for timestamp without quotes */ + if (0 == scan_date(p, 0, 0, 0) || 0 == scan_time(p, 0, 0, 0)) { + // forward thru the timestamp + p += strspn(p, "0123456789.:+-T Z"); + // squeeze out any spaces at end of string + for (; p[-1] == ' '; p--) + ; + // tokenize + set_token(ctx, STRING, lineno, orig, p - orig); + return 0; + } + + /* literals */ + for (; *p && *p != '\n'; p++) { + int ch = *p; + if (ch == '.' && dotisspecial) + break; + if ('A' <= ch && ch <= 'Z') + continue; + if ('a' <= ch && ch <= 'z') + continue; + if (strchr("0123456789+-_.", ch)) + continue; + break; + } + + set_token(ctx, STRING, lineno, orig, p - orig); + return 0; +} + +static int next_token(context_t *ctx, int dotisspecial) { + int lineno = ctx->tok.lineno; + char *p = ctx->tok.ptr; + int i; + + /* eat this tok */ + for (i = 0; i < ctx->tok.len; i++) { + if (*p++ == '\n') + lineno++; + } + + /* make next tok */ + while (p < ctx->stop) { + /* skip comment. stop just before the \n. */ + if (*p == '#') { + for (p++; p < ctx->stop && *p != '\n'; p++) + ; + continue; + } + + if (dotisspecial && *p == '.') { + set_token(ctx, DOT, lineno, p, 1); + return 0; + } + + switch (*p) { + case ',': + set_token(ctx, COMMA, lineno, p, 1); + return 0; + case '=': + set_token(ctx, EQUAL, lineno, p, 1); + return 0; + case '{': + set_token(ctx, LBRACE, lineno, p, 1); + return 0; + case '}': + set_token(ctx, RBRACE, lineno, p, 1); + return 0; + case '[': + set_token(ctx, LBRACKET, lineno, p, 1); + return 0; + case ']': + set_token(ctx, RBRACKET, lineno, p, 1); + return 0; + case '\n': + set_token(ctx, NEWLINE, lineno, p, 1); + return 0; + case '\r': + case ' ': + case '\t': + /* ignore white spaces */ + p++; + continue; + } + + return scan_string(ctx, p, lineno, dotisspecial); + } + + set_eof(ctx, lineno); + return 0; +} + +const char *toml_key_in(const toml_table_t *tab, int keyidx) { + if (keyidx < tab->nkval) + return tab->kval[keyidx]->key; + + keyidx -= tab->nkval; + if (keyidx < tab->narr) + return tab->arr[keyidx]->key; + + keyidx -= tab->narr; + if (keyidx < tab->ntab) + return tab->tab[keyidx]->key; + + return 0; +} + +int toml_key_exists(const toml_table_t *tab, const char *key) { + int i; + for (i = 0; i < tab->nkval; i++) { + if (0 == strcmp(key, tab->kval[i]->key)) + return 1; + } + for (i = 0; i < tab->narr; i++) { + if (0 == strcmp(key, tab->arr[i]->key)) + return 1; + } + for (i = 0; i < tab->ntab; i++) { + if (0 == strcmp(key, tab->tab[i]->key)) + return 1; + } + return 0; +} + +toml_raw_t toml_raw_in(const toml_table_t *tab, const char *key) { + int i; + for (i = 0; i < tab->nkval; i++) { + if (0 == strcmp(key, tab->kval[i]->key)) + return tab->kval[i]->val; + } + return 0; +} + +toml_array_t *toml_array_in(const toml_table_t *tab, const char *key) { + int i; + for (i = 0; i < tab->narr; i++) { + if (0 == strcmp(key, tab->arr[i]->key)) + return tab->arr[i]; + } + return 0; +} + +toml_table_t *toml_table_in(const toml_table_t *tab, const char *key) { + int i; + for (i = 0; i < tab->ntab; i++) { + if (0 == strcmp(key, tab->tab[i]->key)) + return tab->tab[i]; + } + return 0; +} + +toml_raw_t toml_raw_at(const toml_array_t *arr, int idx) { + return (0 <= idx && idx < arr->nitem) ? arr->item[idx].val : 0; +} + +char toml_array_kind(const toml_array_t *arr) { return arr->kind; } + +char toml_array_type(const toml_array_t *arr) { + if (arr->kind != 'v') + return 0; + + if (arr->nitem == 0) + return 0; + + return arr->type; +} + +int toml_array_nelem(const toml_array_t *arr) { return arr->nitem; } + +const char *toml_array_key(const toml_array_t *arr) { + return arr ? arr->key : (const char *)NULL; +} + +int toml_table_nkval(const toml_table_t *tab) { return tab->nkval; } + +int toml_table_narr(const toml_table_t *tab) { return tab->narr; } + +int toml_table_ntab(const toml_table_t *tab) { return tab->ntab; } + +const char *toml_table_key(const toml_table_t *tab) { + return tab ? tab->key : (const char *)NULL; +} + +toml_array_t *toml_array_at(const toml_array_t *arr, int idx) { + return (0 <= idx && idx < arr->nitem) ? arr->item[idx].arr : 0; +} + +toml_table_t *toml_table_at(const toml_array_t *arr, int idx) { + return (0 <= idx && idx < arr->nitem) ? arr->item[idx].tab : 0; +} + +static int parse_millisec(const char *p, const char **endp); + +int toml_rtots(toml_raw_t src_, toml_timestamp_t *ret) { + if (!src_) + return -1; + + const char *p = src_; + int must_parse_time = 0; + + memset(ret, 0, sizeof(*ret)); + + int *year = &ret->__buffer.year; + int *month = &ret->__buffer.month; + int *day = &ret->__buffer.day; + int *hour = &ret->__buffer.hour; + int *minute = &ret->__buffer.minute; + int *second = &ret->__buffer.second; + int *millisec = &ret->__buffer.millisec; + + /* parse date YYYY-MM-DD */ + if (0 == scan_date(p, year, month, day)) { + ret->year = year; + ret->month = month; + ret->day = day; + + p += 10; + if (*p) { + // parse the T or space separator + if (*p != 'T' && *p != ' ') + return -1; + must_parse_time = 1; + p++; + } + } + + /* parse time HH:MM:SS */ + if (0 == scan_time(p, hour, minute, second)) { + ret->hour = hour; + ret->minute = minute; + ret->second = second; + + /* optionally, parse millisec */ + p += 8; + if (*p == '.') { + p++; /* skip '.' */ + const char *qq; + *millisec = parse_millisec(p, &qq); + ret->millisec = millisec; + p = qq; + } + + if (*p) { + /* parse and copy Z */ + char *z = ret->__buffer.z; + ret->z = z; + if (*p == 'Z' || *p == 'z') { + *z++ = 'Z'; + p++; + *z = 0; + + } else if (*p == '+' || *p == '-') { + *z++ = *p++; + + if (!(isdigit(p[0]) && isdigit(p[1]))) + return -1; + *z++ = *p++; + *z++ = *p++; + + if (*p == ':') { + *z++ = *p++; + + if (!(isdigit(p[0]) && isdigit(p[1]))) + return -1; + *z++ = *p++; + *z++ = *p++; + } + + *z = 0; + } + } + } + if (*p != 0) + return -1; + + if (must_parse_time && !ret->hour) + return -1; + + return 0; +} + +/* Raw to boolean */ +int toml_rtob(toml_raw_t src, int *ret_) { + if (!src) + return -1; + int dummy; + int *ret = ret_ ? ret_ : &dummy; + + if (0 == strcmp(src, "true")) { + *ret = 1; + return 0; + } + if (0 == strcmp(src, "false")) { + *ret = 0; + return 0; + } + return -1; +} + +/* Raw to integer */ +int toml_rtoi(toml_raw_t src, int64_t *ret_) { + if (!src) + return -1; + + char buf[100]; + char *p = buf; + char *q = p + sizeof(buf); + const char *s = src; + int base = 0; + int64_t dummy; + int64_t *ret = ret_ ? ret_ : &dummy; + + /* allow +/- */ + if (s[0] == '+' || s[0] == '-') + *p++ = *s++; + + /* disallow +_100 */ + if (s[0] == '_') + return -1; + + /* if 0* ... */ + if ('0' == s[0]) { + switch (s[1]) { + case 'x': + base = 16; + s += 2; + break; + case 'o': + base = 8; + s += 2; + break; + case 'b': + base = 2; + s += 2; + break; + case '\0': + return *ret = 0, 0; + default: + /* ensure no other digits after it */ + if (s[1]) + return -1; + } + } + + /* just strip underscores and pass to strtoll */ + while (*s && p < q) { + int ch = *s++; + if (ch == '_') { + // disallow '__' + if (s[0] == '_') + return -1; + // numbers cannot end with '_' + if (s[0] == '\0') + return -1; + continue; /* skip _ */ + } + *p++ = ch; + } + + // if not at end-of-string or we ran out of buffer ... + if (*s || p == q) + return -1; + + /* cap with NUL */ + *p = 0; + + /* Run strtoll on buf to get the integer */ + char *endp; + errno = 0; + *ret = strtoll(buf, &endp, base); + return (errno || *endp) ? -1 : 0; +} + +int toml_rtod_ex(toml_raw_t src, double *ret_, char *buf, int buflen) { + if (!src) + return -1; + + char *p = buf; + char *q = p + buflen; + const char *s = src; + double dummy; + double *ret = ret_ ? ret_ : &dummy; + + /* allow +/- */ + if (s[0] == '+' || s[0] == '-') + *p++ = *s++; + + /* disallow +_1.00 */ + if (s[0] == '_') + return -1; + + /* decimal point, if used, must be surrounded by at least one digit on each + * side */ + { + char *dot = strchr(s, '.'); + if (dot) { + if (dot == s || !isdigit(dot[-1]) || !isdigit(dot[1])) + return -1; + } + } + + /* zero must be followed by . or 'e', or NUL */ + if (s[0] == '0' && s[1] && !strchr("eE.", s[1])) + return -1; + + /* just strip underscores and pass to strtod */ + while (*s && p < q) { + int ch = *s++; + if (ch == '_') { + // disallow '__' + if (s[0] == '_') + return -1; + // disallow last char '_' + if (s[0] == 0) + return -1; + continue; /* skip _ */ + } + *p++ = ch; + } + if (*s || p == q) + return -1; /* reached end of string or buffer is full? */ + + /* cap with NUL */ + *p = 0; + + /* Run strtod on buf to get the value */ + char *endp; + errno = 0; + *ret = strtod(buf, &endp); + return (errno || *endp) ? -1 : 0; +} + +int toml_rtod(toml_raw_t src, double *ret_) { + char buf[100]; + return toml_rtod_ex(src, ret_, buf, sizeof(buf)); +} + +int toml_rtos(toml_raw_t src, char **ret) { + int multiline = 0; + const char *sp; + const char *sq; + + *ret = 0; + if (!src) + return -1; + + int qchar = src[0]; + int srclen = strlen(src); + if (!(qchar == '\'' || qchar == '"')) { + return -1; + } + + // triple quotes? + if (qchar == src[1] && qchar == src[2]) { + multiline = 1; + sp = src + 3; + sq = src + srclen - 3; + /* last 3 chars in src must be qchar */ + if (!(sp <= sq && sq[0] == qchar && sq[1] == qchar && sq[2] == qchar)) + return -1; + + /* skip new line immediate after qchar */ + if (sp[0] == '\n') + sp++; + else if (sp[0] == '\r' && sp[1] == '\n') + sp += 2; + + } else { + sp = src + 1; + sq = src + srclen - 1; + /* last char in src must be qchar */ + if (!(sp <= sq && *sq == qchar)) + return -1; + } + + if (qchar == '\'') { + *ret = norm_lit_str(sp, sq - sp, multiline, 0, 0); + } else { + *ret = norm_basic_str(sp, sq - sp, multiline, 0, 0); + } + + return *ret ? 0 : -1; +} + +toml_datum_t toml_string_at(const toml_array_t *arr, int idx) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtos(toml_raw_at(arr, idx), &ret.u.s)); + return ret; +} + +toml_datum_t toml_bool_at(const toml_array_t *arr, int idx) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtob(toml_raw_at(arr, idx), &ret.u.b)); + return ret; +} + +toml_datum_t toml_int_at(const toml_array_t *arr, int idx) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtoi(toml_raw_at(arr, idx), &ret.u.i)); + return ret; +} + +toml_datum_t toml_double_at(const toml_array_t *arr, int idx) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtod(toml_raw_at(arr, idx), &ret.u.d)); + return ret; +} + +toml_datum_t toml_timestamp_at(const toml_array_t *arr, int idx) { + toml_timestamp_t ts; + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtots(toml_raw_at(arr, idx), &ts)); + if (ret.ok) { + ret.ok = !!(ret.u.ts = MALLOC(sizeof(*ret.u.ts))); + if (ret.ok) { + *ret.u.ts = ts; + if (ret.u.ts->year) + ret.u.ts->year = &ret.u.ts->__buffer.year; + if (ret.u.ts->month) + ret.u.ts->month = &ret.u.ts->__buffer.month; + if (ret.u.ts->day) + ret.u.ts->day = &ret.u.ts->__buffer.day; + if (ret.u.ts->hour) + ret.u.ts->hour = &ret.u.ts->__buffer.hour; + if (ret.u.ts->minute) + ret.u.ts->minute = &ret.u.ts->__buffer.minute; + if (ret.u.ts->second) + ret.u.ts->second = &ret.u.ts->__buffer.second; + if (ret.u.ts->millisec) + ret.u.ts->millisec = &ret.u.ts->__buffer.millisec; + if (ret.u.ts->z) + ret.u.ts->z = ret.u.ts->__buffer.z; + } + } + return ret; +} + +toml_datum_t toml_string_in(const toml_table_t *arr, const char *key) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + toml_raw_t raw = toml_raw_in(arr, key); + if (raw) { + ret.ok = (0 == toml_rtos(raw, &ret.u.s)); + } + return ret; +} + +toml_datum_t toml_bool_in(const toml_table_t *arr, const char *key) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtob(toml_raw_in(arr, key), &ret.u.b)); + return ret; +} + +toml_datum_t toml_int_in(const toml_table_t *arr, const char *key) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtoi(toml_raw_in(arr, key), &ret.u.i)); + return ret; +} + +toml_datum_t toml_double_in(const toml_table_t *arr, const char *key) { + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtod(toml_raw_in(arr, key), &ret.u.d)); + return ret; +} + +toml_datum_t toml_timestamp_in(const toml_table_t *arr, const char *key) { + toml_timestamp_t ts; + toml_datum_t ret; + memset(&ret, 0, sizeof(ret)); + ret.ok = (0 == toml_rtots(toml_raw_in(arr, key), &ts)); + if (ret.ok) { + ret.ok = !!(ret.u.ts = MALLOC(sizeof(*ret.u.ts))); + if (ret.ok) { + *ret.u.ts = ts; + if (ret.u.ts->year) + ret.u.ts->year = &ret.u.ts->__buffer.year; + if (ret.u.ts->month) + ret.u.ts->month = &ret.u.ts->__buffer.month; + if (ret.u.ts->day) + ret.u.ts->day = &ret.u.ts->__buffer.day; + if (ret.u.ts->hour) + ret.u.ts->hour = &ret.u.ts->__buffer.hour; + if (ret.u.ts->minute) + ret.u.ts->minute = &ret.u.ts->__buffer.minute; + if (ret.u.ts->second) + ret.u.ts->second = &ret.u.ts->__buffer.second; + if (ret.u.ts->millisec) + ret.u.ts->millisec = &ret.u.ts->__buffer.millisec; + if (ret.u.ts->z) + ret.u.ts->z = ret.u.ts->__buffer.z; + } + } + return ret; +} + +static int parse_millisec(const char *p, const char **endp) { + int ret = 0; + int unit = 100; /* unit in millisec */ + for (; '0' <= *p && *p <= '9'; p++, unit /= 10) { + ret += (*p - '0') * unit; + } + *endp = p; + return ret; +} diff --git a/src/app_profile/toml.h b/src/app_profile/toml.h new file mode 100644 index 0000000000000000000000000000000000000000..82a81cec4a301295741d6c49a2140ad92c77e0bc --- /dev/null +++ b/src/app_profile/toml.h @@ -0,0 +1,171 @@ +/* + MIT License + + Copyright (c) CK Tan + https://github.com/cktan/tomlc99 + + 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, sublicense, 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 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. +*/ +#ifndef TOML_H +#define TOML_H + +#include +#include + +#ifdef __cplusplus +#define TOML_EXTERN extern "C" +#else +#define TOML_EXTERN extern +#endif + +typedef struct toml_timestamp_t toml_timestamp_t; +typedef struct toml_table_t toml_table_t; +typedef struct toml_array_t toml_array_t; +typedef struct toml_datum_t toml_datum_t; + +/* Parse a file. Return a table on success, or 0 otherwise. + * Caller must toml_free(the-return-value) after use. + */ +TOML_EXTERN toml_table_t *toml_parse_file(FILE *fp, char *errbuf, int errbufsz); + +/* Parse a string containing the full config. + * Return a table on success, or 0 otherwise. + * Caller must toml_free(the-return-value) after use. + */ +TOML_EXTERN toml_table_t *toml_parse(char *conf, /* NUL terminated, please. */ + char *errbuf, int errbufsz); + +/* Free the table returned by toml_parse() or toml_parse_file(). Once + * this function is called, any handles accessed through this tab + * directly or indirectly are no longer valid. + */ +TOML_EXTERN void toml_free(toml_table_t *tab); + +/* Timestamp types. The year, month, day, hour, minute, second, z + * fields may be NULL if they are not relevant. e.g. In a DATE + * type, the hour, minute, second and z fields will be NULLs. + */ +struct toml_timestamp_t { + struct { /* internal. do not use. */ + int year, month, day; + int hour, minute, second, millisec; + char z[10]; + } __buffer; + int *year, *month, *day; + int *hour, *minute, *second, *millisec; + char *z; +}; + +/*----------------------------------------------------------------- + * Enhanced access methods + */ +struct toml_datum_t { + int ok; + union { + toml_timestamp_t *ts; /* ts must be freed after use */ + char *s; /* string value. s must be freed after use */ + int b; /* bool value */ + int64_t i; /* int value */ + double d; /* double value */ + } u; +}; + +/* on arrays: */ +/* ... retrieve size of array. */ +TOML_EXTERN int toml_array_nelem(const toml_array_t *arr); +/* ... retrieve values using index. */ +TOML_EXTERN toml_datum_t toml_string_at(const toml_array_t *arr, int idx); +TOML_EXTERN toml_datum_t toml_bool_at(const toml_array_t *arr, int idx); +TOML_EXTERN toml_datum_t toml_int_at(const toml_array_t *arr, int idx); +TOML_EXTERN toml_datum_t toml_double_at(const toml_array_t *arr, int idx); +TOML_EXTERN toml_datum_t toml_timestamp_at(const toml_array_t *arr, int idx); +/* ... retrieve array or table using index. */ +TOML_EXTERN toml_array_t *toml_array_at(const toml_array_t *arr, int idx); +TOML_EXTERN toml_table_t *toml_table_at(const toml_array_t *arr, int idx); + +/* on tables: */ +/* ... retrieve the key in table at keyidx. Return 0 if out of range. */ +TOML_EXTERN const char *toml_key_in(const toml_table_t *tab, int keyidx); +/* ... returns 1 if key exists in tab, 0 otherwise */ +TOML_EXTERN int toml_key_exists(const toml_table_t *tab, const char *key); +/* ... retrieve values using key. */ +TOML_EXTERN toml_datum_t toml_string_in(const toml_table_t *arr, + const char *key); +TOML_EXTERN toml_datum_t toml_bool_in(const toml_table_t *arr, const char *key); +TOML_EXTERN toml_datum_t toml_int_in(const toml_table_t *arr, const char *key); +TOML_EXTERN toml_datum_t toml_double_in(const toml_table_t *arr, + const char *key); +TOML_EXTERN toml_datum_t toml_timestamp_in(const toml_table_t *arr, + const char *key); +/* .. retrieve array or table using key. */ +TOML_EXTERN toml_array_t *toml_array_in(const toml_table_t *tab, + const char *key); +TOML_EXTERN toml_table_t *toml_table_in(const toml_table_t *tab, + const char *key); + +/*----------------------------------------------------------------- + * lesser used + */ +/* Return the array kind: 't'able, 'a'rray, 'v'alue, 'm'ixed */ +TOML_EXTERN char toml_array_kind(const toml_array_t *arr); + +/* For array kind 'v'alue, return the type of values + i:int, d:double, b:bool, s:string, t:time, D:date, T:timestamp, 'm'ixed + 0 if unknown +*/ +TOML_EXTERN char toml_array_type(const toml_array_t *arr); + +/* Return the key of an array */ +TOML_EXTERN const char *toml_array_key(const toml_array_t *arr); + +/* Return the number of key-values in a table */ +TOML_EXTERN int toml_table_nkval(const toml_table_t *tab); + +/* Return the number of arrays in a table */ +TOML_EXTERN int toml_table_narr(const toml_table_t *tab); + +/* Return the number of sub-tables in a table */ +TOML_EXTERN int toml_table_ntab(const toml_table_t *tab); + +/* Return the key of a table*/ +TOML_EXTERN const char *toml_table_key(const toml_table_t *tab); + +/*-------------------------------------------------------------- + * misc + */ +TOML_EXTERN int toml_utf8_to_ucs(const char *orig, int len, int64_t *ret); +TOML_EXTERN int toml_ucs_to_utf8(int64_t code, char buf[6]); +TOML_EXTERN void toml_set_memutil(void *(*xxmalloc)(size_t), + void (*xxfree)(void *)); + +/*-------------------------------------------------------------- + * deprecated + */ +/* A raw value, must be processed by toml_rto* before using. */ +typedef const char *toml_raw_t; +TOML_EXTERN toml_raw_t toml_raw_in(const toml_table_t *tab, const char *key); +TOML_EXTERN toml_raw_t toml_raw_at(const toml_array_t *arr, int idx); +TOML_EXTERN int toml_rtos(toml_raw_t s, char **ret); +TOML_EXTERN int toml_rtob(toml_raw_t s, int *ret); +TOML_EXTERN int toml_rtoi(toml_raw_t s, int64_t *ret); +TOML_EXTERN int toml_rtod(toml_raw_t s, double *ret); +TOML_EXTERN int toml_rtod_ex(toml_raw_t s, double *ret, char *buf, int buflen); +TOML_EXTERN int toml_rtots(toml_raw_t s, toml_timestamp_t *ret); + +#endif /* TOML_H */ diff --git a/src/meson.build b/src/meson.build index bedb18cda12dc3a4bb1614bf843af039a30afb7f..677afa11bce3f4937b8365a55c8db5c86591a2cd 100644 --- a/src/meson.build +++ b/src/meson.build @@ -25,6 +25,7 @@ subdir('util') subdir('generate') subdir('GLdispatch') subdir('OpenGL') +subdir('app_profile') if get_option('egl') subdir('EGL') @@ -42,3 +43,6 @@ if get_option('gles2') subdir('GLESv2') endif +if with_vulkan + subdir('vulkanconfig') +endif diff --git a/src/vulkanconfig/Makefile.am b/src/vulkanconfig/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..56451a641cd671e76d76d8b30029f4f8b660ef9a --- /dev/null +++ b/src/vulkanconfig/Makefile.am @@ -0,0 +1,52 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and/or associated documentation files (the +# "Materials"), to deal in the Materials without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Materials, and to +# permit persons to whom the Materials are furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# unaltered in all copies or substantial portions of the Materials. +# Any additions, deletions, or changes to the original source files +# must be clearly indicated in accompanying documentation. +# +# THE MATERIALS ARE 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 +# MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +lib_LTLIBRARIES = libVkAppProfile.la + +libVkAppProfile_la_CFLAGS = -I$(top_srcdir)/src/util/uthash/src +libVkAppProfile_la_CFLAGS += -I$(top_srcdir)/src/util +libVkAppProfile_la_CFLAGS += -I$(top_srcdir)/include +libVkAppProfile_la_CFLAGS += -I$(top_srcdir)/src/app_profile + +# Required library flags +libVkAppProfile_la_CFLAGS += $(PTHREAD_CFLAGS) +libVkAppProfile_la_CFLAGS += $(VULKAN_CFLAGS) + +# Required libraries +libVkAppProfile_la_LIBADD = ../util/libutils_misc.la +libVkAppProfile_la_LIBADD += $(PTHREAD_LIBS) +libVkAppProfile_la_LIBADD += $(top_builddir)/src/app_profile/libGlvndAppProfile.la +libVkAppProfile_la_LDFLAGS = -shared -Wl,-Bsymbolic -version-info 0 $(LINKER_FLAG_NO_UNDEFINED) + +libVkAppProfile_la_SOURCES = +libVkAppProfile_la_SOURCES += profileLayer.c +libVkAppProfile_la_SOURCES += profileLayer.h +libVkAppProfile_la_SOURCES += instanceMap.c +libVkAppProfile_la_SOURCES += instanceMap.h +libVkAppProfile_la_SOURCES += physDevice.c + +EXTRA_DIST = \ + glvnd_device_config.json + +layerjsondir = $(datadir)/vulkan/implicit_layer.d +layerjson_DATA = glvnd_device_config.json diff --git a/src/vulkanconfig/glvnd_device_config.json b/src/vulkanconfig/glvnd_device_config.json new file mode 100644 index 0000000000000000000000000000000000000000..651f2109f17d9f6adec06ac0b6b42c52f5a913fa --- /dev/null +++ b/src/vulkanconfig/glvnd_device_config.json @@ -0,0 +1,14 @@ +{ + "file_format_version" : "1.1.0", + "layer": { + "name": "VK_LAYER_GLVND_device_config", + "type": "INSTANCE", + "library_path": "libVkAppProfile.so.0", + "api_version" : "1.1.126", + "implementation_version" : "1", + "description" : "Sorts the physical device list based on a config file.", + "functions": { + "vkNegotiateLoaderLayerInterfaceVersion": "vk_profileNegotiateLoaderLayerInterfaceVersion" + } + } +} diff --git a/src/vulkanconfig/instanceMap.c b/src/vulkanconfig/instanceMap.c new file mode 100644 index 0000000000000000000000000000000000000000..f655f07ce6c5d224cb562e22292dd5e59cefe4f9 --- /dev/null +++ b/src/vulkanconfig/instanceMap.c @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#include "instanceMap.h" + +#include +#include +#include +#include + +static pthread_mutex_t instanceMapLock = PTHREAD_MUTEX_INITIALIZER; +static InstanceLayerBase *instanceMap = NULL; + +static void *GetInstanceKey(VkInstance instance) +{ + VkLayerDispatchTable *dispatchTable = *(VkLayerDispatchTable **)instance; + return dispatchTable; +} + +InstanceLayerBase *GetInstanceLayerData(VkInstance instance) +{ + void *key = GetInstanceKey(instance); + InstanceLayerBase *layer = NULL; + + pthread_mutex_lock(&instanceMapLock);; + HASH_FIND_PTR(instanceMap, &key, layer); + pthread_mutex_unlock(&instanceMapLock); + return layer; +} + +void AddInstanceLayerData(VkInstance instance, InstanceLayerBase *layerData) +{ + assert (GetInstanceLayerData(instance) == NULL); + + pthread_mutex_lock(&instanceMapLock);; + layerData->key = GetInstanceKey(instance); + HASH_ADD_PTR(instanceMap, key, layerData); + pthread_mutex_unlock(&instanceMapLock); +} + +InstanceLayerBase *RemoveInstanceLayerData(VkInstance instance) +{ + void *key = GetInstanceKey(instance); + InstanceLayerBase *layer = NULL; + + pthread_mutex_lock(&instanceMapLock);; + HASH_FIND_PTR(instanceMap, &key, layer); + if (layer != NULL) { + HASH_DEL(instanceMap, layer); + } + pthread_mutex_unlock(&instanceMapLock); + return layer; +} + diff --git a/src/vulkanconfig/instanceMap.h b/src/vulkanconfig/instanceMap.h new file mode 100644 index 0000000000000000000000000000000000000000..5b49fa302565d2368657c44333f3fea8fc070fa4 --- /dev/null +++ b/src/vulkanconfig/instanceMap.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#ifndef INSTANCE_MAP_H +#define INSTANCE_MAP_H + +#include + +#include "uthash.h" + +/** + * A basic struct for keeping track of per-instance data. + */ +typedef struct +{ + void *key; + UT_hash_handle hh; +} InstanceLayerBase; + +InstanceLayerBase *GetInstanceLayerData(VkInstance instance); +void AddInstanceLayerData(VkInstance instance, InstanceLayerBase *layerData); +InstanceLayerBase *RemoveInstanceLayerData(VkInstance instance); + +#endif // INSTANCE_MAP_H diff --git a/src/vulkanconfig/meson.build b/src/vulkanconfig/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..0acb58434439a508d8fbbede9da46758939e1318 --- /dev/null +++ b/src/vulkanconfig/meson.build @@ -0,0 +1,50 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and/or associated documentation files (the +# "Materials"), to deal in the Materials without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Materials, and to +# permit persons to whom the Materials are furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# unaltered in all copies or substantial portions of the Materials. +# Any additions, deletions, or changes to the original source files +# must be clearly indicated in accompanying documentation. +# +# THE MATERIALS ARE 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 +# MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +libVkAppProfile = shared_library( + 'VkAppProfile', + [ + 'profileLayer.c', + 'instanceMap.c', + 'physDevice.c', + ], + include_directories : [ + inc_include, + inc_uthash, + ], + link_args : '-Wl,-Bsymbolic', + dependencies : [ + dep_threads, + idep_utils_misc, + idep_AppProfile, + ], + version : '0', + install : true, + gnu_symbol_visibility : 'hidden', +) + +install_data(['glvnd_device_config.json'], + install_dir : join_paths(get_option('prefix'), + get_option('datadir'), + 'vulkan/implicit_layer.d') +) diff --git a/src/vulkanconfig/physDevice.c b/src/vulkanconfig/physDevice.c new file mode 100644 index 0000000000000000000000000000000000000000..838e919d21fc7a63f4bff41090d4d9018cdc8105 --- /dev/null +++ b/src/vulkanconfig/physDevice.c @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#include +#include +#include +#include + +#include "profileLayer.h" +#include "utils_misc.h" + +static VkBool32 CheckExtensions(InstanceLayerData *layer, VkPhysicalDevice dev) +{ + VkPhysicalDeviceProperties props; + VkExtensionProperties *extensions; + VkBool32 foundExtension = VK_FALSE; + uint32_t count = 0; + uint32_t i; + + // Make sure that the device supports Vulkan 1.1 so that we can use + // vkGetPhysicalDeviceProperties2. Vulkan 1.1 also promotes + // VkPhysicalDeviceIDProperties to core, so we don't have to separately + // check for it. + layer->fpGetPhysicalDeviceProperties(dev, &props); + if (VK_VERSION_MAJOR(props.apiVersion) != 1 || VK_VERSION_MINOR(props.apiVersion) < 1) { + return VK_FALSE; + } + if (VK_VERSION_MINOR(props.apiVersion) >= 2) { + // With Vulkan 1.2 or later, VkPhysicalDeviceIDProperties and + // VkPhysicalDeviceDriverProperties are promoted to core. + return VK_TRUE; + } + + if (layer->fpEnumerateDeviceExtensionProperties(dev, NULL, &count, NULL) != VK_SUCCESS) { + return VK_FALSE; + } + if (count == 0) { + return VK_FALSE; + } + + extensions = malloc(count * sizeof(VkExtensionProperties)); + if (extensions == NULL) { + return VK_FALSE; + } + + if (layer->fpEnumerateDeviceExtensionProperties(dev, NULL, &count, extensions) != VK_SUCCESS) { + free(extensions); + return VK_FALSE; + } + + // Check for VK_KHR_driver_properties + for (i=0; iextensionsSupported) { + return VK_FALSE; + } + + if (vendor == NULL || uuid == NULL) { + return VK_FALSE; + } + + // Convert the VkDriverId to a name that would be in the app profile + switch (dev->driverProps.driverID) { + case VK_DRIVER_ID_NVIDIA_PROPRIETARY: + deviceVendor = "nvidia"; + break; + case VK_DRIVER_ID_MESA_RADV: + case VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA: + deviceVendor = "mesa"; + break; + // TODO: Add strings for the other VkDriverId values + default: + deviceVendor = NULL; + break; + } + if (deviceVendor == NULL) { + return VK_FALSE; + } + if (strcmp(vendor, deviceVendor) != 0) { + return VK_FALSE; + } + + // Check the device UUID + if (memcmp(dev->deviceIDProps.deviceUUID, uuid, VK_UUID_SIZE) != 0) { + return VK_FALSE; + } + + return VK_TRUE; +} + +VKAPI_ATTR VkResult VKAPI_CALL vk_profileEnumeratePhysicalDevices( + VkInstance instance, + uint32_t* pPhysicalDeviceCount, + VkPhysicalDevice* pPhysicalDevices) +{ + InstanceLayerData *layer = (InstanceLayerData *) GetInstanceLayerData(instance); + VkPhysicalDevice *devices; + DeviceInfo *info; + uint32_t count = 0; + uint32_t outIndex = 0; + uint32_t i, j; + int profileDevCount; + const char **deviceVendors; + const uint8_t **deviceUUIDs; + uintptr_t shouldFilter = 0; + VkResult result; + + /* + * This layer works by sorting the VkPhysicalDevice list so that the + * devices listed in the profile (if any) show up first in the list. That + * should be sufficient for any application that just grabs the first + * usable device that it finds. + * + * Another option would be to filter the list so that an application only + * sees the selected devices, or to intercept WSI functions so that only + * the selected device supports a particular window system. + * + * On the application side, a new Vulkan extension could allow an + * application to just query a preferred device. + */ + + if (layer->profile == NULL) { + return layer->fpEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices); + } + + profileDevCount = glvndProfileGetAttribute(layer->profile, + GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, 0, NULL, NULL); + if (profileDevCount <= 0) { + return layer->fpEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices); + } + deviceVendors = alloca(profileDevCount * sizeof(const char *)); + deviceUUIDs = alloca(profileDevCount * sizeof(const uint8_t *)); + + if (glvndProfileGetAttribute(layer->profile, GLVND_PROFILE_ATTRIB_OFFLOAD_VENDOR_NAME, + profileDevCount, NULL, (uintptr_t *) deviceVendors) != profileDevCount) { + return layer->fpEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices); + } + if (glvndProfileGetAttribute(layer->profile, GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, + profileDevCount, NULL, (uintptr_t *) deviceUUIDs) != profileDevCount) { + return layer->fpEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices); + } + + if (glvndProfileGetAttribute(layer->profile, GLVND_PROFILE_ATTRIB_FILTER_DEVICES, 1, NULL, &shouldFilter) <= 0) { + shouldFilter = 0; + } + + result = layer->fpEnumeratePhysicalDevices(instance, &count, NULL); + if (result != VK_SUCCESS) { + return result; + } + if (count == 0) { + *pPhysicalDeviceCount = 0; + return VK_SUCCESS; + } + + devices = malloc(count * sizeof(VkPhysicalDevice)); + info = malloc(count * sizeof(DeviceInfo)); + if (devices == NULL || info == NULL) { + free(devices); + free(info); + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + + result = layer->fpEnumeratePhysicalDevices(instance, &count, devices); + if (result != VK_SUCCESS) { + free(devices); + free(info); + return result; + } + + for (i=0; idev = devices[i]; + dev->extensionsSupported = CheckExtensions(layer, devices[i]); + if (dev->extensionsSupported) + { + dev->props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; + dev->props.pNext = &dev->deviceIDProps; + dev->deviceIDProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES; + dev->deviceIDProps.pNext = &dev->driverProps; + dev->driverProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES; + dev->driverProps.pNext = NULL; + + layer->fpGetPhysicalDeviceProperties2(devices[i], &dev->props); + } + } + + // Look through each device ID from the profile and try to find a matching + // VkPhysicalDevice. + for (i=0; i *pPhysicalDeviceCount) { + outIndex = *pPhysicalDeviceCount; + result = VK_INCOMPLETE; + } else { + *pPhysicalDeviceCount = outIndex; + result = VK_SUCCESS; + } + memcpy(pPhysicalDevices, devices, outIndex * sizeof(VkPhysicalDevice)); + } else { + *pPhysicalDeviceCount = outIndex; + result = VK_SUCCESS; + } + free(devices); + free(info); + return result; +} diff --git a/src/vulkanconfig/profileLayer.c b/src/vulkanconfig/profileLayer.c new file mode 100644 index 0000000000000000000000000000000000000000..dcd73dbdaae94c99b02a0c576bb5effb8607f902 --- /dev/null +++ b/src/vulkanconfig/profileLayer.c @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#include "profileLayer.h" + +#include +#include +#include +#include +#include +#include + +static InstanceLayerData *InitLayerData(void) +{ + InstanceLayerData *layer; + + layer = calloc(1, sizeof(InstanceLayerData)); + if (layer == NULL) { + return NULL; + } + + return layer; +} + +static void FreeLayerData(InstanceLayerData *layer) +{ + if (layer != NULL) { + free(layer); + } +} + +static VkResult VKAPI_CALL vk_profileCreateInstance( + const VkInstanceCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkInstance* pInstance) +{ + PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = NULL; + PFN_vkCreateInstance fpCreateInstance = NULL; + const VkLayerInstanceCreateInfo * chainInfo; + InstanceLayerData *layerData; + VkResult result; + + // Find the next vkCreateInstance down the chain. + chainInfo = (const VkLayerInstanceCreateInfo *)pCreateInfo->pNext; + while (chainInfo) { + if (chainInfo->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && + chainInfo->function == VK_LAYER_LINK_INFO) { + + fpGetInstanceProcAddr = chainInfo->u.pLayerInfo->pfnNextGetInstanceProcAddr; + fpCreateInstance = (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance"); + break; + } + chainInfo = (const VkLayerInstanceCreateInfo *)chainInfo->pNext; + } + if (fpCreateInstance == NULL) { + return VK_ERROR_INITIALIZATION_FAILED; + } + + layerData = InitLayerData(); + if (layerData == NULL) { + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + ((VkLayerInstanceCreateInfo *) chainInfo)->u.pLayerInfo = chainInfo->u.pLayerInfo->pNext; + result = fpCreateInstance(pCreateInfo, pAllocator, pInstance); + if (result != VK_SUCCESS) { + FreeLayerData(layerData); + return result; + } + layerData->instance = *pInstance; + + // Use the chained GetInstanceProcAddr. + layerData->fpGetInstanceProcAddr = fpGetInstanceProcAddr; + layerData->fpDestroyInstance = (PFN_vkDestroyInstance)fpGetInstanceProcAddr(*pInstance, "vkDestroyInstance"); + layerData->fpEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)fpGetInstanceProcAddr(*pInstance, "vkEnumeratePhysicalDevices"); + layerData->fpEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)fpGetInstanceProcAddr(*pInstance, "vkEnumerateDeviceExtensionProperties"); + layerData->fpGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)fpGetInstanceProcAddr(*pInstance, "vkGetPhysicalDeviceProperties"); + + /* + * We can't rely on the app enabling VK_KHR_get_physical_device_properties2, + * and a layer can't (currently) add an extension to an instance, + * so instead we just rely on having vkGetPhysicalDeviceProperties2 + * as a core function. + * + * Ideally, we should check the API version here, but apparently a layer + * can't look up vkEnumerateInstanceVersion. + */ + layerData->fpGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2)fpGetInstanceProcAddr(*pInstance, "vkGetPhysicalDeviceProperties2"); + layerData->fpEnumeratePhysicalDeviceGroups = (PFN_vkEnumeratePhysicalDeviceGroups)fpGetInstanceProcAddr(*pInstance, "vkEnumeratePhysicalDeviceGroups"); + layerData->fpEnumeratePhysicalDeviceGroupsKHR = (PFN_vkEnumeratePhysicalDeviceGroups)fpGetInstanceProcAddr(*pInstance, "vkEnumeratePhysicalDeviceGroupsKHR"); + + // We rely on vkGetPhysicalDeviceProperties2, so if it isn't available, + // then don't bother loading a profile. + if (layerData->fpGetPhysicalDeviceProperties2 != NULL) { + static const uintptr_t PROFILE_HINTS[] = { + GLVND_PROFILE_HINT_API_NAME, (uintptr_t) "vulkan", + 0 + }; + layerData->profile = glvndProfileLoad(PROFILE_HINTS); + if (layerData->profile != NULL) { + if (glvndProfileGetAttribute(layerData->profile, GLVND_PROFILE_ATTRIB_OFFLOAD_DEVICE_UUID, 0, NULL, NULL) <= 0) { + // We don't have an offload device configured, so free the + // profile now. + glvndProfileFree(layerData->profile); + layerData->profile = NULL; + } + } + } + + AddInstanceLayerData(*pInstance, &layerData->base); + return VK_SUCCESS; +} + +static VKAPI_ATTR void VKAPI_CALL vk_profileDestroyInstance( + VkInstance instance, + const VkAllocationCallbacks* pAllocator) +{ + if (instance != NULL) { + InstanceLayerData *layerData = (InstanceLayerData *) RemoveInstanceLayerData(instance); + layerData->fpDestroyInstance(instance, pAllocator); + FreeLayerData(layerData); + } +} + +static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_profileGetInstanceProcAddr(VkInstance instance, const char *pName) +{ + if (strcmp(pName, "vkCreateInstance") == 0) { + return (PFN_vkVoidFunction) vk_profileCreateInstance; + } else if (strcmp(pName, "vkDestroyInstance") == 0) { + return (PFN_vkVoidFunction)vk_profileDestroyInstance; + } else if (strcmp(pName, "vkEnumeratePhysicalDevices") == 0) { + return (PFN_vkVoidFunction)vk_profileEnumeratePhysicalDevices; + } else { + InstanceLayerData *layerData = (InstanceLayerData *) GetInstanceLayerData(instance); + return layerData->fpGetInstanceProcAddr(instance, pName); + } +} + +VK_LAYER_EXPORT VKAPI_ATTR VkResult vk_profileNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *pVersionStruct) +{ + if (pVersionStruct->sType != LAYER_NEGOTIATE_INTERFACE_STRUCT) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + if (pVersionStruct->loaderLayerInterfaceVersion != 2) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + + pVersionStruct->pfnGetInstanceProcAddr = vk_profileGetInstanceProcAddr; + return VK_SUCCESS; +} diff --git a/src/vulkanconfig/profileLayer.h b/src/vulkanconfig/profileLayer.h new file mode 100644 index 0000000000000000000000000000000000000000..eaf57002dc428143042e1606f335fe6e82ea5b9b --- /dev/null +++ b/src/vulkanconfig/profileLayer.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * unaltered in all copies or substantial portions of the Materials. + * Any additions, deletions, or changes to the original source files + * must be clearly indicated in accompanying documentation. + * + * THE MATERIALS ARE 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 + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +#ifndef PROFILE_LAYER_H +#define PROFILE_LAYER_H + +#include +#include + +#include "app_profile.h" +#include "instanceMap.h" + +typedef struct +{ + InstanceLayerBase base; // Must be first + + VkInstance instance; + GLVNDProfile *profile; + + PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr; + PFN_vkDestroyInstance fpDestroyInstance; + PFN_vkEnumeratePhysicalDevices fpEnumeratePhysicalDevices; + PFN_vkEnumerateDeviceExtensionProperties fpEnumerateDeviceExtensionProperties; + PFN_vkGetPhysicalDeviceProperties fpGetPhysicalDeviceProperties; + + PFN_vkGetPhysicalDeviceProperties2 fpGetPhysicalDeviceProperties2; + PFN_vkEnumeratePhysicalDeviceGroups fpEnumeratePhysicalDeviceGroups; + PFN_vkEnumeratePhysicalDeviceGroups fpEnumeratePhysicalDeviceGroupsKHR; +} InstanceLayerData; + +VKAPI_ATTR VkResult VKAPI_CALL vk_profileEnumeratePhysicalDevices( + VkInstance instance, + uint32_t* pPhysicalDeviceCount, + VkPhysicalDevice* pPhysicalDevices); + +#endif // PROFILE_LAYER_H