cmExportCommand.cxx 12 KB

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