cmExportCommand.cxx 11 KB

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