cmGlobalVisualStudioGenerator.cxx 32 KB

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