runtime_interface.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // Copyright (c) 2017-2022, The Khronos Group Inc.
  2. // Copyright (c) 2017-2019 Valve Corporation
  3. // Copyright (c) 2017-2019 LunarG, Inc.
  4. //
  5. // SPDX-License-Identifier: Apache-2.0 OR MIT
  6. //
  7. // Initial Author: Mark Young <[email protected]>
  8. //
  9. #include "runtime_interface.hpp"
  10. #include "manifest_file.hpp"
  11. #include "loader_interfaces.h"
  12. #include "loader_logger.hpp"
  13. #include "loader_platform.hpp"
  14. #include "xr_generated_dispatch_table.h"
  15. #include <openxr/openxr.h>
  16. #include <cstring>
  17. #include <memory>
  18. #include <mutex>
  19. #include <string>
  20. #include <unordered_map>
  21. #include <utility>
  22. #include <vector>
  23. #ifdef XR_USE_PLATFORM_ANDROID
  24. #include "android_utilities.h"
  25. #include <android/asset_manager_jni.h>
  26. #include <json/value.h>
  27. #endif // XR_USE_PLATFORM_ANDROID
  28. #ifdef XR_KHR_LOADER_INIT_SUPPORT
  29. namespace {
  30. /*!
  31. * Stores a copy of the data passed to the xrInitializeLoaderKHR function in a singleton.
  32. */
  33. class LoaderInitData {
  34. public:
  35. /*!
  36. * Singleton accessor.
  37. */
  38. static LoaderInitData& instance() {
  39. static LoaderInitData obj;
  40. return obj;
  41. }
  42. #ifdef XR_USE_PLATFORM_ANDROID
  43. /*!
  44. * Type alias for the platform-specific structure type.
  45. */
  46. using StructType = XrLoaderInitInfoAndroidKHR;
  47. /*!
  48. * Native library path.
  49. */
  50. std::string _native_library_path;
  51. /*!
  52. * Android asset manager.
  53. */
  54. AAssetManager* _android_asset_manager;
  55. #endif
  56. /*!
  57. * Get our copy of the data, casted to pass to the runtime's matching method.
  58. */
  59. const XrLoaderInitInfoBaseHeaderKHR* getParam() const { return reinterpret_cast<const XrLoaderInitInfoBaseHeaderKHR*>(&_data); }
  60. /*!
  61. * Get the data via its real structure type.
  62. */
  63. const StructType& getData() const { return _data; }
  64. /*!
  65. * Has this been correctly initialized?
  66. */
  67. bool initialized() const noexcept { return _initialized; }
  68. /*!
  69. * Initialize loader data - called by InitializeLoader() and thus ultimately by the loader's xrInitializeLoaderKHR
  70. * implementation. Each platform that needs this extension will provide an implementation of this.
  71. */
  72. XrResult initialize(const XrLoaderInitInfoBaseHeaderKHR* info);
  73. private:
  74. //! Private constructor, forces use of singleton accessor.
  75. LoaderInitData() = default;
  76. //! Platform-specific init data
  77. StructType _data = {};
  78. //! Flag for indicating whether _data is valid.
  79. bool _initialized = false;
  80. };
  81. #ifdef XR_USE_PLATFORM_ANDROID
  82. // Check and copy the Android-specific init data.
  83. XrResult LoaderInitData::initialize(const XrLoaderInitInfoBaseHeaderKHR* info) {
  84. if (info->type != XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR) {
  85. return XR_ERROR_VALIDATION_FAILURE;
  86. }
  87. auto cast_info = reinterpret_cast<XrLoaderInitInfoAndroidKHR const*>(info);
  88. if (cast_info->applicationVM == nullptr) {
  89. return XR_ERROR_VALIDATION_FAILURE;
  90. }
  91. if (cast_info->applicationContext == nullptr) {
  92. return XR_ERROR_VALIDATION_FAILURE;
  93. }
  94. _data = *cast_info;
  95. jni::init((jni::JavaVM*)_data.applicationVM);
  96. _data.next = nullptr;
  97. JNIEnv* Env;
  98. ((jni::JavaVM*)(cast_info->applicationVM))->AttachCurrentThread(&Env, nullptr);
  99. const jclass contextClass = Env->GetObjectClass((jobject)_data.applicationContext);
  100. const jmethodID getAssetsMethod = Env->GetMethodID(contextClass, "getAssets", "()Landroid/content/res/AssetManager;");
  101. const jobject AssetManagerObject = Env->CallObjectMethod((jobject)_data.applicationContext, getAssetsMethod);
  102. _android_asset_manager = AAssetManager_fromJava(Env, AssetManagerObject);
  103. const jmethodID getApplicationContextMethod =
  104. Env->GetMethodID(contextClass, "getApplicationContext", "()Landroid/content/Context;");
  105. const jobject contextObject = Env->CallObjectMethod((jobject)_data.applicationContext, getApplicationContextMethod);
  106. const jmethodID getApplicationInfoMethod =
  107. Env->GetMethodID(contextClass, "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;");
  108. const jobject applicationInfoObject = Env->CallObjectMethod(contextObject, getApplicationInfoMethod);
  109. const jfieldID nativeLibraryDirField =
  110. Env->GetFieldID(Env->GetObjectClass(applicationInfoObject), "nativeLibraryDir", "Ljava/lang/String;");
  111. const jobject nativeLibraryDirObject = Env->GetObjectField(applicationInfoObject, nativeLibraryDirField);
  112. const jmethodID getBytesMethod =
  113. Env->GetMethodID(Env->GetObjectClass(nativeLibraryDirObject), "getBytes", "(Ljava/lang/String;)[B");
  114. const auto bytesObject =
  115. static_cast<jbyteArray>(Env->CallObjectMethod(nativeLibraryDirObject, getBytesMethod, Env->NewStringUTF("UTF-8")));
  116. const size_t length = Env->GetArrayLength(bytesObject);
  117. const jbyte* const bytes = Env->GetByteArrayElements(bytesObject, nullptr);
  118. _native_library_path = std::string(reinterpret_cast<const char*>(bytes), length);
  119. _initialized = true;
  120. return XR_SUCCESS;
  121. }
  122. #endif // XR_USE_PLATFORM_ANDROID
  123. } // namespace
  124. XrResult InitializeLoader(const XrLoaderInitInfoBaseHeaderKHR* loaderInitInfo) {
  125. return LoaderInitData::instance().initialize(loaderInitInfo);
  126. }
  127. std::string GetAndroidNativeLibraryDir() { return LoaderInitData::instance()._native_library_path; }
  128. void* Android_Get_Asset_Manager() { return LoaderInitData::instance()._android_asset_manager; }
  129. #endif // XR_KHR_LOADER_INIT_SUPPORT
  130. #ifdef XR_USE_PLATFORM_ANDROID
  131. XrResult GetPlatformRuntimeVirtualManifest(Json::Value& out_manifest) {
  132. using wrap::android::content::Context;
  133. auto& initData = LoaderInitData::instance();
  134. if (!initData.initialized()) {
  135. return XR_ERROR_INITIALIZATION_FAILED;
  136. }
  137. auto context = Context(reinterpret_cast<jobject>(initData.getData().applicationContext));
  138. if (context.isNull()) {
  139. return XR_ERROR_INITIALIZATION_FAILED;
  140. }
  141. Json::Value virtualManifest;
  142. if (0 != openxr_android::getActiveRuntimeVirtualManifest(context, virtualManifest)) {
  143. return XR_ERROR_INITIALIZATION_FAILED;
  144. }
  145. out_manifest = virtualManifest;
  146. return XR_SUCCESS;
  147. }
  148. #endif // XR_USE_PLATFORM_ANDROID
  149. XrResult RuntimeInterface::TryLoadingSingleRuntime(const std::string& openxr_command,
  150. std::unique_ptr<RuntimeManifestFile>& manifest_file) {
  151. LoaderPlatformLibraryHandle runtime_library = LoaderPlatformLibraryOpen(manifest_file->LibraryPath());
  152. if (nullptr == runtime_library) {
  153. std::string library_message = LoaderPlatformLibraryOpenError(manifest_file->LibraryPath());
  154. std::string warning_message = "RuntimeInterface::LoadRuntime skipping manifest file ";
  155. warning_message += manifest_file->Filename();
  156. warning_message += ", failed to load with message \"";
  157. warning_message += library_message;
  158. warning_message += "\"";
  159. LoaderLogger::LogErrorMessage(openxr_command, warning_message);
  160. return XR_ERROR_FILE_ACCESS_ERROR;
  161. }
  162. #ifdef XR_KHR_LOADER_INIT_SUPPORT
  163. if (!LoaderInitData::instance().initialized()) {
  164. LoaderLogger::LogErrorMessage(openxr_command, "RuntimeInterface::LoadRuntime skipping manifest file " +
  165. manifest_file->Filename() +
  166. " because xrInitializeLoaderKHR was not yet called.");
  167. LoaderPlatformLibraryClose(runtime_library);
  168. return XR_ERROR_VALIDATION_FAILURE;
  169. }
  170. bool forwardedInitLoader = false;
  171. {
  172. // If we have xrInitializeLoaderKHR exposed as an export, forward call to it.
  173. const auto function_name = manifest_file->GetFunctionName("xrInitializeLoaderKHR");
  174. auto initLoader =
  175. reinterpret_cast<PFN_xrInitializeLoaderKHR>(LoaderPlatformLibraryGetProcAddr(runtime_library, function_name));
  176. if (initLoader != nullptr) {
  177. // we found the entry point one way or another.
  178. LoaderLogger::LogInfoMessage(openxr_command,
  179. "RuntimeInterface::LoadRuntime forwarding xrInitializeLoaderKHR call to runtime before "
  180. "calling xrNegotiateLoaderRuntimeInterface.");
  181. XrResult res = initLoader(LoaderInitData::instance().getParam());
  182. if (!XR_SUCCEEDED(res)) {
  183. LoaderLogger::LogErrorMessage(openxr_command,
  184. "RuntimeInterface::LoadRuntime forwarded call to xrInitializeLoaderKHR failed.");
  185. LoaderPlatformLibraryClose(runtime_library);
  186. return res;
  187. }
  188. forwardedInitLoader = true;
  189. }
  190. }
  191. #endif
  192. // Get and settle on an runtime interface version (using any provided name if required).
  193. std::string function_name = manifest_file->GetFunctionName("xrNegotiateLoaderRuntimeInterface");
  194. auto negotiate =
  195. reinterpret_cast<PFN_xrNegotiateLoaderRuntimeInterface>(LoaderPlatformLibraryGetProcAddr(runtime_library, function_name));
  196. // Loader info for negotiation
  197. XrNegotiateLoaderInfo loader_info = {};
  198. loader_info.structType = XR_LOADER_INTERFACE_STRUCT_LOADER_INFO;
  199. loader_info.structVersion = XR_LOADER_INFO_STRUCT_VERSION;
  200. loader_info.structSize = sizeof(XrNegotiateLoaderInfo);
  201. loader_info.minInterfaceVersion = 1;
  202. loader_info.maxInterfaceVersion = XR_CURRENT_LOADER_RUNTIME_VERSION;
  203. loader_info.minApiVersion = XR_MAKE_VERSION(1, 0, 0);
  204. loader_info.maxApiVersion = XR_MAKE_VERSION(1, 0x3ff, 0xfff); // Maximum allowed version for this major version.
  205. // Set up the runtime return structure
  206. XrNegotiateRuntimeRequest runtime_info = {};
  207. runtime_info.structType = XR_LOADER_INTERFACE_STRUCT_RUNTIME_REQUEST;
  208. runtime_info.structVersion = XR_RUNTIME_INFO_STRUCT_VERSION;
  209. runtime_info.structSize = sizeof(XrNegotiateRuntimeRequest);
  210. // Skip calling the negotiate function and fail if the function pointer
  211. // could not get loaded
  212. XrResult res = XR_ERROR_RUNTIME_FAILURE;
  213. if (nullptr != negotiate) {
  214. res = negotiate(&loader_info, &runtime_info);
  215. }
  216. // If we supposedly succeeded, but got a nullptr for GetInstanceProcAddr
  217. // then something still went wrong, so return with an error.
  218. if (XR_SUCCEEDED(res)) {
  219. uint32_t runtime_major = XR_VERSION_MAJOR(runtime_info.runtimeApiVersion);
  220. uint32_t runtime_minor = XR_VERSION_MINOR(runtime_info.runtimeApiVersion);
  221. uint32_t loader_major = XR_VERSION_MAJOR(XR_CURRENT_API_VERSION);
  222. if (nullptr == runtime_info.getInstanceProcAddr) {
  223. std::string error_message = "RuntimeInterface::LoadRuntime skipping manifest file ";
  224. error_message += manifest_file->Filename();
  225. error_message += ", negotiation succeeded but returned NULL getInstanceProcAddr";
  226. LoaderLogger::LogErrorMessage(openxr_command, error_message);
  227. res = XR_ERROR_FILE_CONTENTS_INVALID;
  228. } else if (0 >= runtime_info.runtimeInterfaceVersion ||
  229. XR_CURRENT_LOADER_RUNTIME_VERSION < runtime_info.runtimeInterfaceVersion) {
  230. std::string error_message = "RuntimeInterface::LoadRuntime skipping manifest file ";
  231. error_message += manifest_file->Filename();
  232. error_message += ", negotiation succeeded but returned invalid interface version";
  233. LoaderLogger::LogErrorMessage(openxr_command, error_message);
  234. res = XR_ERROR_FILE_CONTENTS_INVALID;
  235. } else if (runtime_major != loader_major || (runtime_major == 0 && runtime_minor == 0)) {
  236. std::string error_message = "RuntimeInterface::LoadRuntime skipping manifest file ";
  237. error_message += manifest_file->Filename();
  238. error_message += ", OpenXR version returned not compatible with this loader";
  239. LoaderLogger::LogErrorMessage(openxr_command, error_message);
  240. res = XR_ERROR_FILE_CONTENTS_INVALID;
  241. }
  242. }
  243. #ifdef XR_KHR_LOADER_INIT_SUPPORT
  244. if (XR_SUCCEEDED(res) && !forwardedInitLoader) {
  245. // Forward initialize loader call, where possible and if we did not do so before.
  246. PFN_xrVoidFunction initializeVoid = nullptr;
  247. PFN_xrInitializeLoaderKHR initialize = nullptr;
  248. // Now we may try asking xrGetInstanceProcAddr
  249. if (XR_SUCCEEDED(runtime_info.getInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", &initializeVoid))) {
  250. if (initializeVoid == nullptr) {
  251. LoaderLogger::LogErrorMessage(openxr_command,
  252. "RuntimeInterface::LoadRuntime got success from xrGetInstanceProcAddr "
  253. "for xrInitializeLoaderKHR, but output a null pointer.");
  254. res = XR_ERROR_RUNTIME_FAILURE;
  255. } else {
  256. initialize = reinterpret_cast<PFN_xrInitializeLoaderKHR>(initializeVoid);
  257. }
  258. }
  259. if (initialize != nullptr) {
  260. // we found the entry point one way or another.
  261. LoaderLogger::LogInfoMessage(openxr_command,
  262. "RuntimeInterface::LoadRuntime forwarding xrInitializeLoaderKHR call to runtime after "
  263. "calling xrNegotiateLoaderRuntimeInterface.");
  264. res = initialize(LoaderInitData::instance().getParam());
  265. if (!XR_SUCCEEDED(res)) {
  266. LoaderLogger::LogErrorMessage(openxr_command,
  267. "RuntimeInterface::LoadRuntime forwarded call to xrInitializeLoaderKHR failed.");
  268. }
  269. }
  270. }
  271. #endif
  272. if (XR_FAILED(res)) {
  273. std::string warning_message = "RuntimeInterface::LoadRuntime skipping manifest file ";
  274. warning_message += manifest_file->Filename();
  275. warning_message += ", negotiation failed with error ";
  276. warning_message += std::to_string(res);
  277. LoaderLogger::LogErrorMessage(openxr_command, warning_message);
  278. LoaderPlatformLibraryClose(runtime_library);
  279. return res;
  280. }
  281. std::string info_message = "RuntimeInterface::LoadRuntime succeeded loading runtime defined in manifest file ";
  282. info_message += manifest_file->Filename();
  283. info_message += " using interface version ";
  284. info_message += std::to_string(runtime_info.runtimeInterfaceVersion);
  285. info_message += " and OpenXR API version ";
  286. info_message += std::to_string(XR_VERSION_MAJOR(runtime_info.runtimeApiVersion));
  287. info_message += ".";
  288. info_message += std::to_string(XR_VERSION_MINOR(runtime_info.runtimeApiVersion));
  289. LoaderLogger::LogInfoMessage(openxr_command, info_message);
  290. // Use this runtime
  291. GetInstance().reset(new RuntimeInterface(runtime_library, runtime_info.getInstanceProcAddr));
  292. // Grab the list of extensions this runtime supports for easy filtering after the
  293. // xrCreateInstance call
  294. std::vector<std::string> supported_extensions;
  295. std::vector<XrExtensionProperties> extension_properties;
  296. GetInstance()->GetInstanceExtensionProperties(extension_properties);
  297. supported_extensions.reserve(extension_properties.size());
  298. for (XrExtensionProperties ext_prop : extension_properties) {
  299. supported_extensions.emplace_back(ext_prop.extensionName);
  300. }
  301. GetInstance()->SetSupportedExtensions(supported_extensions);
  302. return XR_SUCCESS;
  303. }
  304. XrResult RuntimeInterface::LoadRuntime(const std::string& openxr_command) {
  305. // If something's already loaded, we're done here.
  306. if (GetInstance() != nullptr) {
  307. return XR_SUCCESS;
  308. }
  309. #ifdef XR_KHR_LOADER_INIT_SUPPORT
  310. if (!LoaderInitData::instance().initialized()) {
  311. LoaderLogger::LogErrorMessage(
  312. openxr_command, "RuntimeInterface::LoadRuntime cannot run because xrInitializeLoaderKHR was not successfully called.");
  313. return XR_ERROR_INITIALIZATION_FAILED;
  314. }
  315. #endif // XR_KHR_LOADER_INIT_SUPPORT
  316. std::vector<std::unique_ptr<RuntimeManifestFile>> runtime_manifest_files = {};
  317. // Find the available runtimes which we may need to report information for.
  318. XrResult last_error = RuntimeManifestFile::FindManifestFiles(runtime_manifest_files);
  319. if (XR_FAILED(last_error)) {
  320. LoaderLogger::LogErrorMessage(openxr_command, "RuntimeInterface::LoadRuntimes - unknown error");
  321. } else {
  322. last_error = XR_ERROR_RUNTIME_UNAVAILABLE;
  323. for (std::unique_ptr<RuntimeManifestFile>& manifest_file : runtime_manifest_files) {
  324. last_error = RuntimeInterface::TryLoadingSingleRuntime(openxr_command, manifest_file);
  325. if (XR_SUCCEEDED(last_error)) {
  326. break;
  327. }
  328. }
  329. }
  330. // Unsuccessful in loading any runtime, throw the runtime unavailable message.
  331. if (XR_FAILED(last_error)) {
  332. LoaderLogger::LogErrorMessage(openxr_command, "RuntimeInterface::LoadRuntimes - failed to load a runtime");
  333. last_error = XR_ERROR_RUNTIME_UNAVAILABLE;
  334. }
  335. return last_error;
  336. }
  337. void RuntimeInterface::UnloadRuntime(const std::string& openxr_command) {
  338. if (GetInstance()) {
  339. LoaderLogger::LogInfoMessage(openxr_command, "RuntimeInterface::UnloadRuntime - Unloading RuntimeInterface");
  340. GetInstance().reset();
  341. }
  342. }
  343. XrResult RuntimeInterface::GetInstanceProcAddr(XrInstance instance, const char* name, PFN_xrVoidFunction* function) {
  344. return GetInstance()->_get_instance_proc_addr(instance, name, function);
  345. }
  346. const XrGeneratedDispatchTable* RuntimeInterface::GetDispatchTable(XrInstance instance) {
  347. XrGeneratedDispatchTable* table = nullptr;
  348. std::lock_guard<std::mutex> mlock(GetInstance()->_dispatch_table_mutex);
  349. auto it = GetInstance()->_dispatch_table_map.find(instance);
  350. if (it != GetInstance()->_dispatch_table_map.end()) {
  351. table = it->second.get();
  352. }
  353. return table;
  354. }
  355. const XrGeneratedDispatchTable* RuntimeInterface::GetDebugUtilsMessengerDispatchTable(XrDebugUtilsMessengerEXT messenger) {
  356. XrInstance runtime_instance = XR_NULL_HANDLE;
  357. {
  358. std::lock_guard<std::mutex> mlock(GetInstance()->_messenger_to_instance_mutex);
  359. auto it = GetInstance()->_messenger_to_instance_map.find(messenger);
  360. if (it != GetInstance()->_messenger_to_instance_map.end()) {
  361. runtime_instance = it->second;
  362. }
  363. }
  364. return GetDispatchTable(runtime_instance);
  365. }
  366. RuntimeInterface::RuntimeInterface(LoaderPlatformLibraryHandle runtime_library, PFN_xrGetInstanceProcAddr get_instance_proc_addr)
  367. : _runtime_library(runtime_library), _get_instance_proc_addr(get_instance_proc_addr) {}
  368. RuntimeInterface::~RuntimeInterface() {
  369. std::string info_message = "RuntimeInterface being destroyed.";
  370. LoaderLogger::LogInfoMessage("", info_message);
  371. {
  372. std::lock_guard<std::mutex> mlock(_dispatch_table_mutex);
  373. _dispatch_table_map.clear();
  374. }
  375. LoaderPlatformLibraryClose(_runtime_library);
  376. }
  377. void RuntimeInterface::GetInstanceExtensionProperties(std::vector<XrExtensionProperties>& extension_properties) {
  378. std::vector<XrExtensionProperties> runtime_extension_properties;
  379. PFN_xrEnumerateInstanceExtensionProperties rt_xrEnumerateInstanceExtensionProperties;
  380. _get_instance_proc_addr(XR_NULL_HANDLE, "xrEnumerateInstanceExtensionProperties",
  381. reinterpret_cast<PFN_xrVoidFunction*>(&rt_xrEnumerateInstanceExtensionProperties));
  382. uint32_t count = 0;
  383. uint32_t count_output = 0;
  384. // Get the count from the runtime
  385. rt_xrEnumerateInstanceExtensionProperties(nullptr, count, &count_output, nullptr);
  386. if (count_output > 0) {
  387. runtime_extension_properties.resize(count_output);
  388. count = count_output;
  389. for (XrExtensionProperties& ext_prop : runtime_extension_properties) {
  390. ext_prop.type = XR_TYPE_EXTENSION_PROPERTIES;
  391. ext_prop.next = nullptr;
  392. }
  393. rt_xrEnumerateInstanceExtensionProperties(nullptr, count, &count_output, runtime_extension_properties.data());
  394. }
  395. size_t ext_count = runtime_extension_properties.size();
  396. size_t props_count = extension_properties.size();
  397. for (size_t ext = 0; ext < ext_count; ++ext) {
  398. bool found = false;
  399. for (size_t prop = 0; prop < props_count; ++prop) {
  400. // If we find it, then make sure the spec version matches that of the runtime instead of the
  401. // layer.
  402. if (strcmp(extension_properties[prop].extensionName, runtime_extension_properties[ext].extensionName) == 0) {
  403. // Make sure the spec version used is the runtime's
  404. extension_properties[prop].extensionVersion = runtime_extension_properties[ext].extensionVersion;
  405. found = true;
  406. break;
  407. }
  408. }
  409. if (!found) {
  410. extension_properties.push_back(runtime_extension_properties[ext]);
  411. }
  412. }
  413. }
  414. XrResult RuntimeInterface::CreateInstance(const XrInstanceCreateInfo* info, XrInstance* instance) {
  415. XrResult res = XR_SUCCESS;
  416. bool create_succeeded = false;
  417. PFN_xrCreateInstance rt_xrCreateInstance;
  418. _get_instance_proc_addr(XR_NULL_HANDLE, "xrCreateInstance", reinterpret_cast<PFN_xrVoidFunction*>(&rt_xrCreateInstance));
  419. res = rt_xrCreateInstance(info, instance);
  420. if (XR_SUCCEEDED(res)) {
  421. create_succeeded = true;
  422. std::unique_ptr<XrGeneratedDispatchTable> dispatch_table(new XrGeneratedDispatchTable());
  423. GeneratedXrPopulateDispatchTable(dispatch_table.get(), *instance, _get_instance_proc_addr);
  424. std::lock_guard<std::mutex> mlock(_dispatch_table_mutex);
  425. _dispatch_table_map[*instance] = std::move(dispatch_table);
  426. }
  427. // If the failure occurred during the populate, clean up the instance we had picked up from the runtime
  428. if (XR_FAILED(res) && create_succeeded) {
  429. PFN_xrDestroyInstance rt_xrDestroyInstance;
  430. _get_instance_proc_addr(*instance, "xrDestroyInstance", reinterpret_cast<PFN_xrVoidFunction*>(&rt_xrDestroyInstance));
  431. rt_xrDestroyInstance(*instance);
  432. *instance = XR_NULL_HANDLE;
  433. }
  434. return res;
  435. }
  436. XrResult RuntimeInterface::DestroyInstance(XrInstance instance) {
  437. if (XR_NULL_HANDLE != instance) {
  438. // Destroy the dispatch table for this instance first
  439. {
  440. std::lock_guard<std::mutex> mlock(_dispatch_table_mutex);
  441. auto map_iter = _dispatch_table_map.find(instance);
  442. if (map_iter != _dispatch_table_map.end()) {
  443. _dispatch_table_map.erase(map_iter);
  444. }
  445. }
  446. // Now delete the instance
  447. PFN_xrDestroyInstance rt_xrDestroyInstance;
  448. _get_instance_proc_addr(instance, "xrDestroyInstance", reinterpret_cast<PFN_xrVoidFunction*>(&rt_xrDestroyInstance));
  449. rt_xrDestroyInstance(instance);
  450. }
  451. return XR_SUCCESS;
  452. }
  453. bool RuntimeInterface::TrackDebugMessenger(XrInstance instance, XrDebugUtilsMessengerEXT messenger) {
  454. std::lock_guard<std::mutex> mlock(_messenger_to_instance_mutex);
  455. _messenger_to_instance_map[messenger] = instance;
  456. return true;
  457. }
  458. void RuntimeInterface::ForgetDebugMessenger(XrDebugUtilsMessengerEXT messenger) {
  459. if (XR_NULL_HANDLE != messenger) {
  460. std::lock_guard<std::mutex> mlock(_messenger_to_instance_mutex);
  461. _messenger_to_instance_map.erase(messenger);
  462. }
  463. }
  464. void RuntimeInterface::SetSupportedExtensions(std::vector<std::string>& supported_extensions) {
  465. _supported_extensions = supported_extensions;
  466. }
  467. bool RuntimeInterface::SupportsExtension(const std::string& extension_name) {
  468. bool found_prop = false;
  469. for (const std::string& supported_extension : _supported_extensions) {
  470. if (supported_extension == extension_name) {
  471. found_prop = true;
  472. break;
  473. }
  474. }
  475. return found_prop;
  476. }