cmGlobalVisualStudioGenerator.cxx 31 KB

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