cmExportCommand.cxx 11 KB

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