cmExportCommand.cxx 11 KB

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