cmGlobalVisualStudioGenerator.cxx 34 KB

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