cmGlobalVisualStudioGenerator.cxx 33 KB

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