cmGlobalVisualStudioGenerator.cxx 33 KB

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