cmGlobalVisualStudioGenerator.cxx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. std::string key = R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\)";
  169. return key + 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 = 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. oss << " 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 = dir + "/CMakeMacros/" CMAKE_VSMACROS_FILENAME;
  276. std::string nextSubkeyName;
  277. if (cmSystemTools::FileExists(macrosFile) &&
  278. IsVisualStudioMacrosFileRegistered(
  279. macrosFile, this->GetUserMacrosRegKeyBase(), nextSubkeyName)) {
  280. if (m == MacroReload) {
  281. std::vector<std::string> filenames;
  282. this->GetFilesReplacedDuringGenerate(filenames);
  283. if (!filenames.empty()) {
  284. std::string projects = cmJoin(filenames, ";");
  285. cmCallVisualStudioMacro::CallMacro(
  286. vsSolutionFile, CMAKE_VSMACROS_RELOAD_MACRONAME, projects,
  287. this->GetCMakeInstance()->GetDebugOutput());
  288. }
  289. } else if (m == MacroStop) {
  290. cmCallVisualStudioMacro::CallMacro(
  291. vsSolutionFile, CMAKE_VSMACROS_STOP_MACRONAME, "",
  292. this->GetCMakeInstance()->GetDebugOutput());
  293. }
  294. }
  295. }
  296. }
  297. std::string cmGlobalVisualStudioGenerator::GetUserMacrosDirectory()
  298. {
  299. return "";
  300. }
  301. std::string cmGlobalVisualStudioGenerator::GetUserMacrosRegKeyBase()
  302. {
  303. return "";
  304. }
  305. void cmGlobalVisualStudioGenerator::FillLinkClosure(
  306. const cmGeneratorTarget* target, TargetSet& linked)
  307. {
  308. if (linked.insert(target).second) {
  309. TargetDependSet const& depends = this->GetTargetDirectDepends(target);
  310. for (cmTargetDepend const& di : depends) {
  311. if (di.IsLink()) {
  312. this->FillLinkClosure(di, linked);
  313. }
  314. }
  315. }
  316. }
  317. cmGlobalVisualStudioGenerator::TargetSet const&
  318. cmGlobalVisualStudioGenerator::GetTargetLinkClosure(cmGeneratorTarget* target)
  319. {
  320. auto i = this->TargetLinkClosure.find(target);
  321. if (i == this->TargetLinkClosure.end()) {
  322. TargetSetMap::value_type entry(target, TargetSet());
  323. i = this->TargetLinkClosure.insert(entry).first;
  324. this->FillLinkClosure(target, i->second);
  325. }
  326. return i->second;
  327. }
  328. void cmGlobalVisualStudioGenerator::FollowLinkDepends(
  329. const cmGeneratorTarget* target, std::set<const cmGeneratorTarget*>& linked)
  330. {
  331. if (!target->IsInBuildSystem()) {
  332. return;
  333. }
  334. if (linked.insert(target).second &&
  335. target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  336. // Static library targets do not list their link dependencies so
  337. // we must follow them transitively now.
  338. TargetDependSet const& depends = this->GetTargetDirectDepends(target);
  339. for (cmTargetDepend const& di : depends) {
  340. if (di.IsLink()) {
  341. this->FollowLinkDepends(di, linked);
  342. }
  343. }
  344. }
  345. }
  346. bool cmGlobalVisualStudioGenerator::ComputeTargetDepends()
  347. {
  348. if (!this->cmGlobalGenerator::ComputeTargetDepends()) {
  349. return false;
  350. }
  351. for (auto const& it : this->ProjectMap) {
  352. for (const cmLocalGenerator* i : it.second) {
  353. for (const auto& ti : i->GetGeneratorTargets()) {
  354. this->ComputeVSTargetDepends(ti.get());
  355. }
  356. }
  357. }
  358. return true;
  359. }
  360. static bool VSLinkable(cmGeneratorTarget const* t)
  361. {
  362. return t->IsLinkable() || t->GetType() == cmStateEnums::OBJECT_LIBRARY;
  363. }
  364. void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
  365. cmGeneratorTarget* target)
  366. {
  367. if (this->VSTargetDepends.find(target) != this->VSTargetDepends.end()) {
  368. return;
  369. }
  370. VSDependSet& vsTargetDepend = this->VSTargetDepends[target];
  371. // VS <= 7.1 has two behaviors that affect solution dependencies.
  372. //
  373. // (1) Solution-level dependencies between a linkable target and a
  374. // library cause that library to be linked. We use an intermedite
  375. // empty utility target to express the dependency. (VS 8 and above
  376. // provide a project file "LinkLibraryDependencies" setting to
  377. // choose whether to activate this behavior. We disable it except
  378. // when linking external project files.)
  379. //
  380. // (2) We cannot let static libraries depend directly on targets to
  381. // which they "link" because the librarian tool will copy the
  382. // targets into the static library. While the work-around for
  383. // behavior (1) would also avoid this, it would create a large
  384. // number of extra utility targets for little gain. Instead, use
  385. // the above work-around only for dependencies explicitly added by
  386. // the add_dependencies() command. Approximate link dependencies by
  387. // leaving them out for the static library itself but following them
  388. // transitively for other targets.
  389. bool allowLinkable = (target->GetType() != cmStateEnums::STATIC_LIBRARY &&
  390. target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  391. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  392. target->GetType() != cmStateEnums::EXECUTABLE);
  393. TargetDependSet const& depends = this->GetTargetDirectDepends(target);
  394. // Collect implicit link dependencies (target_link_libraries).
  395. // Static libraries cannot depend on their link implementation
  396. // due to behavior (2), but they do not really need to.
  397. std::set<cmGeneratorTarget const*> linkDepends;
  398. if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  399. for (cmTargetDepend const& di : depends) {
  400. if (di.IsLink()) {
  401. this->FollowLinkDepends(di, linkDepends);
  402. }
  403. }
  404. }
  405. // Collect explicit util dependencies (add_dependencies).
  406. std::set<cmGeneratorTarget const*> utilDepends;
  407. for (cmTargetDepend const& di : depends) {
  408. if (di.IsUtil()) {
  409. this->FollowLinkDepends(di, utilDepends);
  410. }
  411. }
  412. // Collect all targets linked by this target so we can avoid
  413. // intermediate targets below.
  414. TargetSet linked;
  415. if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  416. linked = this->GetTargetLinkClosure(target);
  417. }
  418. // Emit link dependencies.
  419. for (cmGeneratorTarget const* dep : linkDepends) {
  420. vsTargetDepend.insert(dep->GetName());
  421. }
  422. // Emit util dependencies. Possibly use intermediate targets.
  423. for (cmGeneratorTarget const* dgt : utilDepends) {
  424. if (allowLinkable || !VSLinkable(dgt) || linked.count(dgt)) {
  425. // Direct dependency allowed.
  426. vsTargetDepend.insert(dgt->GetName());
  427. } else {
  428. // Direct dependency on linkable target not allowed.
  429. // Use an intermediate utility target.
  430. vsTargetDepend.insert(this->GetUtilityDepend(dgt));
  431. }
  432. }
  433. }
  434. bool cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
  435. {
  436. // Visual Studio generators know how to lookup their build tool
  437. // directly instead of needing a helper module to do it, so we
  438. // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
  439. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  440. mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetVSMakeProgram());
  441. }
  442. return true;
  443. }
  444. std::string cmGlobalVisualStudioGenerator::GetUtilityDepend(
  445. cmGeneratorTarget const* target)
  446. {
  447. auto i = this->UtilityDepends.find(target);
  448. if (i == this->UtilityDepends.end()) {
  449. std::string name = this->WriteUtilityDepend(target);
  450. UtilityDependsMap::value_type entry(target, name);
  451. i = this->UtilityDepends.insert(entry).first;
  452. }
  453. return i->second;
  454. }
  455. std::string cmGlobalVisualStudioGenerator::GetStartupProjectName(
  456. cmLocalGenerator const* root) const
  457. {
  458. cmValue n = root->GetMakefile()->GetProperty("VS_STARTUP_PROJECT");
  459. if (cmNonempty(n)) {
  460. std::string startup = *n;
  461. if (this->FindTarget(startup)) {
  462. return startup;
  463. }
  464. root->GetMakefile()->IssueMessage(
  465. MessageType::AUTHOR_WARNING,
  466. "Directory property VS_STARTUP_PROJECT specifies target "
  467. "'" +
  468. startup + "' that does not exist. Ignoring.");
  469. }
  470. // default, if not specified
  471. return this->GetAllTargetName();
  472. }
  473. bool IsVisualStudioMacrosFileRegistered(const std::string& macrosFile,
  474. const std::string& regKeyBase,
  475. std::string& nextAvailableSubKeyName)
  476. {
  477. bool macrosRegistered = false;
  478. std::string s1;
  479. std::string s2;
  480. // Make lowercase local copies, convert to Unix slashes, and
  481. // see if the resulting strings are the same:
  482. s1 = cmSystemTools::LowerCase(macrosFile);
  483. cmSystemTools::ConvertToUnixSlashes(s1);
  484. std::string keyname;
  485. HKEY hkey = nullptr;
  486. LONG result = ERROR_SUCCESS;
  487. DWORD index = 0;
  488. keyname = regKeyBase + "\\OtherProjects7";
  489. hkey = nullptr;
  490. result =
  491. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  492. 0, KEY_READ, &hkey);
  493. if (ERROR_SUCCESS == result) {
  494. // Iterate the subkeys and look for the values of interest in each subkey:
  495. wchar_t subkeyname[256];
  496. DWORD cch_subkeyname = cm::size(subkeyname);
  497. wchar_t keyclass[256];
  498. DWORD cch_keyclass = cm::size(keyclass);
  499. FILETIME lastWriteTime;
  500. lastWriteTime.dwHighDateTime = 0;
  501. lastWriteTime.dwLowDateTime = 0;
  502. while (ERROR_SUCCESS ==
  503. RegEnumKeyExW(hkey, index, subkeyname, &cch_subkeyname, 0, keyclass,
  504. &cch_keyclass, &lastWriteTime)) {
  505. // Open the subkey and query the values of interest:
  506. HKEY hsubkey = nullptr;
  507. result = RegOpenKeyExW(hkey, subkeyname, 0, KEY_READ, &hsubkey);
  508. if (ERROR_SUCCESS == result) {
  509. DWORD valueType = REG_SZ;
  510. wchar_t data1[256];
  511. DWORD cch_data1 = sizeof(data1);
  512. RegQueryValueExW(hsubkey, L"Path", 0, &valueType, (LPBYTE)data1,
  513. &cch_data1);
  514. DWORD data2 = 0;
  515. DWORD cch_data2 = sizeof(data2);
  516. RegQueryValueExW(hsubkey, L"Security", 0, &valueType, (LPBYTE)&data2,
  517. &cch_data2);
  518. DWORD data3 = 0;
  519. DWORD cch_data3 = sizeof(data3);
  520. RegQueryValueExW(hsubkey, L"StorageFormat", 0, &valueType,
  521. (LPBYTE)&data3, &cch_data3);
  522. s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
  523. cmSystemTools::ConvertToUnixSlashes(s2);
  524. if (s2 == s1) {
  525. macrosRegistered = true;
  526. }
  527. std::string fullname = cmsys::Encoding::ToNarrow(data1);
  528. std::string filename;
  529. std::string filepath;
  530. std::string filepathname;
  531. std::string filepathpath;
  532. if (cmSystemTools::FileExists(fullname)) {
  533. filename = cmSystemTools::GetFilenameName(fullname);
  534. filepath = cmSystemTools::GetFilenamePath(fullname);
  535. filepathname = cmSystemTools::GetFilenameName(filepath);
  536. filepathpath = cmSystemTools::GetFilenamePath(filepath);
  537. }
  538. // std::cout << keyname << "\\" << subkeyname << ":" << std::endl;
  539. // std::cout << " Path: " << data1 << std::endl;
  540. // std::cout << " Security: " << data2 << std::endl;
  541. // std::cout << " StorageFormat: " << data3 << std::endl;
  542. // std::cout << " filename: " << filename << std::endl;
  543. // std::cout << " filepath: " << filepath << std::endl;
  544. // std::cout << " filepathname: " << filepathname << std::endl;
  545. // std::cout << " filepathpath: " << filepathpath << std::endl;
  546. // std::cout << std::endl;
  547. RegCloseKey(hsubkey);
  548. } else {
  549. std::cout << "error opening subkey: "
  550. << cmsys::Encoding::ToNarrow(subkeyname) << std::endl;
  551. std::cout << std::endl;
  552. }
  553. ++index;
  554. cch_subkeyname = cm::size(subkeyname);
  555. cch_keyclass = cm::size(keyclass);
  556. lastWriteTime.dwHighDateTime = 0;
  557. lastWriteTime.dwLowDateTime = 0;
  558. }
  559. RegCloseKey(hkey);
  560. } else {
  561. std::cout << "error opening key: " << keyname << std::endl;
  562. std::cout << std::endl;
  563. }
  564. // Pass back next available sub key name, assuming sub keys always
  565. // follow the expected naming scheme. Expected naming scheme is that
  566. // the subkeys of OtherProjects7 is 0 to n-1, so it's ok to use "n"
  567. // as the name of the next subkey.
  568. nextAvailableSubKeyName = std::to_string(index);
  569. keyname = regKeyBase + "\\RecordingProject7";
  570. hkey = nullptr;
  571. result =
  572. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  573. 0, KEY_READ, &hkey);
  574. if (ERROR_SUCCESS == result) {
  575. DWORD valueType = REG_SZ;
  576. wchar_t data1[256];
  577. DWORD cch_data1 = sizeof(data1);
  578. RegQueryValueExW(hkey, L"Path", 0, &valueType, (LPBYTE)data1, &cch_data1);
  579. DWORD data2 = 0;
  580. DWORD cch_data2 = sizeof(data2);
  581. RegQueryValueExW(hkey, L"Security", 0, &valueType, (LPBYTE)&data2,
  582. &cch_data2);
  583. DWORD data3 = 0;
  584. DWORD cch_data3 = sizeof(data3);
  585. RegQueryValueExW(hkey, L"StorageFormat", 0, &valueType, (LPBYTE)&data3,
  586. &cch_data3);
  587. s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
  588. cmSystemTools::ConvertToUnixSlashes(s2);
  589. if (s2 == s1) {
  590. macrosRegistered = true;
  591. }
  592. // std::cout << keyname << ":" << std::endl;
  593. // std::cout << " Path: " << data1 << std::endl;
  594. // std::cout << " Security: " << data2 << std::endl;
  595. // std::cout << " StorageFormat: " << data3 << std::endl;
  596. // std::cout << std::endl;
  597. RegCloseKey(hkey);
  598. } else {
  599. std::cout << "error opening key: " << keyname << std::endl;
  600. std::cout << std::endl;
  601. }
  602. return macrosRegistered;
  603. }
  604. void WriteVSMacrosFileRegistryEntry(const std::string& nextAvailableSubKeyName,
  605. const std::string& macrosFile,
  606. const std::string& regKeyBase)
  607. {
  608. std::string keyname = regKeyBase + "\\OtherProjects7";
  609. HKEY hkey = nullptr;
  610. LONG result =
  611. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  612. 0, KEY_READ | KEY_WRITE, &hkey);
  613. if (ERROR_SUCCESS == result) {
  614. // Create the subkey and set the values of interest:
  615. HKEY hsubkey = nullptr;
  616. wchar_t lpClass[] = L"";
  617. result = RegCreateKeyExW(
  618. hkey, cmsys::Encoding::ToWide(nextAvailableSubKeyName).c_str(), 0,
  619. lpClass, 0, KEY_READ | KEY_WRITE, 0, &hsubkey, 0);
  620. if (ERROR_SUCCESS == result) {
  621. DWORD dw = 0;
  622. std::string s(macrosFile);
  623. std::replace(s.begin(), s.end(), '/', '\\');
  624. std::wstring ws = cmsys::Encoding::ToWide(s);
  625. result =
  626. RegSetValueExW(hsubkey, L"Path", 0, REG_SZ, (LPBYTE)ws.c_str(),
  627. static_cast<DWORD>(ws.size() + 1) * sizeof(wchar_t));
  628. if (ERROR_SUCCESS != result) {
  629. std::cout << "error result 1: " << result << std::endl;
  630. std::cout << std::endl;
  631. }
  632. // Security value is always "1" for sample macros files (seems to be "2"
  633. // if you put the file somewhere outside the standard VSMacros folder)
  634. dw = 1;
  635. result = RegSetValueExW(hsubkey, L"Security", 0, REG_DWORD, (LPBYTE)&dw,
  636. sizeof(DWORD));
  637. if (ERROR_SUCCESS != result) {
  638. std::cout << "error result 2: " << result << std::endl;
  639. std::cout << std::endl;
  640. }
  641. // StorageFormat value is always "0" for sample macros files
  642. dw = 0;
  643. result = RegSetValueExW(hsubkey, L"StorageFormat", 0, REG_DWORD,
  644. (LPBYTE)&dw, sizeof(DWORD));
  645. if (ERROR_SUCCESS != result) {
  646. std::cout << "error result 3: " << result << std::endl;
  647. std::cout << std::endl;
  648. }
  649. RegCloseKey(hsubkey);
  650. } else {
  651. std::cout << "error creating subkey: " << nextAvailableSubKeyName
  652. << std::endl;
  653. std::cout << std::endl;
  654. }
  655. RegCloseKey(hkey);
  656. } else {
  657. std::cout << "error opening key: " << keyname << std::endl;
  658. std::cout << std::endl;
  659. }
  660. }
  661. void RegisterVisualStudioMacros(const std::string& macrosFile,
  662. const std::string& regKeyBase)
  663. {
  664. bool macrosRegistered;
  665. std::string nextAvailableSubKeyName;
  666. macrosRegistered = IsVisualStudioMacrosFileRegistered(
  667. macrosFile, regKeyBase, nextAvailableSubKeyName);
  668. if (!macrosRegistered) {
  669. int count =
  670. cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances("ALL");
  671. // Only register the macros file if there are *no* instances of Visual
  672. // Studio running. If we register it while one is running, first, it has
  673. // no effect on the running instance; second, and worse, Visual Studio
  674. // removes our newly added registration entry when it quits. Instead,
  675. // emit a warning asking the user to exit all running Visual Studio
  676. // instances...
  677. //
  678. if (0 != count) {
  679. std::ostringstream oss;
  680. oss << "Could not register CMake's Visual Studio macros file '"
  681. << CMAKE_VSMACROS_FILENAME "' while Visual Studio is running."
  682. << " Please exit all running instances of Visual Studio before"
  683. << " continuing." << std::endl
  684. << std::endl
  685. << "CMake needs to register Visual Studio macros when its macros"
  686. << " file is updated or when it detects that its current macros file"
  687. << " is no longer registered with Visual Studio." << std::endl;
  688. cmSystemTools::Message(oss.str(), "Warning");
  689. // Count them again now that the warning is over. In the case of a GUI
  690. // warning, the user may have gone to close Visual Studio and then come
  691. // back to the CMake GUI and clicked ok on the above warning. If so,
  692. // then register the macros *now* if the count is *now* 0...
  693. //
  694. count = cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances(
  695. "ALL");
  696. // Also re-get the nextAvailableSubKeyName in case Visual Studio
  697. // wrote out new registered macros information as it was exiting:
  698. //
  699. if (0 == count) {
  700. IsVisualStudioMacrosFileRegistered(macrosFile, regKeyBase,
  701. nextAvailableSubKeyName);
  702. }
  703. }
  704. // Do another if check - 'count' may have changed inside the above if:
  705. //
  706. if (0 == count) {
  707. WriteVSMacrosFileRegistryEntry(nextAvailableSubKeyName, macrosFile,
  708. regKeyBase);
  709. }
  710. }
  711. }
  712. bool cmGlobalVisualStudioGenerator::TargetIsFortranOnly(
  713. cmGeneratorTarget const* gt)
  714. {
  715. // If there's only one source language, Fortran has to be used
  716. // in order for the sources to compile.
  717. std::set<std::string> languages = gt->GetAllConfigCompileLanguages();
  718. // Consider an explicit linker language property, but *not* the
  719. // computed linker language that may depend on linked targets.
  720. // This allows the project to control the language choice in
  721. // a target with none of its own sources, e.g. when also using
  722. // object libraries.
  723. cmValue linkLang = gt->GetProperty("LINKER_LANGUAGE");
  724. if (cmNonempty(linkLang)) {
  725. languages.insert(*linkLang);
  726. }
  727. // Intel Fortran .vfproj files do support the resource compiler.
  728. languages.erase("RC");
  729. return languages.size() == 1 && *languages.begin() == "Fortran"_s;
  730. }
  731. bool cmGlobalVisualStudioGenerator::IsInSolution(
  732. const cmGeneratorTarget* gt) const
  733. {
  734. return gt->IsInBuildSystem();
  735. }
  736. bool cmGlobalVisualStudioGenerator::IsDepInSolution(
  737. const std::string& targetName) const
  738. {
  739. return !targetName.empty();
  740. }
  741. bool cmGlobalVisualStudioGenerator::TargetCompare::operator()(
  742. cmGeneratorTarget const* l, cmGeneratorTarget const* r) const
  743. {
  744. // Make sure a given named target is ordered first,
  745. // e.g. to set ALL_BUILD as the default active project.
  746. // When the empty string is named this is a no-op.
  747. if (r->GetName() == this->First) {
  748. return false;
  749. }
  750. if (l->GetName() == this->First) {
  751. return true;
  752. }
  753. return l->GetName() < r->GetName();
  754. }
  755. cmGlobalVisualStudioGenerator::OrderedTargetDependSet::OrderedTargetDependSet(
  756. TargetDependSet const& targets, std::string const& first)
  757. : derived(TargetCompare(first))
  758. {
  759. this->insert(targets.begin(), targets.end());
  760. }
  761. cmGlobalVisualStudioGenerator::OrderedTargetDependSet::OrderedTargetDependSet(
  762. TargetSet const& targets, std::string const& first)
  763. : derived(TargetCompare(first))
  764. {
  765. for (cmGeneratorTarget const* it : targets) {
  766. this->insert(it);
  767. }
  768. }
  769. std::string cmGlobalVisualStudioGenerator::ExpandCFGIntDir(
  770. const std::string& str, const std::string& config) const
  771. {
  772. std::string replace = GetCMakeCFGIntDir();
  773. std::string tmp = str;
  774. for (std::string::size_type i = tmp.find(replace); i != std::string::npos;
  775. i = tmp.find(replace, i)) {
  776. tmp.replace(i, replace.size(), config);
  777. i += config.size();
  778. }
  779. return tmp;
  780. }
  781. void cmGlobalVisualStudioGenerator::AddSymbolExportCommand(
  782. cmGeneratorTarget* gt, std::vector<cmCustomCommand>& commands,
  783. std::string const& configName)
  784. {
  785. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  786. gt->GetModuleDefinitionInfo(configName);
  787. if (!mdi || !mdi->DefFileGenerated) {
  788. return;
  789. }
  790. std::vector<std::string> outputs;
  791. outputs.push_back(mdi->DefFile);
  792. std::vector<std::string> empty;
  793. std::vector<cmSourceFile const*> objectSources;
  794. gt->GetObjectSources(objectSources, configName);
  795. std::map<cmSourceFile const*, std::string> mapping;
  796. for (cmSourceFile const* it : objectSources) {
  797. mapping[it];
  798. }
  799. gt->LocalGenerator->ComputeObjectFilenames(mapping, gt);
  800. std::string obj_dir = gt->ObjectDirectory;
  801. std::string cmakeCommand = cmSystemTools::GetCMakeCommand();
  802. std::string obj_dir_expanded = obj_dir;
  803. cmSystemTools::ReplaceString(obj_dir_expanded, this->GetCMakeCFGIntDir(),
  804. configName.c_str());
  805. cmSystemTools::MakeDirectory(obj_dir_expanded);
  806. std::string const objs_file = obj_dir_expanded + "/objects.txt";
  807. cmGeneratedFileStream fout(objs_file.c_str());
  808. if (!fout) {
  809. cmSystemTools::Error("could not open " + objs_file);
  810. return;
  811. }
  812. if (mdi->WindowsExportAllSymbols) {
  813. std::vector<std::string> objs;
  814. for (cmSourceFile const* it : objectSources) {
  815. // Find the object file name corresponding to this source file.
  816. // It must exist because we populated the mapping just above.
  817. const auto& v = mapping[it];
  818. assert(!v.empty());
  819. std::string objFile = obj_dir + v;
  820. objs.push_back(objFile);
  821. }
  822. std::vector<cmSourceFile const*> externalObjectSources;
  823. gt->GetExternalObjects(externalObjectSources, configName);
  824. for (cmSourceFile const* it : externalObjectSources) {
  825. objs.push_back(it->GetFullPath());
  826. }
  827. for (std::string const& it : objs) {
  828. std::string objFile = it;
  829. // replace $(ConfigurationName) in the object names
  830. cmSystemTools::ReplaceString(objFile, this->GetCMakeCFGIntDir(),
  831. configName);
  832. if (cmHasLiteralSuffix(objFile, ".obj")) {
  833. fout << objFile << "\n";
  834. }
  835. }
  836. }
  837. for (cmSourceFile const* i : mdi->Sources) {
  838. fout << i->GetFullPath() << "\n";
  839. }
  840. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  841. { cmakeCommand, "-E", "__create_def", mdi->DefFile, objs_file });
  842. cmCustomCommand command;
  843. command.SetOutputs(outputs);
  844. command.SetCommandLines(commandLines);
  845. command.SetComment("Auto build dll exports");
  846. command.SetBacktrace(gt->Target->GetMakefile()->GetBacktrace());
  847. command.SetWorkingDirectory(".");
  848. command.SetStdPipesUTF8(true);
  849. commands.push_back(std::move(command));
  850. }
  851. static bool OpenSolution(std::string const& sln)
  852. {
  853. HRESULT comInitialized =
  854. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  855. if (FAILED(comInitialized)) {
  856. return false;
  857. }
  858. HINSTANCE hi = ShellExecuteA(nullptr, "open", sln.c_str(), nullptr, nullptr,
  859. SW_SHOWNORMAL);
  860. CoUninitialize();
  861. return reinterpret_cast<intptr_t>(hi) > 32;
  862. }
  863. bool cmGlobalVisualStudioGenerator::Open(const std::string& bindir,
  864. const std::string& projectName,
  865. bool dryRun)
  866. {
  867. std::string sln = bindir + "/" + projectName + ".sln";
  868. if (dryRun) {
  869. return cmSystemTools::FileExists(sln, true);
  870. }
  871. sln = cmSystemTools::ConvertToOutputPath(sln);
  872. return std::async(std::launch::async, OpenSolution, sln).get();
  873. }