cmExportCommand.cxx 12 KB

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