Module.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <AzCore/Component/ComponentApplication.h>
  9. #include <AzCore/Module/Module.h>
  10. #include <AzCore/PlatformIncl.h>
  11. #include <AzCore/Module/ModuleManagerBus.h>
  12. #include <AzCore/Memory/AllocationRecords.h>
  13. #include <AzCore/UnitTest/TestTypes.h>
  14. #include "ModuleTestBus.h"
  15. #if !AZ_UNIT_TEST_SKIP_DLL_TEST
  16. #if AZ_TRAIT_TEST_SUPPORT_DLOPEN
  17. #include <dlfcn.h>
  18. #endif
  19. using namespace AZ;
  20. using ::testing::Return;
  21. using ::testing::StrEq;
  22. using ::testing::Matcher;
  23. namespace UnitTest
  24. {
  25. static const AZ::Uuid AZCoreTestsDLLModuleId{ "{99C6BF95-847F-4EEE-BB60-9B26D02FF577}" };
  26. class SystemComponentRequests
  27. : public AZ::EBusTraits
  28. {
  29. public:
  30. virtual bool IsConnected() = 0;
  31. };
  32. using SystemComponentRequestBus = AZ::EBus<SystemComponentRequests>;
  33. class SystemComponentFromModule
  34. : public AZ::Component
  35. , protected SystemComponentRequestBus::Handler
  36. {
  37. public:
  38. AZ_COMPONENT(SystemComponentFromModule, "{7CDDF71F-4D9E-41B0-8F82-4FFA86513809}")
  39. void Activate() override
  40. {
  41. SystemComponentRequestBus::Handler::BusConnect();
  42. }
  43. void Deactivate() override
  44. {
  45. SystemComponentRequestBus::Handler::BusDisconnect();
  46. }
  47. static void Reflect(AZ::ReflectContext* reflectContext)
  48. {
  49. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
  50. {
  51. serializeContext->Class<SystemComponentFromModule, AZ::Component>()
  52. ;
  53. }
  54. }
  55. protected:
  56. bool IsConnected() override
  57. {
  58. return true;
  59. }
  60. };
  61. class StaticModule
  62. : public Module
  63. , public ModuleTestRequestBus::Handler
  64. {
  65. public:
  66. AZ_CLASS_ALLOCATOR(StaticModule, AZ::SystemAllocator)
  67. static bool s_loaded;
  68. static bool s_reflected;
  69. StaticModule()
  70. {
  71. s_loaded = true;
  72. ModuleTestRequestBus::Handler::BusConnect();
  73. m_descriptors.insert(m_descriptors.end(), {
  74. SystemComponentFromModule::CreateDescriptor(),
  75. });
  76. }
  77. ~StaticModule() override
  78. {
  79. ModuleTestRequestBus::Handler::BusDisconnect();
  80. s_loaded = false;
  81. }
  82. //void Reflect(ReflectContext*) override
  83. //{
  84. // s_reflected = true;
  85. //}
  86. AZ::ComponentTypeList GetRequiredSystemComponents() const override
  87. {
  88. return AZ::ComponentTypeList{
  89. azrtti_typeid<SystemComponentFromModule>(),
  90. };
  91. }
  92. const char* GetModuleName() override
  93. {
  94. return "StaticModule";
  95. }
  96. };
  97. bool StaticModule::s_loaded = false;
  98. bool StaticModule::s_reflected = false;
  99. void AZCreateStaticModules(AZStd::vector<AZ::Module*>& modulesOut)
  100. {
  101. modulesOut.push_back(new UnitTest::StaticModule());
  102. }
  103. class ModuleManager : public UnitTest::LeakDetectionFixture
  104. {
  105. };
  106. #if AZ_TRAIT_DISABLE_FAILED_MODULE_TESTS
  107. TEST_F(ModuleManager, DISABLED_Test)
  108. #else
  109. TEST_F(ModuleManager, Test)
  110. #endif // AZ_TRAIT_DISABLE_FAILED_MODULE_TESTS
  111. {
  112. {
  113. ComponentApplication app;
  114. // Create application descriptor
  115. ComponentApplication::Descriptor appDesc;
  116. appDesc.m_memoryBlocksByteSize = 10 * 1024 * 1024;
  117. appDesc.m_recordingMode = Debug::AllocationRecords::RECORD_FULL;
  118. // AZCoreTestDLL will load as a dynamic module
  119. DynamicModuleDescriptor& dynamicModuleDescriptor = appDesc.m_modules.emplace_back();
  120. dynamicModuleDescriptor.m_dynamicLibraryPath = "AzCoreTestDLL";
  121. // StaticModule will load via AZCreateStaticModule(...)
  122. // Start up application
  123. ComponentApplication::StartupParameters startupParams;
  124. startupParams.m_createStaticModulesCallback = AZCreateStaticModules;
  125. Entity* systemEntity = app.Create(appDesc, startupParams);
  126. EXPECT_NE(nullptr, systemEntity);
  127. systemEntity->Init();
  128. systemEntity->Activate();
  129. // Check that StaticModule was loaded and reflected
  130. EXPECT_TRUE(StaticModule::s_loaded);
  131. // AZ_TEST_ASSERT(StaticModule::s_reflected);
  132. { // Query both modules via the ModuleTestRequestBus
  133. EBusAggregateResults<const char*> moduleNames;
  134. ModuleTestRequestBus::BroadcastResult(moduleNames, &ModuleTestRequestBus::Events::GetModuleName);
  135. EXPECT_TRUE(moduleNames.values.size() == 2);
  136. bool foundStaticModule = false;
  137. bool foundDynamicModule = false;
  138. for (const char* moduleName : moduleNames.values)
  139. {
  140. if (strcmp(moduleName, "DllModule") == 0)
  141. {
  142. foundDynamicModule = true;
  143. }
  144. if (strcmp(moduleName, "StaticModule") == 0)
  145. {
  146. foundStaticModule = true;
  147. }
  148. }
  149. EXPECT_TRUE(foundDynamicModule);
  150. EXPECT_TRUE(foundStaticModule);
  151. }
  152. // Check that system component from module was added
  153. bool isComponentAround = false;
  154. SystemComponentRequestBus::BroadcastResult(isComponentAround, &SystemComponentRequestBus::Events::IsConnected);
  155. EXPECT_TRUE(isComponentAround);
  156. {
  157. // Find the dynamic module
  158. const ModuleData* systemLoadedModule = nullptr;
  159. ModuleManagerRequestBus::Broadcast(&ModuleManagerRequestBus::Events::EnumerateModules, [&systemLoadedModule](const ModuleData& moduleData) {
  160. if (azrtti_typeid(moduleData.GetModule()) == AZCoreTestsDLLModuleId)
  161. {
  162. systemLoadedModule = &moduleData;
  163. return false;
  164. }
  165. else
  166. {
  167. return true;
  168. }
  169. });
  170. ASSERT_NE(nullptr, systemLoadedModule);
  171. ModuleManagerRequests::LoadModuleOutcome loadResult = AZ::Failure(AZStd::string("Failed to connect to ModuleManagerRequestBus"));
  172. // Load the module
  173. ModuleManagerRequestBus::BroadcastResult(loadResult, &ModuleManagerRequestBus::Events::LoadDynamicModule, "AzCoreTestDLL", ModuleInitializationSteps::ActivateEntity, true);
  174. ASSERT_TRUE(loadResult.IsSuccess());
  175. // Capture the handle
  176. AZStd::shared_ptr<ModuleData> moduleHandle = AZStd::move(loadResult.GetValue());
  177. // Validate that the pointer is the same as the one the system loaded
  178. EXPECT_EQ(systemLoadedModule, moduleHandle.get());
  179. // Load the module again
  180. ModuleManagerRequestBus::BroadcastResult(loadResult, &ModuleManagerRequestBus::Events::LoadDynamicModule, "AzCoreTestDLL", ModuleInitializationSteps::ActivateEntity, true);
  181. ASSERT_TRUE(loadResult.IsSuccess());
  182. // Validate that the pointers from the load calls are the same
  183. EXPECT_EQ(moduleHandle.get(), loadResult.GetValue().get());
  184. }
  185. // shut down application (deletes Modules, unloads DLLs)
  186. app.Destroy();
  187. }
  188. EXPECT_FALSE(StaticModule::s_loaded);
  189. bool isComponentAround = false;
  190. SystemComponentRequestBus::BroadcastResult(isComponentAround, &SystemComponentRequestBus::Events::IsConnected);
  191. EXPECT_FALSE(isComponentAround);
  192. }
  193. #if AZ_TRAIT_DISABLE_FAILED_MODULE_TESTS
  194. TEST_F(ModuleManager, DISABLED_SequentialLoadTest)
  195. #else
  196. TEST_F(ModuleManager, SequentialLoadTest)
  197. #endif
  198. {
  199. {
  200. ComponentApplication app;
  201. // Start up application
  202. ComponentApplication::Descriptor appDesc;
  203. ComponentApplication::StartupParameters startupParams;
  204. Entity* systemEntity = app.Create(appDesc, startupParams);
  205. EXPECT_NE(nullptr, systemEntity);
  206. systemEntity->Init();
  207. systemEntity->Activate();
  208. {
  209. // this scope exists to clear memory before app is destroyed.
  210. ModuleManagerRequests::LoadModuleOutcome loadResult = AZ::Failure(AZStd::string("Failed to connect to ModuleManagerRequestBus"));
  211. // Create the module
  212. ModuleManagerRequestBus::BroadcastResult(loadResult, &ModuleManagerRequestBus::Events::LoadDynamicModule, "AzCoreTestDLL", ModuleInitializationSteps::None, true);
  213. ASSERT_TRUE(loadResult.IsSuccess());
  214. // Find the dynamic module
  215. const ModuleData* systemLoadedModule = nullptr;
  216. ModuleManagerRequestBus::Broadcast(&ModuleManagerRequestBus::Events::EnumerateModules, [&systemLoadedModule](const ModuleData& moduleData)
  217. {
  218. // Because the module was loaded with ModuleInitializationSteps::None, it should be the only one that doesn't have a module class
  219. if (!moduleData.GetModule())
  220. {
  221. systemLoadedModule = &moduleData;
  222. return false;
  223. }
  224. else
  225. {
  226. return true;
  227. }
  228. });
  229. // Test that the module exists, but is empty
  230. ASSERT_NE(nullptr, systemLoadedModule);
  231. EXPECT_EQ(nullptr, systemLoadedModule->GetDynamicModuleHandle());
  232. EXPECT_EQ(nullptr, systemLoadedModule->GetModule());
  233. EXPECT_EQ(nullptr, systemLoadedModule->GetEntity());
  234. // Capture the handle
  235. AZStd::shared_ptr<ModuleData> moduleHandle = AZStd::move(loadResult.GetValue());
  236. // Validate that the pointer is the same as the one the system loaded
  237. EXPECT_EQ(systemLoadedModule, moduleHandle.get());
  238. // Load the module
  239. ModuleManagerRequestBus::BroadcastResult(loadResult, &ModuleManagerRequestBus::Events::LoadDynamicModule, "AzCoreTestDLL", ModuleInitializationSteps::Load, true);
  240. ASSERT_TRUE(loadResult.IsSuccess());
  241. // Validate that the pointers from the load calls are the same
  242. EXPECT_EQ(moduleHandle.get(), loadResult.GetValue().get());
  243. EXPECT_NE(nullptr, systemLoadedModule->GetDynamicModuleHandle());
  244. EXPECT_EQ(nullptr, systemLoadedModule->GetModule());
  245. EXPECT_EQ(nullptr, systemLoadedModule->GetEntity());
  246. // Create the module class
  247. ModuleManagerRequestBus::BroadcastResult(loadResult, &ModuleManagerRequestBus::Events::LoadDynamicModule, "AzCoreTestDLL", ModuleInitializationSteps::CreateClass, true);
  248. ASSERT_TRUE(loadResult.IsSuccess());
  249. EXPECT_EQ(moduleHandle.get(), loadResult.GetValue().get());
  250. EXPECT_NE(nullptr, systemLoadedModule->GetDynamicModuleHandle());
  251. EXPECT_NE(nullptr, systemLoadedModule->GetModule());
  252. EXPECT_EQ(nullptr, systemLoadedModule->GetEntity());
  253. // Activate the system entity
  254. ModuleManagerRequestBus::BroadcastResult(loadResult, &ModuleManagerRequestBus::Events::LoadDynamicModule, "AzCoreTestDLL", ModuleInitializationSteps::ActivateEntity, true);
  255. ASSERT_TRUE(loadResult.IsSuccess());
  256. EXPECT_EQ(moduleHandle.get(), loadResult.GetValue().get());
  257. EXPECT_NE(nullptr, systemLoadedModule->GetDynamicModuleHandle());
  258. EXPECT_NE(nullptr, systemLoadedModule->GetModule());
  259. EXPECT_NE(nullptr, systemLoadedModule->GetEntity());
  260. }
  261. // shut down application (deletes Modules, unloads DLLs)
  262. app.Destroy();
  263. }
  264. }
  265. // the following tests only run on the following platforms which support module loading and unloading
  266. // as these platforms expand we can always use traits to include the ones that can do so:
  267. #if AZ_TRAIT_TEST_SUPPORT_MODULE_LOADING
  268. // this class just attaches to the PrintF stream and watches for a specific message
  269. // to appear.
  270. class PrintFCollector : public AZ::Debug::TraceMessageBus::Handler
  271. {
  272. public:
  273. PrintFCollector(const char* stringToWatchFor)
  274. :m_stringToWatchFor(stringToWatchFor)
  275. {
  276. BusConnect();
  277. }
  278. bool OnPrintf(const char* window, const char* message) override
  279. {
  280. if (
  281. ((window)&&(strstr(window, m_stringToWatchFor.c_str()))) ||
  282. ((message)&&(strstr(message, m_stringToWatchFor.c_str())))
  283. )
  284. {
  285. m_foundWhatWeWereWatchingFor = true;
  286. }
  287. return false;
  288. }
  289. ~PrintFCollector() override
  290. {
  291. BusDisconnect();
  292. }
  293. bool m_foundWhatWeWereWatchingFor = false;
  294. AZ::OSString m_stringToWatchFor;
  295. };
  296. TEST_F(ModuleManager, OwnerInitializesAndDeinitializesTest)
  297. {
  298. // in this test, we make sure that a module is always initialized even if the operating
  299. // system previously loaded it (due to static linkage or other reason)
  300. // and that when it is initialized in this manner, it is also deinitialized when the owner
  301. // unloads it (even if the operating system still has a handle to it).
  302. // note that the above test already tests repeated loads and unloads, so there is no
  303. // need to test that here.
  304. ComponentApplication app;
  305. // Start up application
  306. ComponentApplication::Descriptor appDesc;
  307. ComponentApplication::StartupParameters startupParams;
  308. Entity* systemEntity = app.Create(appDesc, startupParams);
  309. ASSERT_NE(nullptr, systemEntity);
  310. systemEntity->Init();
  311. systemEntity->Activate();
  312. // we open a scope here to make sure any heap allocations made by local variables during this test
  313. // are destroyed before we try to stop the app.
  314. {
  315. // we will use the fact that DynamicModuleHandle resolves paths to operating system specific
  316. // paths without actually calling Load(), and capture the final name it uses to load modules so that we
  317. // can manually load it ourselves.
  318. AZ::OSString finalPath;
  319. {
  320. auto handle = DynamicModuleHandle::Create("AzCoreTestDLL");
  321. finalPath = handle->GetFilename();
  322. }
  323. // now that we know the true name of the module in a way that it could be loaded by the operating system,
  324. // we need to actually load the module using the operating system loader so that its "already loaded" by OS.
  325. {
  326. #if AZ_TRAIT_TEST_SUPPORT_LOADLIBRARY
  327. // expect the module to not currently be loaded.
  328. EXPECT_EQ(nullptr, GetModuleHandleA(finalPath.c_str()));
  329. HMODULE mod = ::LoadLibraryA(finalPath.c_str());
  330. ASSERT_NE(nullptr, mod);
  331. #elif AZ_TRAIT_TEST_SUPPORT_DLOPEN
  332. void* pHandle = dlopen(finalPath.c_str(), RTLD_NOW);
  333. ASSERT_NE(nullptr, pHandle);
  334. #endif
  335. // now that the operating system has an open handle to it, we load it using the
  336. // AZ functions, and make sure that the AZ library correctly attaches even though
  337. // the OS already has it open:
  338. PrintFCollector watchForDestruction("UninitializeDynamicModule called");
  339. PrintFCollector watchForCreation("InitializeDynamicModule called");
  340. {
  341. auto handle = DynamicModuleHandle::Create("AzCoreTestDLL");
  342. handle->Load(true);
  343. EXPECT_TRUE(watchForCreation.m_foundWhatWeWereWatchingFor); // should not destroy until we leave scope.
  344. // steal the file path (which will be resolved with per-platform extensions like DLL or SO.
  345. EXPECT_FALSE(watchForDestruction.m_foundWhatWeWereWatchingFor); // should not destroy until we leave scope.
  346. PrintFCollector watchForCreationSecondTime("InitializeDynamicModule called");
  347. auto handle2 = DynamicModuleHandle::Create("AzCoreTestDLL");
  348. handle2->Load(true);
  349. // this should NOT have initialized it again:
  350. EXPECT_FALSE(watchForCreationSecondTime.m_foundWhatWeWereWatchingFor); // should not destroy until we leave scope.
  351. }
  352. EXPECT_TRUE(watchForDestruction.m_foundWhatWeWereWatchingFor); // we have left scope, destroy should have occurred.
  353. // drop the operating systems attachment to the module:
  354. #if AZ_TRAIT_TEST_SUPPORT_LOADLIBRARY
  355. ::FreeLibrary(mod);
  356. #elif AZ_TRAIT_TEST_SUPPORT_DLOPEN
  357. dlclose(pHandle);
  358. #endif // platform switch statement
  359. }
  360. }
  361. // shut down application (deletes Modules, unloads DLLs)
  362. app.Destroy();
  363. }
  364. #endif // AZ_TRAIT_TEST_SUPPORT_MODULE_LOADING
  365. } // namespace UnitTest
  366. #endif // !AZ_UNIT_TEST_SKIP_DLL_TEST