cmLoadCommandCommand.cxx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #if !defined(_WIN32) && !defined(__sun) && !defined(__OpenBSD__)
  4. // POSIX APIs are needed
  5. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  6. # define _POSIX_C_SOURCE 200809L
  7. #endif
  8. #if defined(__FreeBSD__) || defined(__NetBSD__)
  9. // For isascii
  10. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  11. # define _XOPEN_SOURCE 700
  12. #endif
  13. #include "cmLoadCommandCommand.h"
  14. #include <csignal>
  15. #include <cstdio>
  16. #include <cstdlib>
  17. #include <cstring>
  18. #include <utility>
  19. #include <cm/memory>
  20. #include "cmCPluginAPI.h"
  21. #include "cmCommand.h"
  22. #include "cmDynamicLoader.h"
  23. #include "cmExecutionStatus.h"
  24. #include "cmListFileCache.h"
  25. #include "cmLocalGenerator.h"
  26. #include "cmMakefile.h"
  27. #include "cmState.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. // NOLINTNEXTLINE(bugprone-suspicious-include)
  31. #include "cmCPluginAPI.cxx"
  32. #ifdef __QNX__
  33. # include <malloc.h> /* for malloc/free on QNX */
  34. #endif
  35. namespace {
  36. const char* LastName = nullptr;
  37. extern "C" void TrapsForSignals(int sig);
  38. extern "C" void TrapsForSignals(int sig)
  39. {
  40. fprintf(stderr, "CMake loaded command %s crashed with signal: %d.\n",
  41. LastName, sig);
  42. }
  43. struct SignalHandlerGuard
  44. {
  45. explicit SignalHandlerGuard(const char* name)
  46. {
  47. LastName = name ? name : "????";
  48. signal(SIGSEGV, TrapsForSignals);
  49. #ifdef SIGBUS
  50. signal(SIGBUS, TrapsForSignals);
  51. #endif
  52. signal(SIGILL, TrapsForSignals);
  53. }
  54. ~SignalHandlerGuard()
  55. {
  56. signal(SIGSEGV, nullptr);
  57. #ifdef SIGBUS
  58. signal(SIGBUS, nullptr);
  59. #endif
  60. signal(SIGILL, nullptr);
  61. }
  62. SignalHandlerGuard(SignalHandlerGuard const&) = delete;
  63. SignalHandlerGuard& operator=(SignalHandlerGuard const&) = delete;
  64. };
  65. struct LoadedCommandImpl : cmLoadedCommandInfo
  66. {
  67. explicit LoadedCommandImpl(CM_INIT_FUNCTION init)
  68. : cmLoadedCommandInfo{ 0, 0, &cmStaticCAPI, 0,
  69. nullptr, nullptr, nullptr, nullptr,
  70. nullptr, nullptr, nullptr, nullptr }
  71. {
  72. init(this);
  73. }
  74. ~LoadedCommandImpl()
  75. {
  76. if (this->Destructor) {
  77. SignalHandlerGuard guard(this->Name);
  78. #if defined(__NVCOMPILER) || defined(__LCC__)
  79. static_cast<void>(guard); // convince compiler var is used
  80. #endif
  81. this->Destructor(this);
  82. }
  83. if (this->Error) {
  84. free(this->Error);
  85. }
  86. }
  87. LoadedCommandImpl(LoadedCommandImpl const&) = delete;
  88. LoadedCommandImpl& operator=(LoadedCommandImpl const&) = delete;
  89. int DoInitialPass(cmMakefile* mf, int argc, char* argv[])
  90. {
  91. SignalHandlerGuard guard(this->Name);
  92. #if defined(__NVCOMPILER) || defined(__LCC__)
  93. static_cast<void>(guard); // convince compiler var is used
  94. #endif
  95. return this->InitialPass(this, mf, argc, argv);
  96. }
  97. void DoFinalPass(cmMakefile* mf)
  98. {
  99. SignalHandlerGuard guard(this->Name);
  100. #if defined(__NVCOMPILER) || defined(__LCC__)
  101. static_cast<void>(guard); // convince compiler var is used
  102. #endif
  103. this->FinalPass(this, mf);
  104. }
  105. };
  106. // a class for loadabple commands
  107. class cmLoadedCommand : public cmCommand
  108. {
  109. public:
  110. cmLoadedCommand() = default;
  111. explicit cmLoadedCommand(CM_INIT_FUNCTION init)
  112. : Impl(std::make_shared<LoadedCommandImpl>(init))
  113. {
  114. }
  115. /**
  116. * This is a virtual constructor for the command.
  117. */
  118. std::unique_ptr<cmCommand> Clone() override
  119. {
  120. auto newC = cm::make_unique<cmLoadedCommand>();
  121. // we must copy when we clone
  122. newC->Impl = this->Impl;
  123. return std::unique_ptr<cmCommand>(std::move(newC));
  124. }
  125. /**
  126. * This is called when the command is first encountered in
  127. * the CMakeLists.txt file.
  128. */
  129. bool InitialPass(std::vector<std::string> const& args,
  130. cmExecutionStatus&) override;
  131. private:
  132. std::shared_ptr<LoadedCommandImpl> Impl;
  133. };
  134. bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args,
  135. cmExecutionStatus&)
  136. {
  137. if (!this->Impl->InitialPass) {
  138. return true;
  139. }
  140. // clear the error string
  141. if (this->Impl->Error) {
  142. free(this->Impl->Error);
  143. }
  144. // create argc and argv and then invoke the command
  145. int argc = static_cast<int>(args.size());
  146. char** argv = nullptr;
  147. if (argc) {
  148. argv = static_cast<char**>(malloc(argc * sizeof(char*)));
  149. }
  150. int i;
  151. for (i = 0; i < argc; ++i) {
  152. argv[i] = strdup(args[i].c_str());
  153. }
  154. int result = this->Impl->DoInitialPass(this->Makefile, argc, argv);
  155. cmFreeArguments(argc, argv);
  156. if (result) {
  157. if (this->Impl->FinalPass) {
  158. auto impl = this->Impl;
  159. this->Makefile->AddGeneratorAction(
  160. [impl](cmLocalGenerator& lg, const cmListFileBacktrace&) {
  161. impl->DoFinalPass(lg.GetMakefile());
  162. });
  163. }
  164. return true;
  165. }
  166. /* Initial Pass must have failed so set the error string */
  167. if (this->Impl->Error) {
  168. this->SetError(this->Impl->Error);
  169. }
  170. return false;
  171. }
  172. } // namespace
  173. // cmLoadCommandCommand
  174. bool cmLoadCommandCommand(std::vector<std::string> const& args,
  175. cmExecutionStatus& status)
  176. {
  177. if (args.empty()) {
  178. return true;
  179. }
  180. // Construct a variable to report what file was loaded, if any.
  181. // Start by removing the definition in case of failure.
  182. std::string reportVar = cmStrCat("CMAKE_LOADED_COMMAND_", args[0]);
  183. status.GetMakefile().RemoveDefinition(reportVar);
  184. // the file must exist
  185. std::string moduleName = cmStrCat(
  186. status.GetMakefile().GetRequiredDefinition("CMAKE_SHARED_MODULE_PREFIX"),
  187. "cm", args[0],
  188. status.GetMakefile().GetRequiredDefinition("CMAKE_SHARED_MODULE_SUFFIX"));
  189. // search for the file
  190. std::vector<std::string> path;
  191. for (unsigned int j = 1; j < args.size(); j++) {
  192. // expand variables
  193. std::string exp = args[j];
  194. cmSystemTools::ExpandRegistryValues(exp);
  195. // Glob the entry in case of wildcards.
  196. cmSystemTools::GlobDirs(exp, path);
  197. }
  198. // Try to find the program.
  199. std::string fullPath = cmSystemTools::FindFile(moduleName, path);
  200. if (fullPath.empty()) {
  201. status.SetError(cmStrCat("Attempt to load command failed from file \"",
  202. moduleName, "\""));
  203. return false;
  204. }
  205. // try loading the shared library / dll
  206. cmsys::DynamicLoader::LibraryHandle lib =
  207. cmDynamicLoader::OpenLibrary(fullPath.c_str());
  208. if (!lib) {
  209. std::string err =
  210. cmStrCat("Attempt to load the library ", fullPath, " failed.");
  211. const char* error = cmsys::DynamicLoader::LastError();
  212. if (error) {
  213. err += " Additional error info is:\n";
  214. err += error;
  215. }
  216. status.SetError(err);
  217. return false;
  218. }
  219. // Report what file was loaded for this command.
  220. status.GetMakefile().AddDefinition(reportVar, fullPath);
  221. // find the init function
  222. std::string initFuncName = args[0] + "Init";
  223. CM_INIT_FUNCTION initFunction = reinterpret_cast<CM_INIT_FUNCTION>(
  224. cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName));
  225. if (!initFunction) {
  226. initFuncName = cmStrCat('_', args[0], "Init");
  227. initFunction = reinterpret_cast<CM_INIT_FUNCTION>(
  228. cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName));
  229. }
  230. // if the symbol is found call it to set the name on the
  231. // function blocker
  232. if (initFunction) {
  233. return status.GetMakefile().GetState()->AddScriptedCommand(
  234. args[0],
  235. BT<cmState::Command>(
  236. cmLegacyCommandWrapper(cm::make_unique<cmLoadedCommand>(initFunction)),
  237. status.GetMakefile().GetBacktrace()),
  238. status.GetMakefile());
  239. }
  240. status.SetError("Attempt to load command failed. "
  241. "No init function found.");
  242. return false;
  243. }