cmExportCommand.cxx 12 KB

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