cmExportCommand.cxx 11 KB

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