cmGlobalVisualStudioGenerator.cxx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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 "cmGlobalVisualStudioGenerator.h"
  4. #include <cassert>
  5. #include <future>
  6. #include <iostream>
  7. #include <sstream>
  8. #include <system_error>
  9. #include <utility>
  10. #include <cm/iterator>
  11. #include <cm/memory>
  12. #include <cmext/string_view>
  13. #include <windows.h>
  14. #include <objbase.h>
  15. #include <shellapi.h>
  16. #include "cmCallVisualStudioMacro.h"
  17. #include "cmCustomCommand.h"
  18. #include "cmCustomCommandLines.h"
  19. #include "cmGeneratedFileStream.h"
  20. #include "cmGeneratorTarget.h"
  21. #include "cmLocalGenerator.h"
  22. #include "cmMakefile.h"
  23. #include "cmMessageType.h"
  24. #include "cmPolicies.h"
  25. #include "cmSourceFile.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. #include "cmTarget.h"
  31. #include "cmake.h"
  32. cmGlobalVisualStudioGenerator::cmGlobalVisualStudioGenerator(
  33. cmake* cm, std::string const& platformInGeneratorName)
  34. : cmGlobalGenerator(cm)
  35. {
  36. cm->GetState()->SetIsGeneratorMultiConfig(true);
  37. cm->GetState()->SetWindowsShell(true);
  38. cm->GetState()->SetWindowsVSIDE(true);
  39. if (platformInGeneratorName.empty()) {
  40. this->DefaultPlatformName = "Win32";
  41. } else {
  42. this->DefaultPlatformName = platformInGeneratorName;
  43. this->PlatformInGeneratorName = true;
  44. }
  45. }
  46. cmGlobalVisualStudioGenerator::~cmGlobalVisualStudioGenerator() = default;
  47. cmGlobalVisualStudioGenerator::VSVersion
  48. cmGlobalVisualStudioGenerator::GetVersion() const
  49. {
  50. return this->Version;
  51. }
  52. void cmGlobalVisualStudioGenerator::SetVersion(VSVersion v)
  53. {
  54. this->Version = v;
  55. }
  56. void cmGlobalVisualStudioGenerator::EnableLanguage(
  57. std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
  58. {
  59. mf->AddDefinition("CMAKE_VS_PLATFORM_NAME_DEFAULT",
  60. this->DefaultPlatformName);
  61. this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
  62. }
  63. bool cmGlobalVisualStudioGenerator::SetGeneratorPlatform(std::string const& p,
  64. cmMakefile* mf)
  65. {
  66. if (!this->InitializePlatform(mf)) {
  67. return false;
  68. }
  69. if (this->GetPlatformName() == "x64"_s) {
  70. mf->AddDefinition("CMAKE_FORCE_WIN64", "TRUE");
  71. } else if (this->GetPlatformName() == "Itanium"_s) {
  72. mf->AddDefinition("CMAKE_FORCE_IA64", "TRUE");
  73. }
  74. mf->AddDefinition("CMAKE_VS_PLATFORM_NAME", this->GetPlatformName());
  75. return this->cmGlobalGenerator::SetGeneratorPlatform(p, mf);
  76. }
  77. bool cmGlobalVisualStudioGenerator::InitializePlatform(cmMakefile*)
  78. {
  79. return true;
  80. }
  81. std::string const& cmGlobalVisualStudioGenerator::GetPlatformName() const
  82. {
  83. if (!this->GeneratorPlatform.empty()) {
  84. return this->GeneratorPlatform;
  85. }
  86. return this->DefaultPlatformName;
  87. }
  88. const char* cmGlobalVisualStudioGenerator::GetIDEVersion() const
  89. {
  90. switch (this->Version) {
  91. case cmGlobalVisualStudioGenerator::VSVersion::VS9:
  92. return "9.0";
  93. case cmGlobalVisualStudioGenerator::VSVersion::VS12:
  94. return "12.0";
  95. case cmGlobalVisualStudioGenerator::VSVersion::VS14:
  96. return "14.0";
  97. case cmGlobalVisualStudioGenerator::VSVersion::VS15:
  98. return "15.0";
  99. case cmGlobalVisualStudioGenerator::VSVersion::VS16:
  100. return "16.0";
  101. case cmGlobalVisualStudioGenerator::VSVersion::VS17:
  102. return "17.0";
  103. }
  104. return "";
  105. }
  106. void cmGlobalVisualStudioGenerator::WriteSLNHeader(std::ostream& fout)
  107. {
  108. char utf8bom[] = { char(0xEF), char(0xBB), char(0xBF) };
  109. fout.write(utf8bom, 3);
  110. fout << '\n';
  111. switch (this->Version) {
  112. case cmGlobalVisualStudioGenerator::VSVersion::VS9:
  113. fout << "Microsoft Visual Studio Solution File, Format Version 10.00\n";
  114. fout << "# Visual Studio 2008\n";
  115. break;
  116. case cmGlobalVisualStudioGenerator::VSVersion::VS12:
  117. fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
  118. if (this->ExpressEdition) {
  119. fout << "# Visual Studio Express 2013 for Windows Desktop\n";
  120. } else {
  121. fout << "# Visual Studio 2013\n";
  122. }
  123. break;
  124. case cmGlobalVisualStudioGenerator::VSVersion::VS14:
  125. // Visual Studio 14 writes .sln format 12.00
  126. fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
  127. if (this->ExpressEdition) {
  128. fout << "# Visual Studio Express 14 for Windows Desktop\n";
  129. } else {
  130. fout << "# Visual Studio 14\n";
  131. }
  132. break;
  133. case cmGlobalVisualStudioGenerator::VSVersion::VS15:
  134. // Visual Studio 15 writes .sln format 12.00
  135. fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
  136. if (this->ExpressEdition) {
  137. fout << "# Visual Studio Express 15 for Windows Desktop\n";
  138. } else {
  139. fout << "# Visual Studio 15\n";
  140. }
  141. break;
  142. case cmGlobalVisualStudioGenerator::VSVersion::VS16:
  143. // Visual Studio 16 writes .sln format 12.00
  144. fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
  145. if (this->ExpressEdition) {
  146. fout << "# Visual Studio Express 16 for Windows Desktop\n";
  147. } else {
  148. fout << "# Visual Studio Version 16\n";
  149. }
  150. break;
  151. case cmGlobalVisualStudioGenerator::VSVersion::VS17:
  152. // Visual Studio 17 writes .sln format 12.00
  153. fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
  154. if (this->ExpressEdition) {
  155. fout << "# Visual Studio Express 17 for Windows Desktop\n";
  156. } else {
  157. fout << "# Visual Studio Version 17\n";
  158. }
  159. break;
  160. }
  161. }
  162. std::string cmGlobalVisualStudioGenerator::GetRegistryBase()
  163. {
  164. return cmGlobalVisualStudioGenerator::GetRegistryBase(this->GetIDEVersion());
  165. }
  166. std::string cmGlobalVisualStudioGenerator::GetRegistryBase(const char* version)
  167. {
  168. return cmStrCat(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\)",
  169. version);
  170. }
  171. void cmGlobalVisualStudioGenerator::AddExtraIDETargets()
  172. {
  173. // Add a special target that depends on ALL projects for easy build
  174. // of one configuration only.
  175. for (auto const& it : this->ProjectMap) {
  176. std::vector<cmLocalGenerator*> const& gen = it.second;
  177. // add the ALL_BUILD to the first local generator of each project
  178. if (!gen.empty()) {
  179. // Use no actual command lines so that the target itself is not
  180. // considered always out of date.
  181. auto cc = cm::make_unique<cmCustomCommand>();
  182. cc->SetEscapeOldStyle(false);
  183. cc->SetComment("Build all projects");
  184. cmTarget* allBuild =
  185. gen[0]->AddUtilityCommand("ALL_BUILD", true, std::move(cc));
  186. gen[0]->AddGeneratorTarget(
  187. cm::make_unique<cmGeneratorTarget>(allBuild, gen[0]));
  188. //
  189. // Organize in the "predefined targets" folder:
  190. //
  191. if (this->UseFolderProperty()) {
  192. allBuild->SetProperty("FOLDER", this->GetPredefinedTargetsFolder());
  193. }
  194. // Now make all targets depend on the ALL_BUILD target
  195. for (cmLocalGenerator const* i : gen) {
  196. for (const auto& tgt : i->GetGeneratorTargets()) {
  197. if (tgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  198. tgt->IsImported()) {
  199. continue;
  200. }
  201. if (!this->IsExcluded(gen[0], tgt.get())) {
  202. allBuild->AddUtility(tgt->GetName(), false);
  203. }
  204. }
  205. }
  206. }
  207. }
  208. // Configure CMake Visual Studio macros, for this user on this version
  209. // of Visual Studio.
  210. this->ConfigureCMakeVisualStudioMacros();
  211. }
  212. void cmGlobalVisualStudioGenerator::ComputeTargetObjectDirectory(
  213. cmGeneratorTarget* gt) const
  214. {
  215. std::string dir =
  216. cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), '/');
  217. std::string tgtDir = gt->LocalGenerator->GetTargetDirectory(gt);
  218. if (!tgtDir.empty()) {
  219. dir += tgtDir;
  220. dir += '/';
  221. }
  222. const char* cd = this->GetCMakeCFGIntDir();
  223. if (cd && *cd) {
  224. dir += cd;
  225. dir += '/';
  226. }
  227. gt->ObjectDirectory = dir;
  228. }
  229. bool IsVisualStudioMacrosFileRegistered(const std::string& macrosFile,
  230. const std::string& regKeyBase,
  231. std::string& nextAvailableSubKeyName);
  232. void RegisterVisualStudioMacros(const std::string& macrosFile,
  233. const std::string& regKeyBase);
  234. #define CMAKE_VSMACROS_FILENAME "CMakeVSMacros2.vsmacros"
  235. #define CMAKE_VSMACROS_RELOAD_MACRONAME \
  236. "Macros.CMakeVSMacros2.Macros.ReloadProjects"
  237. #define CMAKE_VSMACROS_STOP_MACRONAME "Macros.CMakeVSMacros2.Macros.StopBuild"
  238. void cmGlobalVisualStudioGenerator::ConfigureCMakeVisualStudioMacros()
  239. {
  240. std::string dir = this->GetUserMacrosDirectory();
  241. if (!dir.empty()) {
  242. std::string src = cmStrCat(cmSystemTools::GetCMakeRoot(),
  243. "/Templates/" CMAKE_VSMACROS_FILENAME);
  244. std::string dst = cmStrCat(dir, "/CMakeMacros/" CMAKE_VSMACROS_FILENAME);
  245. // Copy the macros file to the user directory only if the
  246. // destination does not exist or the source location is newer.
  247. // This will allow the user to edit the macros for development
  248. // purposes but newer versions distributed with CMake will replace
  249. // older versions in user directories.
  250. int res;
  251. if (!cmSystemTools::FileTimeCompare(src, dst, &res) || res > 0) {
  252. if (!cmSystemTools::CopyFileAlways(src, dst)) {
  253. std::ostringstream oss;
  254. oss << "Could not copy from: " << src << std::endl
  255. << " to: " << dst << std::endl;
  256. cmSystemTools::Message(oss.str(), "Warning");
  257. }
  258. }
  259. RegisterVisualStudioMacros(dst, this->GetUserMacrosRegKeyBase());
  260. }
  261. }
  262. void cmGlobalVisualStudioGenerator::CallVisualStudioMacro(
  263. MacroName m, const std::string& vsSolutionFile)
  264. {
  265. // If any solution or project files changed during the generation,
  266. // tell Visual Studio to reload them...
  267. std::string dir = this->GetUserMacrosDirectory();
  268. // Only really try to call the macro if:
  269. // - there is a UserMacrosDirectory
  270. // - the CMake vsmacros file exists
  271. // - the CMake vsmacros file is registered
  272. // - there were .sln/.vcproj files changed during generation
  273. //
  274. if (!dir.empty()) {
  275. std::string macrosFile =
  276. cmStrCat(dir, "/CMakeMacros/" CMAKE_VSMACROS_FILENAME);
  277. std::string nextSubkeyName;
  278. if (cmSystemTools::FileExists(macrosFile) &&
  279. IsVisualStudioMacrosFileRegistered(
  280. macrosFile, this->GetUserMacrosRegKeyBase(), nextSubkeyName)) {
  281. if (m == MacroReload) {
  282. std::vector<std::string> filenames;
  283. this->GetFilesReplacedDuringGenerate(filenames);
  284. if (!filenames.empty()) {
  285. std::string projects = cmJoin(filenames, ";");
  286. cmCallVisualStudioMacro::CallMacro(
  287. vsSolutionFile, CMAKE_VSMACROS_RELOAD_MACRONAME, projects,
  288. this->GetCMakeInstance()->GetDebugOutput());
  289. }
  290. } else if (m == MacroStop) {
  291. cmCallVisualStudioMacro::CallMacro(
  292. vsSolutionFile, CMAKE_VSMACROS_STOP_MACRONAME, "",
  293. this->GetCMakeInstance()->GetDebugOutput());
  294. }
  295. }
  296. }
  297. }
  298. std::string cmGlobalVisualStudioGenerator::GetUserMacrosDirectory()
  299. {
  300. return "";
  301. }
  302. std::string cmGlobalVisualStudioGenerator::GetUserMacrosRegKeyBase()
  303. {
  304. return "";
  305. }
  306. void cmGlobalVisualStudioGenerator::FillLinkClosure(
  307. const cmGeneratorTarget* target, TargetSet& linked)
  308. {
  309. if (linked.insert(target).second) {
  310. TargetDependSet const& depends = this->GetTargetDirectDepends(target);
  311. for (cmTargetDepend const& di : depends) {
  312. if (di.IsLink()) {
  313. this->FillLinkClosure(di, linked);
  314. }
  315. }
  316. }
  317. }
  318. cmGlobalVisualStudioGenerator::TargetSet const&
  319. cmGlobalVisualStudioGenerator::GetTargetLinkClosure(cmGeneratorTarget* target)
  320. {
  321. auto i = this->TargetLinkClosure.find(target);
  322. if (i == this->TargetLinkClosure.end()) {
  323. TargetSetMap::value_type entry(target, TargetSet());
  324. i = this->TargetLinkClosure.insert(entry).first;
  325. this->FillLinkClosure(target, i->second);
  326. }
  327. return i->second;
  328. }
  329. void cmGlobalVisualStudioGenerator::FollowLinkDepends(
  330. const cmGeneratorTarget* target, std::set<const cmGeneratorTarget*>& linked)
  331. {
  332. if (!target->IsInBuildSystem()) {
  333. return;
  334. }
  335. if (linked.insert(target).second &&
  336. target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  337. // Static library targets do not list their link dependencies so
  338. // we must follow them transitively now.
  339. TargetDependSet const& depends = this->GetTargetDirectDepends(target);
  340. for (cmTargetDepend const& di : depends) {
  341. if (di.IsLink()) {
  342. this->FollowLinkDepends(di, linked);
  343. }
  344. }
  345. }
  346. }
  347. bool cmGlobalVisualStudioGenerator::ComputeTargetDepends()
  348. {
  349. if (!this->cmGlobalGenerator::ComputeTargetDepends()) {
  350. return false;
  351. }
  352. for (auto const& it : this->ProjectMap) {
  353. for (const cmLocalGenerator* i : it.second) {
  354. for (const auto& ti : i->GetGeneratorTargets()) {
  355. this->ComputeVSTargetDepends(ti.get());
  356. }
  357. }
  358. }
  359. return true;
  360. }
  361. static bool VSLinkable(cmGeneratorTarget const* t)
  362. {
  363. return t->IsLinkable() || t->GetType() == cmStateEnums::OBJECT_LIBRARY;
  364. }
  365. void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
  366. cmGeneratorTarget* target)
  367. {
  368. if (this->VSTargetDepends.find(target) != this->VSTargetDepends.end()) {
  369. return;
  370. }
  371. VSDependSet& vsTargetDepend = this->VSTargetDepends[target];
  372. // VS <= 7.1 has two behaviors that affect solution dependencies.
  373. //
  374. // (1) Solution-level dependencies between a linkable target and a
  375. // library cause that library to be linked. We use an intermedite
  376. // empty utility target to express the dependency. (VS 8 and above
  377. // provide a project file "LinkLibraryDependencies" setting to
  378. // choose whether to activate this behavior. We disable it except
  379. // when linking external project files.)
  380. //
  381. // (2) We cannot let static libraries depend directly on targets to
  382. // which they "link" because the librarian tool will copy the
  383. // targets into the static library. While the work-around for
  384. // behavior (1) would also avoid this, it would create a large
  385. // number of extra utility targets for little gain. Instead, use
  386. // the above work-around only for dependencies explicitly added by
  387. // the add_dependencies() command. Approximate link dependencies by
  388. // leaving them out for the static library itself but following them
  389. // transitively for other targets.
  390. bool allowLinkable = (target->GetType() != cmStateEnums::STATIC_LIBRARY &&
  391. target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  392. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  393. target->GetType() != cmStateEnums::EXECUTABLE);
  394. TargetDependSet const& depends = this->GetTargetDirectDepends(target);
  395. // Collect implicit link dependencies (target_link_libraries).
  396. // Static libraries cannot depend on their link implementation
  397. // due to behavior (2), but they do not really need to.
  398. std::set<cmGeneratorTarget const*> linkDepends;
  399. if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  400. for (cmTargetDepend const& di : depends) {
  401. if (di.IsLink()) {
  402. this->FollowLinkDepends(di, linkDepends);
  403. }
  404. }
  405. }
  406. // Collect explicit util dependencies (add_dependencies).
  407. std::set<cmGeneratorTarget const*> utilDepends;
  408. for (cmTargetDepend const& di : depends) {
  409. if (di.IsUtil()) {
  410. this->FollowLinkDepends(di, utilDepends);
  411. }
  412. }
  413. // Collect all targets linked by this target so we can avoid
  414. // intermediate targets below.
  415. TargetSet linked;
  416. if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  417. linked = this->GetTargetLinkClosure(target);
  418. }
  419. // Emit link dependencies.
  420. for (cmGeneratorTarget const* dep : linkDepends) {
  421. vsTargetDepend.insert(dep->GetName());
  422. }
  423. // Emit util dependencies. Possibly use intermediate targets.
  424. for (cmGeneratorTarget const* dgt : utilDepends) {
  425. if (allowLinkable || !VSLinkable(dgt) || linked.count(dgt)) {
  426. // Direct dependency allowed.
  427. vsTargetDepend.insert(dgt->GetName());
  428. } else {
  429. // Direct dependency on linkable target not allowed.
  430. // Use an intermediate utility target.
  431. vsTargetDepend.insert(this->GetUtilityDepend(dgt));
  432. }
  433. }
  434. }
  435. bool cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
  436. {
  437. // Visual Studio generators know how to lookup their build tool
  438. // directly instead of needing a helper module to do it, so we
  439. // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
  440. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  441. mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetVSMakeProgram());
  442. }
  443. return true;
  444. }
  445. std::string cmGlobalVisualStudioGenerator::GetUtilityDepend(
  446. cmGeneratorTarget const* target)
  447. {
  448. auto i = this->UtilityDepends.find(target);
  449. if (i == this->UtilityDepends.end()) {
  450. std::string name = this->WriteUtilityDepend(target);
  451. UtilityDependsMap::value_type entry(target, name);
  452. i = this->UtilityDepends.insert(entry).first;
  453. }
  454. return i->second;
  455. }
  456. std::string cmGlobalVisualStudioGenerator::GetStartupProjectName(
  457. cmLocalGenerator const* root) const
  458. {
  459. cmValue n = root->GetMakefile()->GetProperty("VS_STARTUP_PROJECT");
  460. if (cmNonempty(n)) {
  461. std::string startup = *n;
  462. if (this->FindTarget(startup)) {
  463. return startup;
  464. }
  465. root->GetMakefile()->IssueMessage(
  466. MessageType::AUTHOR_WARNING,
  467. cmStrCat("Directory property VS_STARTUP_PROJECT specifies target "
  468. "'",
  469. startup, "' that does not exist. Ignoring."));
  470. }
  471. // default, if not specified
  472. return this->GetAllTargetName();
  473. }
  474. bool IsVisualStudioMacrosFileRegistered(const std::string& macrosFile,
  475. const std::string& regKeyBase,
  476. std::string& nextAvailableSubKeyName)
  477. {
  478. bool macrosRegistered = false;
  479. std::string s1;
  480. std::string s2;
  481. // Make lowercase local copies, convert to Unix slashes, and
  482. // see if the resulting strings are the same:
  483. s1 = cmSystemTools::LowerCase(macrosFile);
  484. cmSystemTools::ConvertToUnixSlashes(s1);
  485. std::string keyname;
  486. HKEY hkey = nullptr;
  487. LONG result = ERROR_SUCCESS;
  488. DWORD index = 0;
  489. keyname = cmStrCat(regKeyBase, "\\OtherProjects7");
  490. hkey = nullptr;
  491. result =
  492. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  493. 0, KEY_READ, &hkey);
  494. if (ERROR_SUCCESS == result) {
  495. // Iterate the subkeys and look for the values of interest in each subkey:
  496. wchar_t subkeyname[256];
  497. DWORD cch_subkeyname = cm::size(subkeyname);
  498. wchar_t keyclass[256];
  499. DWORD cch_keyclass = cm::size(keyclass);
  500. FILETIME lastWriteTime;
  501. lastWriteTime.dwHighDateTime = 0;
  502. lastWriteTime.dwLowDateTime = 0;
  503. while (ERROR_SUCCESS ==
  504. RegEnumKeyExW(hkey, index, subkeyname, &cch_subkeyname, 0, keyclass,
  505. &cch_keyclass, &lastWriteTime)) {
  506. // Open the subkey and query the values of interest:
  507. HKEY hsubkey = nullptr;
  508. result = RegOpenKeyExW(hkey, subkeyname, 0, KEY_READ, &hsubkey);
  509. if (ERROR_SUCCESS == result) {
  510. DWORD valueType = REG_SZ;
  511. wchar_t data1[256];
  512. DWORD cch_data1 = sizeof(data1);
  513. RegQueryValueExW(hsubkey, L"Path", 0, &valueType, (LPBYTE)data1,
  514. &cch_data1);
  515. DWORD data2 = 0;
  516. DWORD cch_data2 = sizeof(data2);
  517. RegQueryValueExW(hsubkey, L"Security", 0, &valueType, (LPBYTE)&data2,
  518. &cch_data2);
  519. DWORD data3 = 0;
  520. DWORD cch_data3 = sizeof(data3);
  521. RegQueryValueExW(hsubkey, L"StorageFormat", 0, &valueType,
  522. (LPBYTE)&data3, &cch_data3);
  523. s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
  524. cmSystemTools::ConvertToUnixSlashes(s2);
  525. if (s2 == s1) {
  526. macrosRegistered = true;
  527. }
  528. std::string fullname = cmsys::Encoding::ToNarrow(data1);
  529. std::string filename;
  530. std::string filepath;
  531. std::string filepathname;
  532. std::string filepathpath;
  533. if (cmSystemTools::FileExists(fullname)) {
  534. filename = cmSystemTools::GetFilenameName(fullname);
  535. filepath = cmSystemTools::GetFilenamePath(fullname);
  536. filepathname = cmSystemTools::GetFilenameName(filepath);
  537. filepathpath = cmSystemTools::GetFilenamePath(filepath);
  538. }
  539. // std::cout << keyname << "\\" << subkeyname << ":" << std::endl;
  540. // std::cout << " Path: " << data1 << std::endl;
  541. // std::cout << " Security: " << data2 << std::endl;
  542. // std::cout << " StorageFormat: " << data3 << std::endl;
  543. // std::cout << " filename: " << filename << std::endl;
  544. // std::cout << " filepath: " << filepath << std::endl;
  545. // std::cout << " filepathname: " << filepathname << std::endl;
  546. // std::cout << " filepathpath: " << filepathpath << std::endl;
  547. // std::cout << std::endl;
  548. RegCloseKey(hsubkey);
  549. } else {
  550. std::cout << "error opening subkey: "
  551. << cmsys::Encoding::ToNarrow(subkeyname) << std::endl;
  552. std::cout << std::endl;
  553. }
  554. ++index;
  555. cch_subkeyname = cm::size(subkeyname);
  556. cch_keyclass = cm::size(keyclass);
  557. lastWriteTime.dwHighDateTime = 0;
  558. lastWriteTime.dwLowDateTime = 0;
  559. }
  560. RegCloseKey(hkey);
  561. } else {
  562. std::cout << "error opening key: " << keyname << std::endl;
  563. std::cout << std::endl;
  564. }
  565. // Pass back next available sub key name, assuming sub keys always
  566. // follow the expected naming scheme. Expected naming scheme is that
  567. // the subkeys of OtherProjects7 is 0 to n-1, so it's ok to use "n"
  568. // as the name of the next subkey.
  569. nextAvailableSubKeyName = std::to_string(index);
  570. keyname = cmStrCat(regKeyBase, "\\RecordingProject7");
  571. hkey = nullptr;
  572. result =
  573. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  574. 0, KEY_READ, &hkey);
  575. if (ERROR_SUCCESS == result) {
  576. DWORD valueType = REG_SZ;
  577. wchar_t data1[256];
  578. DWORD cch_data1 = sizeof(data1);
  579. RegQueryValueExW(hkey, L"Path", 0, &valueType, (LPBYTE)data1, &cch_data1);
  580. DWORD data2 = 0;
  581. DWORD cch_data2 = sizeof(data2);
  582. RegQueryValueExW(hkey, L"Security", 0, &valueType, (LPBYTE)&data2,
  583. &cch_data2);
  584. DWORD data3 = 0;
  585. DWORD cch_data3 = sizeof(data3);
  586. RegQueryValueExW(hkey, L"StorageFormat", 0, &valueType, (LPBYTE)&data3,
  587. &cch_data3);
  588. s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
  589. cmSystemTools::ConvertToUnixSlashes(s2);
  590. if (s2 == s1) {
  591. macrosRegistered = true;
  592. }
  593. // std::cout << keyname << ":" << std::endl;
  594. // std::cout << " Path: " << data1 << std::endl;
  595. // std::cout << " Security: " << data2 << std::endl;
  596. // std::cout << " StorageFormat: " << data3 << std::endl;
  597. // std::cout << std::endl;
  598. RegCloseKey(hkey);
  599. } else {
  600. std::cout << "error opening key: " << keyname << std::endl;
  601. std::cout << std::endl;
  602. }
  603. return macrosRegistered;
  604. }
  605. void WriteVSMacrosFileRegistryEntry(const std::string& nextAvailableSubKeyName,
  606. const std::string& macrosFile,
  607. const std::string& regKeyBase)
  608. {
  609. std::string keyname = cmStrCat(regKeyBase, "\\OtherProjects7");
  610. HKEY hkey = nullptr;
  611. LONG result =
  612. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  613. 0, KEY_READ | KEY_WRITE, &hkey);
  614. if (ERROR_SUCCESS == result) {
  615. // Create the subkey and set the values of interest:
  616. HKEY hsubkey = nullptr;
  617. wchar_t lpClass[] = L"";
  618. result = RegCreateKeyExW(
  619. hkey, cmsys::Encoding::ToWide(nextAvailableSubKeyName).c_str(), 0,
  620. lpClass, 0, KEY_READ | KEY_WRITE, 0, &hsubkey, 0);
  621. if (ERROR_SUCCESS == result) {
  622. DWORD dw = 0;
  623. std::string s(macrosFile);
  624. std::replace(s.begin(), s.end(), '/', '\\');
  625. std::wstring ws = cmsys::Encoding::ToWide(s);
  626. result =
  627. RegSetValueExW(hsubkey, L"Path", 0, REG_SZ, (LPBYTE)ws.c_str(),
  628. static_cast<DWORD>(ws.size() + 1) * sizeof(wchar_t));
  629. if (ERROR_SUCCESS != result) {
  630. std::cout << "error result 1: " << result << std::endl;
  631. std::cout << std::endl;
  632. }
  633. // Security value is always "1" for sample macros files (seems to be "2"
  634. // if you put the file somewhere outside the standard VSMacros folder)
  635. dw = 1;
  636. result = RegSetValueExW(hsubkey, L"Security", 0, REG_DWORD, (LPBYTE)&dw,
  637. sizeof(DWORD));
  638. if (ERROR_SUCCESS != result) {
  639. std::cout << "error result 2: " << result << std::endl;
  640. std::cout << std::endl;
  641. }
  642. // StorageFormat value is always "0" for sample macros files
  643. dw = 0;
  644. result = RegSetValueExW(hsubkey, L"StorageFormat", 0, REG_DWORD,
  645. (LPBYTE)&dw, sizeof(DWORD));
  646. if (ERROR_SUCCESS != result) {
  647. std::cout << "error result 3: " << result << std::endl;
  648. std::cout << std::endl;
  649. }
  650. RegCloseKey(hsubkey);
  651. } else {
  652. std::cout << "error creating subkey: " << nextAvailableSubKeyName
  653. << std::endl;
  654. std::cout << std::endl;
  655. }
  656. RegCloseKey(hkey);
  657. } else {
  658. std::cout << "error opening key: " << keyname << std::endl;
  659. std::cout << std::endl;
  660. }
  661. }
  662. void RegisterVisualStudioMacros(const std::string& macrosFile,
  663. const std::string& regKeyBase)
  664. {
  665. bool macrosRegistered;
  666. std::string nextAvailableSubKeyName;
  667. macrosRegistered = IsVisualStudioMacrosFileRegistered(
  668. macrosFile, regKeyBase, nextAvailableSubKeyName);
  669. if (!macrosRegistered) {
  670. int count =
  671. cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances("ALL");
  672. // Only register the macros file if there are *no* instances of Visual
  673. // Studio running. If we register it while one is running, first, it has
  674. // no effect on the running instance; second, and worse, Visual Studio
  675. // removes our newly added registration entry when it quits. Instead,
  676. // emit a warning asking the user to exit all running Visual Studio
  677. // instances...
  678. //
  679. if (0 != count) {
  680. std::ostringstream oss;
  681. oss << "Could not register CMake's Visual Studio macros file '"
  682. << CMAKE_VSMACROS_FILENAME "' while Visual Studio is running."
  683. << " Please exit all running instances of Visual Studio before"
  684. << " continuing." << std::endl
  685. << std::endl
  686. << "CMake needs to register Visual Studio macros when its macros"
  687. << " file is updated or when it detects that its current macros file"
  688. << " is no longer registered with Visual Studio." << std::endl;
  689. cmSystemTools::Message(oss.str(), "Warning");
  690. // Count them again now that the warning is over. In the case of a GUI
  691. // warning, the user may have gone to close Visual Studio and then come
  692. // back to the CMake GUI and clicked ok on the above warning. If so,
  693. // then register the macros *now* if the count is *now* 0...
  694. //
  695. count = cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances(
  696. "ALL");
  697. // Also re-get the nextAvailableSubKeyName in case Visual Studio
  698. // wrote out new registered macros information as it was exiting:
  699. //
  700. if (0 == count) {
  701. IsVisualStudioMacrosFileRegistered(macrosFile, regKeyBase,
  702. nextAvailableSubKeyName);
  703. }
  704. }
  705. // Do another if check - 'count' may have changed inside the above if:
  706. //
  707. if (0 == count) {
  708. WriteVSMacrosFileRegistryEntry(nextAvailableSubKeyName, macrosFile,
  709. regKeyBase);
  710. }
  711. }
  712. }
  713. bool cmGlobalVisualStudioGenerator::TargetIsFortranOnly(
  714. cmGeneratorTarget const* gt)
  715. {
  716. // If there's only one source language, Fortran has to be used
  717. // in order for the sources to compile.
  718. std::set<std::string> languages = gt->GetAllConfigCompileLanguages();
  719. // Consider an explicit linker language property, but *not* the
  720. // computed linker language that may depend on linked targets.
  721. // This allows the project to control the language choice in
  722. // a target with none of its own sources, e.g. when also using
  723. // object libraries.
  724. cmValue linkLang = gt->GetProperty("LINKER_LANGUAGE");
  725. if (cmNonempty(linkLang)) {
  726. languages.insert(*linkLang);
  727. }
  728. // Intel Fortran .vfproj files do support the resource compiler.
  729. languages.erase("RC");
  730. return languages.size() == 1 && *languages.begin() == "Fortran"_s;
  731. }
  732. bool cmGlobalVisualStudioGenerator::IsInSolution(
  733. const cmGeneratorTarget* gt) const
  734. {
  735. return gt->IsInBuildSystem();
  736. }
  737. bool cmGlobalVisualStudioGenerator::IsDepInSolution(
  738. const std::string& targetName) const
  739. {
  740. return !targetName.empty();
  741. }
  742. bool cmGlobalVisualStudioGenerator::TargetCompare::operator()(
  743. cmGeneratorTarget const* l, cmGeneratorTarget const* r) const
  744. {
  745. // Make sure a given named target is ordered first,
  746. // e.g. to set ALL_BUILD as the default active project.
  747. // When the empty string is named this is a no-op.
  748. if (r->GetName() == this->First) {
  749. return false;
  750. }
  751. if (l->GetName() == this->First) {
  752. return true;
  753. }
  754. return l->GetName() < r->GetName();
  755. }
  756. cmGlobalVisualStudioGenerator::OrderedTargetDependSet::OrderedTargetDependSet(
  757. TargetDependSet const& targets, std::string const& first)
  758. : derived(TargetCompare(first))
  759. {
  760. this->insert(targets.begin(), targets.end());
  761. }
  762. cmGlobalVisualStudioGenerator::OrderedTargetDependSet::OrderedTargetDependSet(
  763. TargetSet const& targets, std::string const& first)
  764. : derived(TargetCompare(first))
  765. {
  766. for (cmGeneratorTarget const* it : targets) {
  767. this->insert(it);
  768. }
  769. }
  770. std::string cmGlobalVisualStudioGenerator::ExpandCFGIntDir(
  771. const std::string& str, const std::string& config) const
  772. {
  773. std::string replace = GetCMakeCFGIntDir();
  774. std::string tmp = str;
  775. for (std::string::size_type i = tmp.find(replace); i != std::string::npos;
  776. i = tmp.find(replace, i)) {
  777. tmp.replace(i, replace.size(), config);
  778. i += config.size();
  779. }
  780. return tmp;
  781. }
  782. void cmGlobalVisualStudioGenerator::AddSymbolExportCommand(
  783. cmGeneratorTarget* gt, std::vector<cmCustomCommand>& commands,
  784. std::string const& configName)
  785. {
  786. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  787. gt->GetModuleDefinitionInfo(configName);
  788. if (!mdi || !mdi->DefFileGenerated) {
  789. return;
  790. }
  791. std::vector<std::string> outputs;
  792. outputs.push_back(mdi->DefFile);
  793. std::vector<std::string> empty;
  794. std::vector<cmSourceFile const*> objectSources;
  795. gt->GetObjectSources(objectSources, configName);
  796. std::map<cmSourceFile const*, std::string> mapping;
  797. for (cmSourceFile const* it : objectSources) {
  798. mapping[it];
  799. }
  800. gt->LocalGenerator->ComputeObjectFilenames(mapping, gt);
  801. std::string obj_dir = gt->ObjectDirectory;
  802. std::string cmakeCommand = cmSystemTools::GetCMakeCommand();
  803. std::string obj_dir_expanded = obj_dir;
  804. cmSystemTools::ReplaceString(obj_dir_expanded, this->GetCMakeCFGIntDir(),
  805. configName.c_str());
  806. cmSystemTools::MakeDirectory(obj_dir_expanded);
  807. std::string const objs_file = cmStrCat(obj_dir_expanded, "/objects.txt");
  808. cmGeneratedFileStream fout(objs_file.c_str());
  809. if (!fout) {
  810. cmSystemTools::Error(cmStrCat("could not open ", objs_file));
  811. return;
  812. }
  813. if (mdi->WindowsExportAllSymbols) {
  814. std::vector<std::string> objs;
  815. for (cmSourceFile const* it : objectSources) {
  816. // Find the object file name corresponding to this source file.
  817. // It must exist because we populated the mapping just above.
  818. const auto& v = mapping[it];
  819. assert(!v.empty());
  820. std::string objFile = cmStrCat(obj_dir, v);
  821. objs.push_back(objFile);
  822. }
  823. std::vector<cmSourceFile const*> externalObjectSources;
  824. gt->GetExternalObjects(externalObjectSources, configName);
  825. for (cmSourceFile const* it : externalObjectSources) {
  826. objs.push_back(it->GetFullPath());
  827. }
  828. for (std::string const& it : objs) {
  829. std::string objFile = it;
  830. // replace $(ConfigurationName) in the object names
  831. cmSystemTools::ReplaceString(objFile, this->GetCMakeCFGIntDir(),
  832. configName);
  833. if (cmHasLiteralSuffix(objFile, ".obj")) {
  834. fout << objFile << "\n";
  835. }
  836. }
  837. }
  838. for (cmSourceFile const* i : mdi->Sources) {
  839. fout << i->GetFullPath() << "\n";
  840. }
  841. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  842. { cmakeCommand, "-E", "__create_def", mdi->DefFile, objs_file });
  843. cmCustomCommand command;
  844. command.SetOutputs(outputs);
  845. command.SetCommandLines(commandLines);
  846. command.SetComment("Auto build dll exports");
  847. command.SetBacktrace(gt->Target->GetMakefile()->GetBacktrace());
  848. command.SetWorkingDirectory(".");
  849. command.SetStdPipesUTF8(true);
  850. commands.push_back(std::move(command));
  851. }
  852. static bool OpenSolution(std::string const& sln)
  853. {
  854. HRESULT comInitialized =
  855. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  856. if (FAILED(comInitialized)) {
  857. return false;
  858. }
  859. HINSTANCE hi = ShellExecuteA(nullptr, "open", sln.c_str(), nullptr, nullptr,
  860. SW_SHOWNORMAL);
  861. CoUninitialize();
  862. return reinterpret_cast<intptr_t>(hi) > 32;
  863. }
  864. bool cmGlobalVisualStudioGenerator::Open(const std::string& bindir,
  865. const std::string& projectName,
  866. bool dryRun)
  867. {
  868. std::string sln = cmStrCat(bindir, '/', projectName, ".sln");
  869. if (dryRun) {
  870. return cmSystemTools::FileExists(sln, true);
  871. }
  872. sln = cmSystemTools::ConvertToOutputPath(sln);
  873. return std::async(std::launch::async, OpenSolution, sln).get();
  874. }