cmExportCommand.cxx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmExportCommand.h"
  4. #include "cm_static_string_view.hxx"
  5. #include "cmsys/RegularExpression.hxx"
  6. #include <map>
  7. #include <sstream>
  8. #include <utility>
  9. #include "cmArgumentParser.h"
  10. #include "cmExportBuildAndroidMKGenerator.h"
  11. #include "cmExportBuildFileGenerator.h"
  12. #include "cmExportSetMap.h"
  13. #include "cmGeneratedFileStream.h"
  14. #include "cmGlobalGenerator.h"
  15. #include "cmMakefile.h"
  16. #include "cmMessageType.h"
  17. #include "cmPolicies.h"
  18. #include "cmStateTypes.h"
  19. #include "cmSystemTools.h"
  20. #include "cmTarget.h"
  21. class cmExportSet;
  22. class cmExecutionStatus;
  23. #if defined(__HAIKU__)
  24. # include <FindDirectory.h>
  25. # include <StorageDefs.h>
  26. #endif
  27. bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
  28. cmExecutionStatus&)
  29. {
  30. if (args.size() < 2) {
  31. this->SetError("called with too few arguments");
  32. return false;
  33. }
  34. if (args[0] == "PACKAGE") {
  35. return this->HandlePackage(args);
  36. }
  37. struct Arguments
  38. {
  39. std::string ExportSetName;
  40. std::vector<std::string> Targets;
  41. std::string Namespace;
  42. std::string Filename;
  43. std::string AndroidMKFile;
  44. bool Append = false;
  45. bool ExportOld = false;
  46. };
  47. auto parser = cmArgumentParser<Arguments>{}
  48. .Bind("NAMESPACE"_s, &Arguments::Namespace)
  49. .Bind("FILE"_s, &Arguments::Filename);
  50. if (args[0] == "EXPORT") {
  51. parser.Bind("EXPORT"_s, &Arguments::ExportSetName);
  52. } else {
  53. parser.Bind("TARGETS"_s, &Arguments::Targets);
  54. parser.Bind("ANDROID_MK"_s, &Arguments::AndroidMKFile);
  55. parser.Bind("APPEND"_s, &Arguments::Append);
  56. parser.Bind("EXPORT_LINK_INTERFACE_LIBRARIES"_s, &Arguments::ExportOld);
  57. }
  58. std::vector<std::string> unknownArgs;
  59. Arguments const arguments = parser.Parse(args, &unknownArgs);
  60. if (!unknownArgs.empty()) {
  61. this->SetError("Unknown argument: \"" + unknownArgs.front() + "\".");
  62. return false;
  63. }
  64. std::string fname;
  65. bool android = false;
  66. if (!arguments.AndroidMKFile.empty()) {
  67. fname = arguments.AndroidMKFile;
  68. android = true;
  69. }
  70. if (arguments.Filename.empty() && fname.empty()) {
  71. if (args[0] != "EXPORT") {
  72. this->SetError("FILE <filename> option missing.");
  73. return false;
  74. }
  75. fname = arguments.ExportSetName + ".cmake";
  76. } else if (fname.empty()) {
  77. // Make sure the file has a .cmake extension.
  78. if (cmSystemTools::GetFilenameLastExtension(arguments.Filename) !=
  79. ".cmake") {
  80. std::ostringstream e;
  81. e << "FILE option given filename \"" << arguments.Filename
  82. << "\" which does not have an extension of \".cmake\".\n";
  83. this->SetError(e.str());
  84. return false;
  85. }
  86. fname = arguments.Filename;
  87. }
  88. // Get the file to write.
  89. if (cmSystemTools::FileIsFullPath(fname)) {
  90. if (!this->Makefile->CanIWriteThisFile(fname)) {
  91. std::ostringstream e;
  92. e << "FILE option given filename \"" << fname
  93. << "\" which is in the source tree.\n";
  94. this->SetError(e.str());
  95. return false;
  96. }
  97. } else {
  98. // Interpret relative paths with respect to the current build dir.
  99. std::string dir = this->Makefile->GetCurrentBinaryDirectory();
  100. fname = dir + "/" + fname;
  101. }
  102. std::vector<std::string> targets;
  103. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  104. cmExportSet* ExportSet = nullptr;
  105. if (args[0] == "EXPORT") {
  106. cmExportSetMap& setMap = gg->GetExportSets();
  107. auto const it = setMap.find(arguments.ExportSetName);
  108. if (it == setMap.end()) {
  109. std::ostringstream e;
  110. e << "Export set \"" << arguments.ExportSetName << "\" not found.";
  111. this->SetError(e.str());
  112. return false;
  113. }
  114. ExportSet = it->second;
  115. } else if (!arguments.Targets.empty()) {
  116. for (std::string const& currentTarget : arguments.Targets) {
  117. if (this->Makefile->IsAlias(currentTarget)) {
  118. std::ostringstream e;
  119. e << "given ALIAS target \"" << currentTarget
  120. << "\" which may not be exported.";
  121. this->SetError(e.str());
  122. return false;
  123. }
  124. if (cmTarget* target = gg->FindTarget(currentTarget)) {
  125. if (target->GetType() == cmStateEnums::UTILITY) {
  126. this->SetError("given custom target \"" + currentTarget +
  127. "\" which may not be exported.");
  128. return false;
  129. }
  130. } else {
  131. std::ostringstream e;
  132. e << "given target \"" << currentTarget
  133. << "\" which is not built by this project.";
  134. this->SetError(e.str());
  135. return false;
  136. }
  137. targets.push_back(currentTarget);
  138. }
  139. if (arguments.Append) {
  140. if (cmExportBuildFileGenerator* ebfg =
  141. gg->GetExportedTargetsFile(fname)) {
  142. ebfg->AppendTargets(targets);
  143. return true;
  144. }
  145. }
  146. } else {
  147. this->SetError("EXPORT or TARGETS specifier missing.");
  148. return false;
  149. }
  150. // Setup export file generation.
  151. cmExportBuildFileGenerator* ebfg = nullptr;
  152. if (android) {
  153. ebfg = new cmExportBuildAndroidMKGenerator;
  154. } else {
  155. ebfg = new cmExportBuildFileGenerator;
  156. }
  157. ebfg->SetExportFile(fname.c_str());
  158. ebfg->SetNamespace(arguments.Namespace);
  159. ebfg->SetAppendMode(arguments.Append);
  160. if (ExportSet != nullptr) {
  161. ebfg->SetExportSet(ExportSet);
  162. } else {
  163. ebfg->SetTargets(targets);
  164. }
  165. this->Makefile->AddExportBuildFileGenerator(ebfg);
  166. ebfg->SetExportOld(arguments.ExportOld);
  167. // Compute the set of configurations exported.
  168. std::vector<std::string> configurationTypes;
  169. this->Makefile->GetConfigurations(configurationTypes);
  170. if (configurationTypes.empty()) {
  171. configurationTypes.emplace_back();
  172. }
  173. for (std::string const& ct : configurationTypes) {
  174. ebfg->AddConfiguration(ct);
  175. }
  176. if (ExportSet != nullptr) {
  177. gg->AddBuildExportExportSet(ebfg);
  178. } else {
  179. gg->AddBuildExportSet(ebfg);
  180. }
  181. return true;
  182. }
  183. bool cmExportCommand::HandlePackage(std::vector<std::string> const& args)
  184. {
  185. // Parse PACKAGE mode arguments.
  186. enum Doing
  187. {
  188. DoingNone,
  189. DoingPackage
  190. };
  191. Doing doing = DoingPackage;
  192. std::string package;
  193. for (unsigned int i = 1; i < args.size(); ++i) {
  194. if (doing == DoingPackage) {
  195. package = args[i];
  196. doing = DoingNone;
  197. } else {
  198. std::ostringstream e;
  199. e << "PACKAGE given unknown argument: " << args[i];
  200. this->SetError(e.str());
  201. return false;
  202. }
  203. }
  204. // Verify the package name.
  205. if (package.empty()) {
  206. this->SetError("PACKAGE must be given a package name.");
  207. return false;
  208. }
  209. const char* packageExpr = "^[A-Za-z0-9_.-]+$";
  210. cmsys::RegularExpression packageRegex(packageExpr);
  211. if (!packageRegex.find(package)) {
  212. std::ostringstream e;
  213. e << "PACKAGE given invalid package name \"" << package << "\". "
  214. << "Package names must match \"" << packageExpr << "\".";
  215. this->SetError(e.str());
  216. return false;
  217. }
  218. // CMP0090 decides both the default and what variable changes it.
  219. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0090)) {
  220. case cmPolicies::WARN:
  221. case cmPolicies::OLD:
  222. // Default is to export, but can be disabled.
  223. if (this->Makefile->IsOn("CMAKE_EXPORT_NO_PACKAGE_REGISTRY")) {
  224. return true;
  225. }
  226. break;
  227. case cmPolicies::REQUIRED_IF_USED:
  228. case cmPolicies::REQUIRED_ALWAYS:
  229. case cmPolicies::NEW:
  230. // Default is to not export, but can be enabled.
  231. if (!this->Makefile->IsOn("CMAKE_EXPORT_PACKAGE_REGISTRY")) {
  232. return true;
  233. }
  234. break;
  235. }
  236. // We store the current build directory in the registry as a value
  237. // named by a hash of its own content. This is deterministic and is
  238. // unique with high probability.
  239. const std::string& outDir = this->Makefile->GetCurrentBinaryDirectory();
  240. std::string hash = cmSystemTools::ComputeStringMD5(outDir);
  241. #if defined(_WIN32) && !defined(__CYGWIN__)
  242. this->StorePackageRegistryWin(package, outDir.c_str(), hash.c_str());
  243. #else
  244. this->StorePackageRegistryDir(package, outDir.c_str(), hash.c_str());
  245. #endif
  246. return true;
  247. }
  248. #if defined(_WIN32) && !defined(__CYGWIN__)
  249. # include <windows.h>
  250. void cmExportCommand::ReportRegistryError(std::string const& msg,
  251. std::string const& key, long err)
  252. {
  253. std::ostringstream e;
  254. e << msg << "\n"
  255. << " HKEY_CURRENT_USER\\" << key << "\n";
  256. wchar_t winmsg[1024];
  257. if (FormatMessageW(
  258. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err,
  259. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), winmsg, 1024, 0) > 0) {
  260. e << "Windows reported:\n"
  261. << " " << cmsys::Encoding::ToNarrow(winmsg);
  262. }
  263. this->Makefile->IssueMessage(MessageType::WARNING, e.str());
  264. }
  265. void cmExportCommand::StorePackageRegistryWin(std::string const& package,
  266. const char* content,
  267. const char* hash)
  268. {
  269. std::string key = "Software\\Kitware\\CMake\\Packages\\";
  270. key += package;
  271. HKEY hKey;
  272. LONG err =
  273. RegCreateKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(key).c_str(), 0,
  274. 0, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, 0, &hKey, 0);
  275. if (err != ERROR_SUCCESS) {
  276. this->ReportRegistryError("Cannot create/open registry key", key, err);
  277. return;
  278. }
  279. std::wstring wcontent = cmsys::Encoding::ToWide(content);
  280. err =
  281. RegSetValueExW(hKey, cmsys::Encoding::ToWide(hash).c_str(), 0, REG_SZ,
  282. (BYTE const*)wcontent.c_str(),
  283. static_cast<DWORD>(wcontent.size() + 1) * sizeof(wchar_t));
  284. RegCloseKey(hKey);
  285. if (err != ERROR_SUCCESS) {
  286. std::ostringstream msg;
  287. msg << "Cannot set registry value \"" << hash << "\" under key";
  288. this->ReportRegistryError(msg.str(), key, err);
  289. return;
  290. }
  291. }
  292. #else
  293. void cmExportCommand::StorePackageRegistryDir(std::string const& package,
  294. const char* content,
  295. const char* hash)
  296. {
  297. # if defined(__HAIKU__)
  298. char dir[B_PATH_NAME_LENGTH];
  299. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) !=
  300. B_OK) {
  301. return;
  302. }
  303. std::string fname = dir;
  304. fname += "/cmake/packages/";
  305. fname += package;
  306. # else
  307. std::string fname;
  308. if (!cmSystemTools::GetEnv("HOME", fname)) {
  309. return;
  310. }
  311. cmSystemTools::ConvertToUnixSlashes(fname);
  312. fname += "/.cmake/packages/";
  313. fname += package;
  314. # endif
  315. cmSystemTools::MakeDirectory(fname);
  316. fname += "/";
  317. fname += hash;
  318. if (!cmSystemTools::FileExists(fname)) {
  319. cmGeneratedFileStream entry(fname, true);
  320. if (entry) {
  321. entry << content << "\n";
  322. } else {
  323. std::ostringstream e;
  324. /* clang-format off */
  325. e << "Cannot create package registry file:\n"
  326. << " " << fname << "\n"
  327. << cmSystemTools::GetLastSystemError() << "\n";
  328. /* clang-format on */
  329. this->Makefile->IssueMessage(MessageType::WARNING, e.str());
  330. }
  331. }
  332. }
  333. #endif