cmLoadCommandCommand.cxx 7.1 KB

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