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