cmGlobalVisualStudioGenerator.cxx 33 KB

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