cmGlobalVisualStudioGenerator.cxx 33 KB

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