cmGlobalVisualStudioGenerator.cxx 33 KB

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