cmGlobalFastbuildGenerator.cxx 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  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 "cmGlobalFastbuildGenerator.h"
  4. #include <algorithm>
  5. #include <cstdlib>
  6. #include <initializer_list>
  7. #include <iterator>
  8. #include <queue>
  9. #include <sstream>
  10. #include <cm/memory>
  11. #include "cmsys/FStream.hxx"
  12. #include "cmsys/RegularExpression.hxx"
  13. #include "cmFastbuildLinkLineComputer.h"
  14. #include "cmFastbuildTargetGenerator.h" // IWYU pragma: keep
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorTarget.h"
  17. #include "cmGlobCacheEntry.h"
  18. #include "cmGlobalGenerator.h"
  19. #include "cmGlobalGeneratorFactory.h"
  20. #include "cmList.h"
  21. #include "cmLocalFastbuildGenerator.h"
  22. #include "cmLocalGenerator.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmState.h"
  26. #include "cmStateDirectory.h"
  27. #include "cmStateSnapshot.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. #include "cmValue.h"
  31. #include "cmVersion.h"
  32. #include "cmake.h"
  33. #if defined(_WIN32)
  34. # include <future>
  35. # include <objbase.h>
  36. # include <shellapi.h>
  37. #endif
  38. class cmLinkLineComputer;
  39. #define FASTBUILD_REBUILD_BFF_TARGET_NAME "rebuild-bff"
  40. #define FASTBUILD_GLOB_CHECK_TARGET "glob-check"
  41. #define FASTBUILD_ENV_VAR_NAME "LocalEnv"
  42. // IDE support
  43. #define FASTBUILD_XCODE_BASE_PATH "XCode/Projects"
  44. #define FASTBUILD_VS_BASE_PATH "VisualStudio/Projects"
  45. #define FASTBUILD_IDE_VS_COMMAND_PREFIX "cd ^$(SolutionDir).. && "
  46. #define FASTBUILD_DEFAULT_IDE_BUILD_ARGS " -ide -cache -summary -dist "
  47. constexpr auto FASTBUILD_CAPTURE_SYSTEM_ENV =
  48. "CMAKE_FASTBUILD_CAPTURE_SYSTEM_ENV";
  49. constexpr auto FASTBUILD_ENV_OVERRIDES = "CMAKE_FASTBUILD_ENV_OVERRIDES";
  50. // Inherits from "CMAKE_FASTBUILD_VERBOSE_GENERATOR" env variable.
  51. constexpr auto FASTBUILD_VERBOSE_GENERATOR =
  52. "CMAKE_FASTBUILD_VERBOSE_GENERATOR";
  53. constexpr auto FASTBUILD_CACHE_PATH = "CMAKE_FASTBUILD_CACHE_PATH";
  54. // Compiler settings.
  55. constexpr auto FASTBUILD_COMPILER_EXTRA_FILES =
  56. "CMAKE_FASTBUILD_COMPILER_EXTRA_FILES";
  57. constexpr auto FASTBUILD_USE_LIGHTCACHE = "CMAKE_FASTBUILD_USE_LIGHTCACHE";
  58. constexpr auto FASTBUILD_USE_RELATIVE_PATHS =
  59. "CMAKE_FASTBUILD_USE_RELATIVE_PATHS";
  60. constexpr auto FASTBUILD_USE_DETERMINISTIC_PATHS =
  61. "CMAKE_FASTBUILD_USE_DETERMINISTIC_PATHS";
  62. constexpr auto FASTBUILD_SOURCE_MAPPING = "CMAKE_FASTBUILD_SOURCE_MAPPING";
  63. constexpr auto FASTBUILD_CLANG_REWRITE_INCLUDES =
  64. "CMAKE_FASTBUILD_CLANG_REWRITE_INCLUDES";
  65. constexpr auto FASTBUILD_CLANG_GCC_UPDATE_XLANG_ARG =
  66. "CMAKE_FASTBUILD_CLANG_GCC_UPDATE_XLANG_ARG";
  67. constexpr auto FASTBUILD_ALLOW_RESPONSE_FILE =
  68. "CMAKE_FASTBUILD_ALLOW_RESPONSE_FILE";
  69. constexpr auto FASTBUILD_FORCE_RESPONSE_FILE =
  70. "CMAKE_FASTBUILD_FORCE_RESPONSE_FILE";
  71. constexpr auto FASTBUILD_IDE_ARGS = "CMAKE_FASTBUILD_IDE_ARGS";
  72. static std::map<std::string, std::string> const compilerIdToFastbuildFamily = {
  73. { "MSVC", "msvc" }, { "Clang", "clang" }, { "AppleClang", "clang" },
  74. { "GNU", "gcc" }, { "NVIDIA", "cuda-nvcc" }, { "Clang-cl", "clang-cl" },
  75. };
  76. static std::set<std::string> const supportedLanguages = { "C", "CXX", "CUDA",
  77. "OBJC", "OBJCXX" };
  78. template <class T>
  79. FastbuildAliasNode generateAlias(std::string const& name, char const* postfix,
  80. T const& nodes)
  81. {
  82. FastbuildAliasNode alias;
  83. alias.Name = name + postfix;
  84. for (auto const& node : nodes) {
  85. alias.PreBuildDependencies.emplace(node.Name);
  86. }
  87. return alias;
  88. }
  89. void FastbuildTarget::GenerateAliases()
  90. {
  91. // -deps
  92. this->DependenciesAlias.Name =
  93. this->Name + FASTBUILD_DEPS_ARTIFACTS_ALIAS_POSTFIX;
  94. for (auto const& dep : this->PreBuildDependencies) {
  95. if (dep.Type != FastbuildTargetDepType::ORDER_ONLY) {
  96. this->DependenciesAlias.PreBuildDependencies.emplace(dep);
  97. }
  98. }
  99. // PRE/POST/REST
  100. if (!this->PreBuildExecNodes.PreBuildDependencies.empty()) {
  101. this->PreBuildExecNodes.Name =
  102. this->Name + FASTBUILD_PRE_BUILD_ALIAS_POSTFIX;
  103. }
  104. if (!this->PreLinkExecNodes.Nodes.empty()) {
  105. this->PreLinkExecNodes.Alias =
  106. generateAlias(this->Name, FASTBUILD_PRE_LINK_ALIAS_POSTFIX,
  107. this->PreLinkExecNodes.Nodes);
  108. }
  109. if (!this->PostBuildExecNodes.Alias.PreBuildDependencies.empty()) {
  110. this->PostBuildExecNodes.Alias.Name =
  111. this->Name + FASTBUILD_POST_BUILD_ALIAS_POSTFIX;
  112. }
  113. if (!this->ExecNodes.PreBuildDependencies.empty()) {
  114. this->ExecNodes.Name = this->Name + FASTBUILD_CUSTOM_COMMAND_ALIAS_POSTFIX;
  115. }
  116. // If we don't have any node that we can build by name (e.g. no static /
  117. // dynamic lib or executable) -> create an alias so that we can build this
  118. // target by name.
  119. if (LinkerNode.empty()) {
  120. FastbuildAliasNode alias;
  121. alias.Name = this->Name;
  122. if (LinkerNode.empty()) {
  123. for (FastbuildObjectListNode const& objListNode : ObjectListNodes) {
  124. alias.PreBuildDependencies.emplace(objListNode.Name);
  125. }
  126. } else {
  127. for (FastbuildLinkerNode const& linkerNode : LinkerNode) {
  128. alias.PreBuildDependencies.emplace(linkerNode.Name);
  129. }
  130. }
  131. AliasNodes.emplace_back(std::move(alias));
  132. }
  133. // Link artifacts (should not be added to all
  134. // since on Windows it might contain Import Lib and FASTBuild doesn't know
  135. // how to create it, so "-all" will fail).
  136. AliasNodes.emplace_back(generateAlias(
  137. this->Name, FASTBUILD_OBJECTS_ALIAS_POSTFIX, this->ObjectListNodes));
  138. for (auto const& linkerNode : this->LinkerNode) {
  139. if (linkerNode.Type == FastbuildLinkerNode::SHARED_LIBRARY ||
  140. linkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY ||
  141. linkerNode.Type == FastbuildLinkerNode::EXECUTABLE) {
  142. std::string postfix = FASTBUILD_LINK_ARTIFACTS_ALIAS_POSTFIX;
  143. if (!linkerNode.Arch.empty()) {
  144. postfix += cmStrCat('-', linkerNode.Arch);
  145. }
  146. #ifdef _WIN32
  147. // On Windows DLL and Executables must be linked via Import Lib file
  148. // (.lib).
  149. if (linkerNode.Type == FastbuildLinkerNode::SHARED_LIBRARY ||
  150. linkerNode.Type == FastbuildLinkerNode::EXECUTABLE) {
  151. FastbuildAliasNode linkAlias;
  152. linkAlias.Name = this->Name + FASTBUILD_LINK_ARTIFACTS_ALIAS_POSTFIX;
  153. linkAlias.PreBuildDependencies.emplace(
  154. FASTBUILD_DOLLAR_TAG "TargetOutputImplib" FASTBUILD_DOLLAR_TAG);
  155. AliasNodes.emplace_back(std::move(linkAlias));
  156. continue;
  157. }
  158. #endif
  159. FastbuildAliasNode alias;
  160. alias.Name = this->Name + postfix;
  161. alias.PreBuildDependencies.emplace(linkerNode.LinkerOutput);
  162. AliasNodes.emplace_back(std::move(alias));
  163. }
  164. }
  165. }
  166. cmGlobalFastbuildGenerator::cmGlobalFastbuildGenerator(cmake* cm)
  167. : cmGlobalCommonGenerator(cm)
  168. , BuildFileStream(nullptr)
  169. {
  170. #ifdef _WIN32
  171. cm->GetState()->SetWindowsShell(true);
  172. #endif
  173. this->FindMakeProgramFile = "CMakeFastbuildFindMake.cmake";
  174. cm->GetState()->SetFastbuildMake(true);
  175. cm->GetState()->SetIsGeneratorMultiConfig(false);
  176. }
  177. void cmGlobalFastbuildGenerator::ReadCompilerOptions(
  178. FastbuildCompiler& compiler, cmMakefile* mf)
  179. {
  180. if (compiler.CompilerFamily == "custom") {
  181. return;
  182. }
  183. if (cmIsOn(mf->GetSafeDefinition(FASTBUILD_USE_LIGHTCACHE))) {
  184. compiler.UseLightCache = true;
  185. }
  186. if (cmIsOn(mf->GetSafeDefinition(FASTBUILD_USE_RELATIVE_PATHS))) {
  187. compiler.UseRelativePaths = true;
  188. UsingRelativePaths = true;
  189. }
  190. if (cmIsOn(mf->GetSafeDefinition(FASTBUILD_USE_DETERMINISTIC_PATHS))) {
  191. compiler.UseDeterministicPaths = true;
  192. }
  193. std::string sourceMapping = mf->GetSafeDefinition(FASTBUILD_SOURCE_MAPPING);
  194. if (!sourceMapping.empty()) {
  195. compiler.SourceMapping = std::move(sourceMapping);
  196. }
  197. auto const clangRewriteIncludesDef =
  198. mf->GetDefinition(FASTBUILD_CLANG_REWRITE_INCLUDES);
  199. if (clangRewriteIncludesDef.IsSet() && clangRewriteIncludesDef.IsOff()) {
  200. compiler.ClangRewriteIncludes = false;
  201. }
  202. if (cmIsOn(mf->GetSafeDefinition(FASTBUILD_CLANG_GCC_UPDATE_XLANG_ARG))) {
  203. compiler.ClangGCCUpdateXLanguageArg = true;
  204. }
  205. if (cmIsOn(mf->GetSafeDefinition(FASTBUILD_ALLOW_RESPONSE_FILE))) {
  206. compiler.AllowResponseFile = true;
  207. }
  208. if (cmIsOn(mf->GetSafeDefinition(FASTBUILD_FORCE_RESPONSE_FILE))) {
  209. compiler.ForceResponseFile = true;
  210. }
  211. }
  212. void cmGlobalFastbuildGenerator::ProcessEnvironment()
  213. {
  214. bool const CaptureSystemEnv =
  215. !this->GetGlobalSetting(FASTBUILD_CAPTURE_SYSTEM_ENV).IsSet() ||
  216. this->GetGlobalSetting(FASTBUILD_CAPTURE_SYSTEM_ENV).IsOn();
  217. // On Windows environment is needed for MSVC, but preserve ability to discard
  218. // it from the generated file if requested.
  219. if (CaptureSystemEnv) {
  220. LocalEnvironment = cmSystemTools::GetEnvironmentVariables();
  221. }
  222. // FASTBuild strips off "-isysroot" command line option (see :
  223. // https://github.com/fastbuild/fastbuild/issues/1066).
  224. // If 'SDK_ROOT' is not set via env and '-isysroot' is absent, AppleClang
  225. // seems to use MacOS SDK by default (even though FBuild flattens includes
  226. // before compiling). It breaks cross-compilation for iOS. Tested in
  227. // "RunCMake.Framework" test.
  228. std::string const osxRoot = this->GetSafeGlobalSetting("CMAKE_OSX_SYSROOT");
  229. if (!osxRoot.empty()) {
  230. LocalEnvironment.emplace_back("SDKROOT=" + osxRoot);
  231. }
  232. auto const EnvOverrides =
  233. this->GetSafeGlobalSetting(FASTBUILD_ENV_OVERRIDES);
  234. if (!EnvOverrides.empty()) {
  235. auto const overrideEnvVar = [this](std::string const& prefix,
  236. std::string val) {
  237. auto const iter =
  238. std::find_if(LocalEnvironment.begin(), LocalEnvironment.end(),
  239. [&prefix](std::string const& value) {
  240. return cmSystemTools::StringStartsWith(value.c_str(),
  241. prefix.c_str());
  242. });
  243. if (iter != LocalEnvironment.end()) {
  244. *iter = std::move(val);
  245. } else {
  246. LocalEnvironment.emplace_back(std::move(val));
  247. }
  248. };
  249. for (auto const& val : cmList{ EnvOverrides }) {
  250. auto const pos = val.find('=');
  251. if (pos != std::string::npos && ((pos + 1) < val.size())) {
  252. overrideEnvVar(val.substr(0, pos + 1), val);
  253. }
  254. }
  255. }
  256. // Empty strings are not allowed.
  257. LocalEnvironment.erase(
  258. std::remove_if(LocalEnvironment.begin(), LocalEnvironment.end(),
  259. [](std::string const& s) { return s.empty(); }),
  260. LocalEnvironment.end());
  261. }
  262. std::unique_ptr<cmGlobalGeneratorFactory>
  263. cmGlobalFastbuildGenerator::NewFactory()
  264. {
  265. return std::unique_ptr<cmGlobalGeneratorFactory>(
  266. new cmGlobalGeneratorSimpleFactory<cmGlobalFastbuildGenerator>());
  267. }
  268. bool cmGlobalFastbuildGenerator::CheckLanguages(
  269. std::vector<std::string> const& languages, cmMakefile* mf) const
  270. {
  271. if (std::find(languages.begin(), languages.end(), "CUDA") !=
  272. languages.end()) {
  273. mf->IssueMessage(MessageType::FATAL_ERROR,
  274. "The FASTBuild generator does not support CUDA yet.");
  275. return false;
  276. }
  277. return true;
  278. }
  279. void cmGlobalFastbuildGenerator::EnableLanguage(
  280. std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
  281. {
  282. this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
  283. for (std::string const& l : lang) {
  284. if (l == "NONE") {
  285. continue;
  286. }
  287. this->ResolveLanguageCompiler(l, mf, optional);
  288. }
  289. }
  290. bool cmGlobalFastbuildGenerator::FindMakeProgram(cmMakefile* mf)
  291. {
  292. if (!cmGlobalGenerator::FindMakeProgram(mf)) {
  293. return false;
  294. }
  295. if (auto fastbuildCommand = mf->GetDefinition("CMAKE_MAKE_PROGRAM")) {
  296. this->FastbuildCommand = *fastbuildCommand;
  297. std::vector<std::string> command;
  298. command.push_back(this->FastbuildCommand);
  299. command.emplace_back("-version");
  300. std::string version;
  301. std::string error;
  302. if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr,
  303. nullptr,
  304. cmSystemTools::OUTPUT_NONE)) {
  305. mf->IssueMessage(MessageType::FATAL_ERROR,
  306. "Running\n '" + cmJoin(command, "' '") +
  307. "'\n"
  308. "failed with:\n " +
  309. error);
  310. cmSystemTools::SetFatalErrorOccurred();
  311. return false;
  312. }
  313. cmsys::RegularExpression versionRegex(R"(^FASTBuild v([0-9]+\.[0-9]+))");
  314. versionRegex.find(version);
  315. this->FastbuildVersion = versionRegex.match(1);
  316. }
  317. return true;
  318. }
  319. std::unique_ptr<cmLocalGenerator>
  320. cmGlobalFastbuildGenerator::CreateLocalGenerator(cmMakefile* makefile)
  321. {
  322. return std::unique_ptr<cmLocalGenerator>(
  323. cm::make_unique<cmLocalFastbuildGenerator>(this, makefile));
  324. }
  325. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  326. cmGlobalFastbuildGenerator::GenerateBuildCommand(
  327. std::string const& makeProgram, std::string const& /*projectName*/,
  328. std::string const& projectDir, std::vector<std::string> const& targetNames,
  329. std::string const& /*config*/, int /*jobs*/, bool verbose,
  330. cmBuildOptions /*buildOptions*/, std::vector<std::string> const& makeOptions)
  331. {
  332. GeneratedMakeCommand makeCommand;
  333. this->FastbuildCommand = this->SelectMakeProgram(makeProgram);
  334. makeCommand.Add(this->FastbuildCommand);
  335. // A build command for fastbuild looks like this:
  336. // fbuild.exe [make-options] [-config projectName.bff] <target>
  337. std::string configFile = cmStrCat(projectDir, '/', FASTBUILD_BUILD_FILE);
  338. // Push in the make options
  339. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  340. if (!configFile.empty()) {
  341. makeCommand.Add("-config", configFile);
  342. }
  343. // Tested in "RunCMake.SymlinkTrees" test.
  344. makeCommand.Add("-continueafterdbmove");
  345. // Tested in RunCMake.LinkWhatYouUse on Linux. (We need to see output of
  346. // LinkerStampExe process).
  347. // In general, it might be useful to see output of external processes
  348. // regardless of their outcome.
  349. makeCommand.Add("-showcmdoutput");
  350. // Add the target-config to the command
  351. for (auto const& tname : targetNames) {
  352. if (!tname.empty()) {
  353. makeCommand.Add(tname);
  354. }
  355. }
  356. if (verbose) {
  357. makeCommand.Add("-verbose");
  358. }
  359. // Make "rebuild-bff" target up-to-date before running the build.
  360. std::string output;
  361. ExecuteFastbuildTarget(projectDir, FASTBUILD_REBUILD_BFF_TARGET_NAME, output,
  362. { "-why" });
  363. // If fbuild.bff was re-generated we need to "restat" it.
  364. if (output.find("Need to build") != std::string::npos) {
  365. // Let the user know that re-generation happened (and why it
  366. // happened).
  367. cmSystemTools::Stdout(output);
  368. // FASTBuild will consider the target out-of-date in case some of the
  369. // inputs have changes after re-generation which might happen if, for
  370. // example, configuration depends on some files generated during
  371. // the configuration itself.
  372. AskCMakeToMakeRebuildBFFUpToDate(projectDir);
  373. }
  374. return { std::move(makeCommand) };
  375. }
  376. void cmGlobalFastbuildGenerator::ComputeTargetObjectDirectory(
  377. cmGeneratorTarget* gt) const
  378. {
  379. // Compute full path to object file directory for this target.
  380. std::string dir =
  381. cmStrCat(gt->GetSupportDirectory(), '/', this->GetCMakeCFGIntDir(), '/');
  382. gt->ObjectDirectory = std::move(dir);
  383. }
  384. void cmGlobalFastbuildGenerator::AppendDirectoryForConfig(
  385. std::string const& prefix, std::string const& config,
  386. std::string const& suffix, std::string& dir)
  387. {
  388. if (!config.empty() && this->IsMultiConfig()) {
  389. dir += cmStrCat(prefix, config, suffix);
  390. }
  391. }
  392. cmDocumentationEntry cmGlobalFastbuildGenerator::GetDocumentation()
  393. {
  394. return { cmGlobalFastbuildGenerator::GetActualName(),
  395. "Generates fbuild.bff files." };
  396. }
  397. void cmGlobalFastbuildGenerator::Generate()
  398. {
  399. // Check minimum Fastbuild version.
  400. if (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  401. this->FastbuildVersion,
  402. RequiredFastbuildVersion())) {
  403. std::ostringstream msg;
  404. msg << "The detected version of Fastbuild (" << this->FastbuildVersion;
  405. msg << ") is less than the version of Fastbuild required by CMake (";
  406. msg << this->RequiredFastbuildVersion() << ").";
  407. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  408. msg.str());
  409. return;
  410. }
  411. this->ProcessEnvironment();
  412. this->OpenBuildFileStream();
  413. this->WriteSettings();
  414. this->WriteEnvironment();
  415. // Execute the standard generate process
  416. cmGlobalGenerator::Generate();
  417. // Write compilers
  418. this->WriteCompilers();
  419. this->WriteTargets();
  420. this->CloseBuildFileStream();
  421. if (cmSystemTools::GetErrorOccurredFlag()) {
  422. return;
  423. }
  424. this->RemoveUnknownClangTidyExportFixesFiles();
  425. if (this->GetCMakeInstance()->GetRegenerateDuringBuild()) {
  426. return;
  427. }
  428. // TODO: figure out how to skip this in TryCompile
  429. // Make "rebuild-bff" target up-to-date after the generation.
  430. // This is actually a noop, it just asks CMake to touch the generated file
  431. // so FASTBuild would consider the target as up-to-date.
  432. AskCMakeToMakeRebuildBFFUpToDate(
  433. this->GetCMakeInstance()->GetHomeOutputDirectory());
  434. }
  435. void cmGlobalFastbuildGenerator::AskCMakeToMakeRebuildBFFUpToDate(
  436. std::string const& workingDir) const
  437. {
  438. // "restat" the generated build file.
  439. // The idea here is to mimic what Ninja's "restat" command does.
  440. // We need to make the "rebuild.bff" target up-to-date, so the regeneration
  441. // will only be triggered when CMake files have actually changed.
  442. // Tested in "RunCMake.Configure" test.
  443. cmsys::ofstream{
  444. cmStrCat(workingDir, '/', FASTBUILD_RESTAT_FILE).c_str(),
  445. std::ios::out | std::ios::binary
  446. } << cmStrCat(workingDir, '/', FASTBUILD_BUILD_FILE);
  447. std::string output;
  448. ExecuteFastbuildTarget(workingDir, FASTBUILD_REBUILD_BFF_TARGET_NAME,
  449. output);
  450. }
  451. void cmGlobalFastbuildGenerator::ExecuteFastbuildTarget(
  452. std::string const& dir, std::string const& target, std::string& output,
  453. std::vector<std::string> const& fbuildOptions) const
  454. {
  455. std::vector<std::string> command;
  456. command.emplace_back(this->FastbuildCommand);
  457. command.emplace_back("-config");
  458. std::string const file = cmStrCat(dir, '/', FASTBUILD_BUILD_FILE);
  459. command.emplace_back(file);
  460. command.emplace_back(target);
  461. if (!fbuildOptions.empty()) {
  462. command.emplace_back(cmJoin(fbuildOptions, " "));
  463. }
  464. int retVal = 0;
  465. if (!cmSystemTools::RunSingleCommand(command, &output, nullptr, &retVal,
  466. dir.c_str(),
  467. cmSystemTools::OUTPUT_NONE) ||
  468. retVal != 0) {
  469. cmSystemTools::Error(cmStrCat("Failed to run FASTBuild command:\n '",
  470. cmJoin(command, "' '"), "'\nOutput:\n",
  471. output));
  472. cmSystemTools::Stdout(output);
  473. std::exit(retVal);
  474. }
  475. }
  476. void cmGlobalFastbuildGenerator::WriteSettings()
  477. {
  478. // Define some placeholder
  479. WriteDivider();
  480. *this->BuildFileStream << "// Helper variables\n\n";
  481. WriteVariable("FB_INPUT_1_PLACEHOLDER", Quote("\"%1\""));
  482. WriteVariable("FB_INPUT_1_0_PLACEHOLDER", Quote("\"%1[0]\""));
  483. WriteVariable("FB_INPUT_1_1_PLACEHOLDER", Quote("\"%1[1]\""));
  484. WriteVariable("FB_INPUT_2_PLACEHOLDER", Quote("\"%2\""));
  485. WriteVariable("FB_INPUT_3_PLACEHOLDER", Quote("\"%3\""));
  486. std::string cacheDir;
  487. // If explicitly set from CMake.
  488. auto val = this->GetSafeGlobalSetting(FASTBUILD_CACHE_PATH);
  489. if (!val.empty()) {
  490. cacheDir = std::move(val);
  491. cmSystemTools::ConvertToOutputSlashes(cacheDir);
  492. }
  493. WriteDivider();
  494. *this->BuildFileStream << "// Settings\n\n";
  495. WriteCommand("Settings");
  496. *this->BuildFileStream << "{\n";
  497. if (!cacheDir.empty()) {
  498. WriteVariable("CachePath", Quote(cacheDir), 1);
  499. }
  500. // Concurrency groups.
  501. WriteStruct(
  502. FASTBUILD_UTIL_CONCURRENCY_GROUP_NAME,
  503. { { "ConcurrencyGroupName", Quote(FASTBUILD_UTIL_CONCURRENCY_GROUP_NAME) },
  504. { "ConcurrencyLimit", "1" } },
  505. 1);
  506. WriteArray("ConcurrencyGroups",
  507. { "." FASTBUILD_UTIL_CONCURRENCY_GROUP_NAME }, 1);
  508. *this->BuildFileStream << "}\n";
  509. }
  510. void cmGlobalFastbuildGenerator::WriteEnvironment()
  511. {
  512. if (!LocalEnvironment.empty()) {
  513. WriteArray(FASTBUILD_ENV_VAR_NAME, Wrap(LocalEnvironment), 0);
  514. }
  515. }
  516. void cmGlobalFastbuildGenerator::WriteDivider()
  517. {
  518. *this->BuildFileStream << "// ======================================"
  519. "=======================================\n";
  520. }
  521. void cmGlobalFastbuildGenerator::Indent(int count)
  522. {
  523. for (int i = 0; i < count; ++i) {
  524. *this->BuildFileStream << " ";
  525. }
  526. }
  527. void cmGlobalFastbuildGenerator::WriteComment(std::string const& comment,
  528. int indent)
  529. {
  530. if (comment.empty()) {
  531. return;
  532. }
  533. std::string::size_type lpos = 0;
  534. std::string::size_type rpos;
  535. *this->BuildFileStream << "\n";
  536. Indent(indent);
  537. *this->BuildFileStream << "/////////////////////////////////////////////\n";
  538. while ((rpos = comment.find('\n', lpos)) != std::string::npos) {
  539. Indent(indent);
  540. *this->BuildFileStream << "// " << comment.substr(lpos, rpos - lpos)
  541. << "\n";
  542. lpos = rpos + 1;
  543. }
  544. Indent(indent);
  545. *this->BuildFileStream << "// " << comment.substr(lpos) << "\n\n";
  546. }
  547. void cmGlobalFastbuildGenerator::WriteVariable(std::string const& key,
  548. std::string const& value,
  549. int indent)
  550. {
  551. WriteVariable(key, value, "=", indent);
  552. }
  553. void cmGlobalFastbuildGenerator::WriteVariable(std::string const& key,
  554. std::string const& value,
  555. std::string const& op,
  556. int indent)
  557. {
  558. Indent(indent);
  559. *this->BuildFileStream << "." << key << " " + op + (value.empty() ? "" : " ")
  560. << value << "\n";
  561. }
  562. void cmGlobalFastbuildGenerator::WriteCommand(std::string const& command,
  563. std::string const& value,
  564. int indent)
  565. {
  566. Indent(indent);
  567. *this->BuildFileStream << command;
  568. if (!value.empty()) {
  569. *this->BuildFileStream << "(" << value << ")";
  570. }
  571. *this->BuildFileStream << "\n";
  572. }
  573. void cmGlobalFastbuildGenerator::WriteArray(
  574. std::string const& key, std::vector<std::string> const& values, int indent)
  575. {
  576. WriteArray(key, values, "=", indent);
  577. }
  578. void cmGlobalFastbuildGenerator::WriteArray(
  579. std::string const& key, std::vector<std::string> const& values,
  580. std::string const& op, int indent)
  581. {
  582. WriteVariable(key, "", op, indent);
  583. Indent(indent);
  584. *this->BuildFileStream << "{\n";
  585. char const* sep = "";
  586. for (std::string const& value : values) {
  587. *this->BuildFileStream << sep;
  588. sep = ",\n";
  589. Indent(indent + 1);
  590. *this->BuildFileStream << value;
  591. }
  592. *this->BuildFileStream << "\n";
  593. Indent(indent);
  594. *this->BuildFileStream << "}\n";
  595. }
  596. void cmGlobalFastbuildGenerator::WriteStruct(
  597. std::string const& name,
  598. std::vector<std::pair<std::string, std::string>> const& variables,
  599. int indent)
  600. {
  601. WriteVariable(name, "", "=", indent);
  602. Indent(indent);
  603. *this->BuildFileStream << "[\n";
  604. for (auto const& val : variables) {
  605. auto const& key = val.first;
  606. auto const& value = val.second;
  607. WriteVariable(key, value, "=", indent + 1);
  608. }
  609. Indent(indent);
  610. *this->BuildFileStream << "]\n";
  611. }
  612. std::string cmGlobalFastbuildGenerator::Quote(std::string const& str,
  613. std::string const& quotation)
  614. {
  615. std::string result = str;
  616. cmSystemTools::ReplaceString(result, quotation, "^" + quotation);
  617. cmSystemTools::ReplaceString(result, FASTBUILD_DOLLAR_TAG, "$");
  618. return quotation + result + quotation;
  619. }
  620. std::string cmGlobalFastbuildGenerator::QuoteIfHasSpaces(std::string str)
  621. {
  622. if (str.find(' ') != std::string::npos) {
  623. return '"' + str + '"';
  624. }
  625. return str;
  626. }
  627. struct WrapHelper
  628. {
  629. std::string Prefix;
  630. std::string Suffix;
  631. bool EscapeDollar;
  632. std::string operator()(std::string in)
  633. {
  634. // If we have ^ in env variable - need to escape it.
  635. cmSystemTools::ReplaceString(in, "^", "^^");
  636. // Those all are considered as line ends by FASTBuild.
  637. cmSystemTools::ReplaceString(in, "\n", "\\n");
  638. cmSystemTools::ReplaceString(in, "\r", "\\r");
  639. // Escaping of single quotes tested in "RunCMake.CompilerArgs" test.
  640. cmSystemTools::ReplaceString(in, "'", "^'");
  641. std::string result = Prefix + in + Suffix;
  642. if (EscapeDollar) {
  643. cmSystemTools::ReplaceString(result, "$", "^$");
  644. cmSystemTools::ReplaceString(result, FASTBUILD_DOLLAR_TAG, "$");
  645. }
  646. return result;
  647. }
  648. std::string operator()(FastbuildTargetDep const& in)
  649. {
  650. return (*this)(in.Name);
  651. }
  652. };
  653. template <class T>
  654. std::vector<std::string> cmGlobalFastbuildGenerator::Wrap(
  655. T const& in, std::string const& prefix, std::string const& suffix,
  656. bool const escape_dollar)
  657. {
  658. std::vector<std::string> result;
  659. WrapHelper helper = { prefix, suffix, escape_dollar };
  660. std::transform(in.begin(), in.end(), std::back_inserter(result), helper);
  661. return result;
  662. }
  663. void cmGlobalFastbuildGenerator::TopologicalSort(
  664. std::vector<FastbuildTargetPtrT>& nodes)
  665. {
  666. std::unordered_map<std::string, int> inDegree;
  667. std::unordered_map<std::string, std::set<std::string>> reverseDeps;
  668. std::unordered_map<std::string, std::size_t> originalIndex;
  669. // Track original positions
  670. for (std::size_t i = 0; i < nodes.size(); ++i) {
  671. auto const& node = nodes[i];
  672. inDegree[node->Name] = 0;
  673. originalIndex[node->Name] = i;
  674. }
  675. // Build reverse dependency graph and in-degree map
  676. for (auto const& node : nodes) {
  677. for (auto const& dep : node->PreBuildDependencies) {
  678. if (inDegree.count(dep.Name)) {
  679. reverseDeps[dep.Name].insert(node->Name);
  680. ++inDegree[node->Name];
  681. }
  682. }
  683. }
  684. // Min-heap based on original position
  685. auto const cmp = [&](std::string const& a, std::string const& b) {
  686. return originalIndex[a] > originalIndex[b];
  687. };
  688. std::priority_queue<std::string, std::vector<std::string>, decltype(cmp)>
  689. zeroInDegree(cmp);
  690. for (auto const& val : inDegree) {
  691. auto const& degree = val.second;
  692. auto const& name = val.first;
  693. if (degree == 0) {
  694. zeroInDegree.push(name);
  695. }
  696. }
  697. std::vector<std::string> sorted;
  698. while (!zeroInDegree.empty()) {
  699. std::string node = zeroInDegree.top();
  700. zeroInDegree.pop();
  701. sorted.push_back(node);
  702. for (auto const& dep : reverseDeps[node]) {
  703. if (--inDegree[dep] == 0) {
  704. zeroInDegree.push(dep);
  705. }
  706. }
  707. }
  708. if (sorted.size() != nodes.size()) {
  709. cmSystemTools::Error("Failed to sort (Cyclic dependency)");
  710. cmSystemTools::Error(cmStrCat("Sorted size: ", sorted.size()));
  711. cmSystemTools::Error(cmStrCat("nodes size: ", nodes.size()));
  712. for (auto const& node : nodes) {
  713. cmSystemTools::Error("Node: " + node->Name);
  714. for (auto const& dep : reverseDeps[node->Name]) {
  715. cmSystemTools::Error("\tReverse dep: " + dep);
  716. }
  717. for (auto const& child : node->PreBuildDependencies) {
  718. cmSystemTools::Error("\tChild: " + child.Name);
  719. }
  720. }
  721. for (auto const& node : sorted) {
  722. cmSystemTools::Error("Sorted: " + node);
  723. }
  724. for (auto const& node : nodes) {
  725. cmSystemTools::Error("In node: " + node->Name);
  726. }
  727. }
  728. // Reconstruct sorted nodes
  729. std::vector<FastbuildTargetPtrT> result;
  730. for (auto const& name : sorted) {
  731. auto it = std::find_if(
  732. nodes.begin(), nodes.end(), [&name](FastbuildTargetPtrT const& node) {
  733. return node /* the node might be in moved-from state*/ &&
  734. node->Name == name;
  735. });
  736. if (it != nodes.end()) {
  737. result.emplace_back(std::move(*it));
  738. }
  739. }
  740. std::swap(result, nodes);
  741. }
  742. void cmGlobalFastbuildGenerator::WriteDisclaimer()
  743. {
  744. *this->BuildFileStream << "// CMAKE generated file: DO NOT EDIT!\n"
  745. << "// Generated by \"" << this->GetName() << "\""
  746. << " Generator, CMake Version "
  747. << cmVersion::GetMajorVersion() << "."
  748. << cmVersion::GetMinorVersion() << "\n\n";
  749. }
  750. void cmGlobalFastbuildGenerator::OpenBuildFileStream()
  751. {
  752. // Compute Fastbuild's build file path.
  753. std::string buildFilePath =
  754. this->GetCMakeInstance()->GetHomeOutputDirectory();
  755. buildFilePath += "/";
  756. buildFilePath += FASTBUILD_BUILD_FILE;
  757. // Get a stream where to generate things.
  758. if (!this->BuildFileStream) {
  759. this->BuildFileStream = cm::make_unique<cmGeneratedFileStream>(
  760. buildFilePath, false, this->GetMakefileEncoding());
  761. if (!this->BuildFileStream) {
  762. // An error message is generated by the constructor if it cannot
  763. // open the file.
  764. return;
  765. }
  766. }
  767. // Write the do not edit header.
  768. this->WriteDisclaimer();
  769. // Write a comment about this file.
  770. *this->BuildFileStream
  771. << "// This file contains all the build statements\n\n";
  772. }
  773. void cmGlobalFastbuildGenerator::CloseBuildFileStream()
  774. {
  775. if (this->BuildFileStream) {
  776. this->BuildFileStream.reset();
  777. } else {
  778. cmSystemTools::Error("Build file stream was not open.");
  779. }
  780. }
  781. void cmGlobalFastbuildGenerator::WriteCompilers()
  782. {
  783. WriteDivider();
  784. *this->BuildFileStream << "// Compilers\n\n";
  785. for (auto const& val : Compilers) {
  786. auto const& compilerDef = val.second;
  787. std::string compilerPath = compilerDef.Executable;
  788. // Write out the compiler that has been configured
  789. WriteCommand("Compiler", Quote(compilerDef.Name));
  790. *this->BuildFileStream << "{\n";
  791. for (auto const& extra : compilerDef.ExtraVariables) {
  792. auto const& extraKey = extra.first;
  793. auto const& extraVal = extra.second;
  794. WriteVariable(extraKey, Quote(extraVal), 1);
  795. }
  796. WriteVariable("Executable", Quote(compilerPath), 1);
  797. WriteVariable("CompilerFamily", Quote(compilerDef.CompilerFamily), 1);
  798. if (compilerDef.UseLightCache && compilerDef.CompilerFamily == "msvc") {
  799. WriteVariable("UseLightCache_Experimental", "true", 1);
  800. }
  801. if (compilerDef.UseRelativePaths) {
  802. WriteVariable("UseRelativePaths_Experimental", "true", 1);
  803. }
  804. if (compilerDef.UseDeterministicPaths) {
  805. WriteVariable("UseDeterministicPaths_Experimental", "true", 1);
  806. }
  807. if (!compilerDef.SourceMapping.empty()) {
  808. WriteVariable("SourceMapping_Experimental",
  809. Quote(compilerDef.SourceMapping), 1);
  810. }
  811. auto const isClang = [&compilerDef] {
  812. return compilerDef.CompilerFamily == "clang" ||
  813. compilerDef.CompilerFamily == "clang-cl";
  814. };
  815. if (!compilerDef.ClangRewriteIncludes && isClang()) {
  816. WriteVariable("ClangRewriteIncludes", "false", 1);
  817. }
  818. if (compilerDef.ClangGCCUpdateXLanguageArg &&
  819. (isClang() || compilerDef.CompilerFamily == "gcc")) {
  820. WriteVariable("ClangGCCUpdateXLanguageArg", "true", 1);
  821. }
  822. if (compilerDef.AllowResponseFile) {
  823. WriteVariable("AllowResponseFile", "true", 1);
  824. }
  825. if (compilerDef.ForceResponseFile) {
  826. WriteVariable("ForceResponseFile", "true", 1);
  827. }
  828. if (compilerDef.DontUseEnv) {
  829. LogMessage("Not using system environment");
  830. } else {
  831. if (!LocalEnvironment.empty()) {
  832. WriteVariable("Environment", "." FASTBUILD_ENV_VAR_NAME, 1);
  833. }
  834. }
  835. if (!compilerDef.ExtraFiles.empty()) {
  836. // Do not escape '$' sign, CMAKE_${LANG}_FASTBUILD_EXTRA_FILES might
  837. // contain FB variables to be expanded (we do use some internally).
  838. // Besides a path cannot contain a '$'
  839. WriteArray("ExtraFiles", Wrap(compilerDef.ExtraFiles, "'", "'", false),
  840. 1);
  841. }
  842. *this->BuildFileStream << "}\n";
  843. auto const compilerId = compilerDef.Name;
  844. WriteVariable(compilerId, Quote(compilerDef.Name));
  845. *this->BuildFileStream << "\n";
  846. }
  847. // We need this because the Library command needs a compiler
  848. // even if don't compile anything
  849. if (!this->Compilers.empty()) {
  850. WriteVariable("Compiler_dummy",
  851. Quote(this->Compilers.begin()->second.Name));
  852. }
  853. }
  854. void cmGlobalFastbuildGenerator::AddCompiler(std::string const& language,
  855. cmMakefile* mf)
  856. {
  857. if (this->Compilers.find(FASTBUILD_COMPILER_PREFIX + language) !=
  858. this->Compilers.end()) {
  859. return;
  860. }
  861. // Calculate the root location of the compiler
  862. std::string const variableString = "CMAKE_" + language + "_COMPILER";
  863. std::string const compilerLocation = mf->GetSafeDefinition(variableString);
  864. if (compilerLocation.empty()) {
  865. return;
  866. }
  867. // Calculate the i18n number.
  868. std::string i18nNum = "1033";
  869. // Add the language to the compiler's name
  870. FastbuildCompiler compilerDef;
  871. compilerDef.ExtraVariables["Root"] =
  872. cmSystemTools::GetFilenamePath(compilerLocation);
  873. compilerDef.Name = FASTBUILD_COMPILER_PREFIX + language;
  874. compilerDef.Executable = compilerLocation;
  875. compilerDef.CmakeCompilerID =
  876. mf->GetSafeDefinition("CMAKE_" + language + "_COMPILER_ID");
  877. if (compilerDef.CmakeCompilerID == "Clang" &&
  878. mf->GetSafeDefinition("CMAKE_" + language +
  879. "_COMPILER_FRONTEND_VARIANT") == "MSVC") {
  880. compilerDef.CmakeCompilerID = "Clang-cl";
  881. }
  882. compilerDef.CmakeCompilerVersion =
  883. mf->GetSafeDefinition("CMAKE_" + language + "_COMPILER_VERSION");
  884. compilerDef.Language = language;
  885. cmExpandList(mf->GetSafeDefinition(FASTBUILD_COMPILER_EXTRA_FILES),
  886. compilerDef.ExtraFiles);
  887. if (supportedLanguages.find(language) != supportedLanguages.end()) {
  888. auto const iter =
  889. compilerIdToFastbuildFamily.find(compilerDef.CmakeCompilerID);
  890. if (iter != compilerIdToFastbuildFamily.end()) {
  891. compilerDef.CompilerFamily = iter->second;
  892. }
  893. }
  894. // Has to be called after we determined 'CompilerFamily'.
  895. ReadCompilerOptions(compilerDef, mf);
  896. // If FASTBUILD_COMPILER_EXTRA_FILES is not set - automatically add extra
  897. // files based on compiler (see
  898. // https://fastbuild.org/docs/functions/compiler.html)
  899. if (compilerDef.ExtraFiles.empty() &&
  900. (language == "C" || language == "CXX") &&
  901. compilerDef.CmakeCompilerID == "MSVC") {
  902. // https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
  903. // Visual Studio 17 (19.30 to 19.39)
  904. // TODO
  905. // Visual Studio 16 (19.20 to 19.29)
  906. if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  907. compilerDef.CmakeCompilerVersion,
  908. "19.20")) {
  909. compilerDef.ExtraFiles.push_back("$Root$/c1.dll");
  910. compilerDef.ExtraFiles.push_back("$Root$/c1xx.dll");
  911. compilerDef.ExtraFiles.push_back("$Root$/c2.dll");
  912. compilerDef.ExtraFiles.push_back(
  913. "$Root$/atlprov.dll"); // Only needed if using ATL
  914. compilerDef.ExtraFiles.push_back("$Root$/msobj140.dll");
  915. compilerDef.ExtraFiles.push_back("$Root$/mspdb140.dll");
  916. compilerDef.ExtraFiles.push_back("$Root$/mspdbcore.dll");
  917. compilerDef.ExtraFiles.push_back("$Root$/mspdbsrv.exe");
  918. compilerDef.ExtraFiles.push_back("$Root$/mspft140.dll");
  919. compilerDef.ExtraFiles.push_back("$Root$/msvcp140.dll");
  920. compilerDef.ExtraFiles.push_back(
  921. "$Root$/msvcp140_atomic_wait.dll"); // Required circa 16.8.3
  922. // (14.28.29333)
  923. compilerDef.ExtraFiles.push_back(
  924. "$Root$/tbbmalloc.dll"); // Required as of 16.2 (14.22.27905)
  925. compilerDef.ExtraFiles.push_back("$Root$/vcruntime140.dll");
  926. compilerDef.ExtraFiles.push_back(
  927. "$Root$/vcruntime140_1.dll"); // Required as of 16.5.1 (14.25.28610)
  928. compilerDef.ExtraFiles.push_back("$Root$/" + i18nNum + "/clui.dll");
  929. compilerDef.ExtraFiles.push_back(
  930. "$Root$/" + i18nNum + "/mspft140ui.dll"); // Localized messages for
  931. // static analysis
  932. }
  933. // Visual Studio 15 (19.10 to 19.19)
  934. else if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  935. compilerDef.CmakeCompilerVersion,
  936. "19.10")) {
  937. compilerDef.ExtraFiles.push_back("$Root$/c1.dll");
  938. compilerDef.ExtraFiles.push_back("$Root$/c1xx.dll");
  939. compilerDef.ExtraFiles.push_back("$Root$/c2.dll");
  940. compilerDef.ExtraFiles.push_back(
  941. "$Root$/atlprov.dll"); // Only needed if using ATL
  942. compilerDef.ExtraFiles.push_back("$Root$/msobj140.dll");
  943. compilerDef.ExtraFiles.push_back("$Root$/mspdb140.dll");
  944. compilerDef.ExtraFiles.push_back("$Root$/mspdbcore.dll");
  945. compilerDef.ExtraFiles.push_back("$Root$/mspdbsrv.exe");
  946. compilerDef.ExtraFiles.push_back("$Root$/mspft140.dll");
  947. compilerDef.ExtraFiles.push_back("$Root$/msvcp140.dll");
  948. compilerDef.ExtraFiles.push_back("$Root$/vcruntime140.dll");
  949. compilerDef.ExtraFiles.push_back("$Root$/" + i18nNum + "/clui.dll");
  950. }
  951. }
  952. // TODO: Handle Intel compiler
  953. this->Compilers[compilerDef.Name] = std::move(compilerDef);
  954. }
  955. void cmGlobalFastbuildGenerator::AddLauncher(std::string const& prefix,
  956. std::string const& launcher,
  957. std::string const& language,
  958. std::string const& args)
  959. {
  960. if (this->Compilers.find(prefix + language) != this->Compilers.end()) {
  961. return;
  962. }
  963. LogMessage("Launcher: " + launcher);
  964. LogMessage("Launcher args: " + args);
  965. FastbuildCompiler compilerDef;
  966. compilerDef.Name = prefix + language;
  967. compilerDef.Args = args;
  968. if (cmSystemTools::FileIsFullPath(launcher)) {
  969. compilerDef.Executable = launcher;
  970. } else {
  971. // FASTBuild needs an absolute path to the executable.
  972. compilerDef.Executable = cmSystemTools::FindProgram(launcher);
  973. if (compilerDef.Executable.empty()) {
  974. cmSystemTools::Error("Failed to find path to " + launcher);
  975. return;
  976. }
  977. }
  978. // When CTest is used as a launcher, there is an interesting env variable
  979. // "CTEST_LAUNCH_LOGS" which is set by parent CTest process and is expected
  980. // to be read from global (sic!) env by the launched CTest process. So we
  981. // will need to make this global env available for CTest executable used as a
  982. // "launcher". Tested in RunCMake.ctest_labels_for_subprojects test..
  983. compilerDef.DontUseEnv = true;
  984. this->Compilers[compilerDef.Name] = std::move(compilerDef);
  985. }
  986. std::string cmGlobalFastbuildGenerator::ConvertToFastbuildPath(
  987. std::string const& path) const
  988. {
  989. cmLocalGenerator const* root = LocalGenerators[0].get();
  990. return root->MaybeRelativeToWorkDir(cmSystemTools::FileIsFullPath(path)
  991. ? cmSystemTools::CollapseFullPath(path)
  992. : path);
  993. }
  994. std::unique_ptr<cmLinkLineComputer>
  995. cmGlobalFastbuildGenerator::CreateLinkLineComputer(
  996. cmOutputConverter* outputConverter,
  997. cmStateDirectory const& /* stateDir */) const
  998. {
  999. return cm::make_unique<cmFastbuildLinkLineComputer>(
  1000. outputConverter,
  1001. this->LocalGenerators[0]->GetStateSnapshot().GetDirectory(), this);
  1002. }
  1003. void cmGlobalFastbuildGenerator::WriteExec(FastbuildExecNode const& Exec,
  1004. int indent)
  1005. {
  1006. auto const identPlus1 = indent + 1;
  1007. WriteCommand("Exec", Exec.Name.empty() ? std::string{} : Quote(Exec.Name),
  1008. indent);
  1009. Indent(indent);
  1010. *BuildFileStream << "{\n";
  1011. {
  1012. if (!Exec.PreBuildDependencies.empty()) {
  1013. WriteArray("PreBuildDependencies", Wrap(Exec.PreBuildDependencies),
  1014. identPlus1);
  1015. }
  1016. WriteVariable("ExecExecutable", Quote(Exec.ExecExecutable), identPlus1);
  1017. if (!Exec.ExecArguments.empty()) {
  1018. WriteVariable("ExecArguments", Quote(Exec.ExecArguments), identPlus1);
  1019. }
  1020. if (!Exec.ExecWorkingDir.empty()) {
  1021. WriteVariable("ExecWorkingDir", Quote(Exec.ExecWorkingDir), identPlus1);
  1022. }
  1023. if (!Exec.ExecInput.empty()) {
  1024. WriteArray("ExecInput", Wrap(Exec.ExecInput), identPlus1);
  1025. }
  1026. if (Exec.ExecUseStdOutAsOutput) {
  1027. WriteVariable("ExecUseStdOutAsOutput", "true", identPlus1);
  1028. }
  1029. if (!Exec.ExecInputPath.empty()) {
  1030. WriteArray("ExecInputPath", Wrap(Exec.ExecInputPath), identPlus1);
  1031. }
  1032. if (!Exec.ExecInputPattern.empty()) {
  1033. WriteArray("ExecInputPattern", Wrap(Exec.ExecInputPattern), identPlus1);
  1034. }
  1035. WriteVariable("ExecAlwaysShowOutput", "true", identPlus1);
  1036. WriteVariable("ExecOutput", Quote(Exec.ExecOutput), identPlus1);
  1037. WriteVariable("ExecAlways", Exec.ExecAlways ? "true" : "false",
  1038. identPlus1);
  1039. if (!Exec.ConcurrencyGroupName.empty()) {
  1040. WriteVariable("ConcurrencyGroupName", Quote(Exec.ConcurrencyGroupName),
  1041. identPlus1);
  1042. }
  1043. }
  1044. Indent(indent);
  1045. *BuildFileStream << "}\n";
  1046. static bool const verbose = GlobalSettingIsOn(FASTBUILD_VERBOSE_GENERATOR) ||
  1047. cmSystemTools::HasEnv(FASTBUILD_VERBOSE_GENERATOR);
  1048. // Those aliases are only used for troubleshooting the generated file.
  1049. if (verbose) {
  1050. WriteAlias(Exec.OutputsAlias);
  1051. WriteAlias(Exec.ByproductsAlias);
  1052. }
  1053. }
  1054. void cmGlobalFastbuildGenerator::WriteUnity(FastbuildUnityNode const& Unity)
  1055. {
  1056. WriteCommand("Unity", Quote(Unity.Name), 1);
  1057. Indent(1);
  1058. *BuildFileStream << "{\n";
  1059. {
  1060. WriteVariable("UnityOutputPath", Quote(Unity.UnityOutputPath), 2);
  1061. WriteVariable("UnityOutputPattern", Quote(Unity.UnityOutputPattern), 2);
  1062. WriteArray("UnityInputFiles", Wrap(Unity.UnityInputFiles), 2);
  1063. if (!Unity.UnityInputIsolatedFiles.empty()) {
  1064. WriteArray("UnityInputIsolatedFiles",
  1065. Wrap(Unity.UnityInputIsolatedFiles), 2);
  1066. }
  1067. if (UsingRelativePaths) {
  1068. WriteVariable("UseRelativePaths_Experimental", "true", 2);
  1069. }
  1070. }
  1071. Indent(1);
  1072. *BuildFileStream << "}\n";
  1073. }
  1074. void cmGlobalFastbuildGenerator::WriteObjectList(
  1075. FastbuildObjectListNode const& ObjectList, bool allowDistribution)
  1076. {
  1077. WriteCommand("ObjectList", Quote(ObjectList.Name), 1);
  1078. Indent(1);
  1079. *BuildFileStream << "{\n";
  1080. {
  1081. if (!allowDistribution) {
  1082. WriteVariable("AllowDistribution", "false", 2);
  1083. }
  1084. if (!ObjectList.PreBuildDependencies.empty()) {
  1085. WriteArray("PreBuildDependencies", Wrap(ObjectList.PreBuildDependencies),
  1086. 2);
  1087. }
  1088. WriteVariable("Compiler", ObjectList.Compiler, 2);
  1089. // If only PCH output is present - this node reuses existing PCH.
  1090. if (!ObjectList.PCHOutputFile.empty()) {
  1091. WriteVariable("PCHOutputFile", Quote(ObjectList.PCHOutputFile), 2);
  1092. }
  1093. // If PCHInputFile and PCHOptions are present - this node creates PCH.
  1094. if (!ObjectList.PCHInputFile.empty() && !ObjectList.PCHOptions.empty()) {
  1095. WriteVariable("PCHInputFile", Quote(ObjectList.PCHInputFile), 2);
  1096. WriteVariable("PCHOptions", Quote(ObjectList.PCHOptions), 2);
  1097. }
  1098. WriteVariable("CompilerOptions", Quote(ObjectList.CompilerOptions), 2);
  1099. WriteVariable("CompilerOutputPath", Quote(ObjectList.CompilerOutputPath),
  1100. 2);
  1101. WriteVariable("CompilerOutputExtension",
  1102. Quote(ObjectList.CompilerOutputExtension), 2);
  1103. WriteVariable("CompilerOutputKeepBaseExtension", "true", 2);
  1104. if (!ObjectList.CompilerInputUnity.empty()) {
  1105. WriteArray("CompilerInputUnity", Wrap(ObjectList.CompilerInputUnity), 2);
  1106. }
  1107. if (!ObjectList.CompilerInputFiles.empty()) {
  1108. WriteArray("CompilerInputFiles", Wrap(ObjectList.CompilerInputFiles), 2);
  1109. }
  1110. if (!ObjectList.AllowCaching) {
  1111. WriteVariable("AllowCaching", "false", 2);
  1112. }
  1113. if (!ObjectList.AllowDistribution) {
  1114. WriteVariable("AllowDistribution", "false", 2);
  1115. }
  1116. if (ObjectList.Hidden) {
  1117. WriteVariable("Hidden", "true", 2);
  1118. }
  1119. }
  1120. Indent(1);
  1121. *BuildFileStream << "}\n";
  1122. }
  1123. void cmGlobalFastbuildGenerator::WriteLinker(
  1124. FastbuildLinkerNode const& LinkerNode, bool allowDistribution)
  1125. {
  1126. WriteCommand(
  1127. LinkerNode.Type == FastbuildLinkerNode::EXECUTABLE ? "Executable"
  1128. : LinkerNode.Type == FastbuildLinkerNode::SHARED_LIBRARY ? "DLL"
  1129. : "Library",
  1130. (!LinkerNode.Name.empty() && LinkerNode.Name != LinkerNode.LinkerOutput)
  1131. ? Quote(LinkerNode.Name)
  1132. : "",
  1133. 1);
  1134. Indent(1);
  1135. *BuildFileStream << "{\n";
  1136. {
  1137. if (!LinkerNode.PreBuildDependencies.empty()) {
  1138. WriteArray("PreBuildDependencies", Wrap(LinkerNode.PreBuildDependencies),
  1139. 2);
  1140. }
  1141. if (!allowDistribution) {
  1142. WriteVariable("AllowDistribution", "false", 2);
  1143. }
  1144. if (!LinkerNode.Compiler.empty() &&
  1145. LinkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY) {
  1146. WriteVariable("Compiler", LinkerNode.Compiler, 2);
  1147. WriteVariable("CompilerOptions", Quote(LinkerNode.CompilerOptions), 2);
  1148. WriteVariable("CompilerOutputPath", Quote("."), 2);
  1149. }
  1150. if (!LocalEnvironment.empty()) {
  1151. WriteVariable("Environment", "." FASTBUILD_ENV_VAR_NAME, 2);
  1152. }
  1153. WriteVariable(LinkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY
  1154. ? "Librarian"
  1155. : "Linker",
  1156. Quote(LinkerNode.Linker), 2);
  1157. WriteVariable(LinkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY
  1158. ? "LibrarianOptions"
  1159. : "LinkerOptions",
  1160. Quote(LinkerNode.LinkerOptions), 2);
  1161. WriteVariable(LinkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY
  1162. ? "LibrarianOutput"
  1163. : "LinkerOutput",
  1164. Quote(LinkerNode.LinkerOutput), 2);
  1165. if (!LinkerNode.LibrarianAdditionalInputs.empty()) {
  1166. WriteArray(LinkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY
  1167. ? "LibrarianAdditionalInputs"
  1168. : "Libraries",
  1169. Wrap(LinkerNode.LibrarianAdditionalInputs), 2);
  1170. }
  1171. if (!LinkerNode.Libraries2.empty()) {
  1172. WriteArray("Libraries2", Wrap(LinkerNode.Libraries2), 2);
  1173. }
  1174. if (!LinkerNode.LibrarianAdditionalInputs.empty()) {
  1175. if (!LinkerNode.LinkerType.empty()) {
  1176. WriteVariable("LinkerType", Quote(LinkerNode.LinkerType), 2);
  1177. }
  1178. }
  1179. if (LinkerNode.Type == FastbuildLinkerNode::EXECUTABLE ||
  1180. LinkerNode.Type == FastbuildLinkerNode::SHARED_LIBRARY) {
  1181. WriteVariable("LinkerLinkObjects",
  1182. LinkerNode.LinkerLinkObjects ? "true" : "false", 2);
  1183. if (!LinkerNode.LinkerStampExe.empty()) {
  1184. WriteVariable("LinkerStampExe", Quote(LinkerNode.LinkerStampExe), 2);
  1185. if (!LinkerNode.LinkerStampExeArgs.empty()) {
  1186. WriteVariable("LinkerStampExeArgs",
  1187. Quote(LinkerNode.LinkerStampExeArgs), 2);
  1188. }
  1189. }
  1190. }
  1191. Indent(1);
  1192. *BuildFileStream << "}\n";
  1193. }
  1194. }
  1195. void cmGlobalFastbuildGenerator::WriteAlias(FastbuildAliasNode const& Alias,
  1196. int indent)
  1197. {
  1198. if (Alias.PreBuildDependencies.empty()) {
  1199. return;
  1200. }
  1201. auto const identPlus1 = indent + 1;
  1202. WriteCommand("Alias", Quote(Alias.Name), indent);
  1203. Indent(indent);
  1204. *BuildFileStream << "{\n";
  1205. WriteArray("Targets", Wrap(Alias.PreBuildDependencies), identPlus1);
  1206. if (Alias.Hidden) {
  1207. WriteVariable("Hidden", "true", identPlus1);
  1208. }
  1209. Indent(indent);
  1210. *BuildFileStream << "}\n";
  1211. }
  1212. void cmGlobalFastbuildGenerator::WriteCopy(FastbuildCopyNode const& Copy)
  1213. {
  1214. cmGlobalFastbuildGenerator::WriteCommand(
  1215. Copy.CopyDir ? "CopyDir" : "Copy",
  1216. cmGlobalFastbuildGenerator::Quote(Copy.Name), 1);
  1217. cmGlobalFastbuildGenerator::Indent(1);
  1218. *BuildFileStream << "{\n";
  1219. WriteVariable("PreBuildDependencies",
  1220. cmGlobalFastbuildGenerator::Quote(Copy.PreBuildDependencies),
  1221. 2);
  1222. WriteVariable(Copy.CopyDir ? "SourcePaths" : "Source",
  1223. cmGlobalFastbuildGenerator::Quote(Copy.Source), 2);
  1224. WriteVariable("Dest", cmGlobalFastbuildGenerator::Quote(Copy.Dest), 2);
  1225. cmGlobalFastbuildGenerator::Indent(1);
  1226. *BuildFileStream << "}\n";
  1227. }
  1228. void cmGlobalFastbuildGenerator::WriteTarget(FastbuildTarget const& target)
  1229. {
  1230. for (auto const& val : target.Variables) {
  1231. auto const& key = val.first;
  1232. auto const& value = val.second;
  1233. WriteVariable(key, cmGlobalFastbuildGenerator::Quote(value), 1);
  1234. }
  1235. // add_custom_commands(...)
  1236. for (auto const& alias : { target.ExecNodes }) {
  1237. this->WriteAlias(alias);
  1238. }
  1239. // -deps Alias.
  1240. this->WriteAlias(target.DependenciesAlias);
  1241. // PRE_BUILD.
  1242. for (auto const& alias : { target.PreBuildExecNodes }) {
  1243. this->WriteAlias(alias);
  1244. }
  1245. // Copy commands.
  1246. for (FastbuildCopyNode const& node : target.CopyNodes) {
  1247. this->WriteCopy(node);
  1248. }
  1249. // Unity.
  1250. for (FastbuildUnityNode const& unity : target.UnityNodes) {
  1251. this->WriteUnity(unity);
  1252. }
  1253. // Objects.
  1254. for (FastbuildObjectListNode const& objectList : target.ObjectListNodes) {
  1255. this->WriteObjectList(objectList, target.AllowDistribution);
  1256. }
  1257. if (!target.PreLinkExecNodes.Nodes.empty()) {
  1258. for (auto const& exec : target.PreLinkExecNodes.Nodes) {
  1259. this->WriteExec(exec);
  1260. }
  1261. this->WriteAlias(target.PreLinkExecNodes.Alias);
  1262. }
  1263. // Libraries / executables.
  1264. if (!target.LinkerNode.empty()) {
  1265. for (auto const& linkerNode : target.LinkerNode) {
  1266. this->WriteLinker(linkerNode, target.AllowDistribution);
  1267. }
  1268. }
  1269. if (!target.PostBuildExecNodes.Nodes.empty()) {
  1270. for (auto const& exec : target.PostBuildExecNodes.Nodes) {
  1271. this->WriteExec(exec);
  1272. }
  1273. this->WriteAlias(target.PostBuildExecNodes.Alias);
  1274. }
  1275. // Aliases (if any).
  1276. for (FastbuildAliasNode const& alias : target.AliasNodes) {
  1277. this->WriteAlias(alias);
  1278. }
  1279. }
  1280. void cmGlobalFastbuildGenerator::WriteIDEProjects()
  1281. {
  1282. for (auto const& proj : IDEProjects) {
  1283. (void)proj;
  1284. // VS
  1285. #if defined(_WIN32)
  1286. auto const& VSProj = proj.second.first;
  1287. WriteCommand("VCXProject", Quote(VSProj.Alias));
  1288. *this->BuildFileStream << "{\n";
  1289. WriteVariable("ProjectOutput", Quote(VSProj.ProjectOutput), 1);
  1290. WriteIDEProjectConfig(VSProj.ProjectConfigs);
  1291. WriteVSBuildCommands();
  1292. WriteIDEProjectCommon(VSProj);
  1293. *this->BuildFileStream << "}\n\n";
  1294. // XCode
  1295. #elif defined(__APPLE__)
  1296. auto const& XCodeProj = proj.second.second;
  1297. WriteCommand("XCodeProject", Quote(XCodeProj.Alias), 0);
  1298. *this->BuildFileStream << "{\n";
  1299. WriteVariable("ProjectOutput", Quote(XCodeProj.ProjectOutput), 1);
  1300. WriteIDEProjectConfig(XCodeProj.ProjectConfigs);
  1301. WriteXCodeBuildCommands();
  1302. WriteIDEProjectCommon(XCodeProj);
  1303. *this->BuildFileStream << "}\n\n";
  1304. #endif
  1305. }
  1306. #if defined(_WIN32)
  1307. this->WriteSolution();
  1308. #elif defined(__APPLE__)
  1309. this->WriteXCodeTopLevelProject();
  1310. #endif
  1311. }
  1312. std::string cmGlobalFastbuildGenerator::GetIDEBuildArgs() const
  1313. {
  1314. cmValue const ideArgs = this->GetGlobalSetting(FASTBUILD_IDE_ARGS);
  1315. if (ideArgs) {
  1316. return cmStrCat(' ', ideArgs, ' ');
  1317. }
  1318. return FASTBUILD_DEFAULT_IDE_BUILD_ARGS;
  1319. }
  1320. void cmGlobalFastbuildGenerator::WriteVSBuildCommands()
  1321. {
  1322. std::string const ideArgs = this->GetIDEBuildArgs();
  1323. WriteVariable(
  1324. "ProjectBuildCommand",
  1325. Quote(cmStrCat(FASTBUILD_IDE_VS_COMMAND_PREFIX, this->FastbuildCommand,
  1326. ideArgs, " ^$(ProjectName)")),
  1327. 1);
  1328. WriteVariable(
  1329. "ProjectRebuildCommand",
  1330. Quote(cmStrCat(FASTBUILD_IDE_VS_COMMAND_PREFIX, this->FastbuildCommand,
  1331. ideArgs, "-clean ^$(ProjectName)")),
  1332. 1);
  1333. WriteVariable("ProjectCleanCommand",
  1334. Quote(cmStrCat(FASTBUILD_IDE_VS_COMMAND_PREFIX,
  1335. this->FastbuildCommand, ideArgs, " clean")),
  1336. 1);
  1337. }
  1338. void cmGlobalFastbuildGenerator::WriteXCodeBuildCommands()
  1339. {
  1340. std::string const ideArgs = this->GetIDEBuildArgs();
  1341. WriteVariable("XCodeBuildToolPath", Quote(this->FastbuildCommand), 1);
  1342. WriteVariable("XCodeBuildToolArgs",
  1343. Quote(cmStrCat(ideArgs, "^$(FASTBUILD_TARGET)")), 1);
  1344. WriteVariable("XCodeBuildWorkingDir",
  1345. Quote(this->CMakeInstance->GetHomeOutputDirectory()), 1);
  1346. }
  1347. void cmGlobalFastbuildGenerator::WriteIDEProjectCommon(
  1348. IDEProjectCommon const& project)
  1349. {
  1350. WriteVariable("ProjectBasePath", Quote(project.ProjectBasePath), 1);
  1351. // So Fastbuild will pick up files relative to CMakeLists.txt
  1352. WriteVariable("ProjectInputPaths", Quote(project.ProjectBasePath), 1);
  1353. }
  1354. void cmGlobalFastbuildGenerator::WriteIDEProjectConfig(
  1355. std::vector<IDEProjectConfig> const& configs, std::string const& keyName)
  1356. {
  1357. std::vector<std::string> allConfigVariables;
  1358. for (auto const& config : configs) {
  1359. std::string configName = "Config" + config.Config;
  1360. WriteVariable(configName, "", 1);
  1361. Indent(1);
  1362. *this->BuildFileStream << "[\n";
  1363. WriteVariable("Config", Quote(config.Config), 2);
  1364. if (!config.Target.empty()) {
  1365. WriteVariable("Target", Quote(config.Target), 2);
  1366. }
  1367. if (!config.Platform.empty()) {
  1368. WriteVariable("Platform", Quote(config.Platform), 2);
  1369. }
  1370. Indent(1);
  1371. *this->BuildFileStream << "]\n";
  1372. allConfigVariables.emplace_back(std::move(configName));
  1373. }
  1374. WriteArray(keyName, Wrap(allConfigVariables, ".", ""), 1);
  1375. }
  1376. void cmGlobalFastbuildGenerator::AddTargetAll()
  1377. {
  1378. FastbuildAliasNode allAliasNode;
  1379. allAliasNode.Name = FASTBUILD_ALL_TARGET_NAME;
  1380. for (auto const& targetBase : FastbuildTargets) {
  1381. if (targetBase->Type == FastbuildTargetType::LINK) {
  1382. auto const& target = static_cast<FastbuildTarget const&>(*targetBase);
  1383. // Add non-global and non-excluded targets to "all"
  1384. if (!target.IsGlobal && !target.ExcludeFromAll) {
  1385. allAliasNode.PreBuildDependencies.emplace(target.Name);
  1386. }
  1387. } else if (targetBase->Type == FastbuildTargetType::ALIAS) {
  1388. auto const& target = static_cast<FastbuildAliasNode const&>(*targetBase);
  1389. if (!target.ExcludeFromAll) {
  1390. allAliasNode.PreBuildDependencies.emplace(target.Name);
  1391. }
  1392. }
  1393. }
  1394. if (allAliasNode.PreBuildDependencies.empty()) {
  1395. allAliasNode.PreBuildDependencies.emplace(FASTBUILD_NOOP_FILE_NAME);
  1396. }
  1397. this->AddTarget(std::move(allAliasNode));
  1398. }
  1399. void cmGlobalFastbuildGenerator::AddGlobCheckExec()
  1400. {
  1401. // Tested in "RunCMake.file" test.
  1402. std::string const globScript =
  1403. this->GetCMakeInstance()->GetGlobVerifyScript();
  1404. if (!globScript.empty()) {
  1405. FastbuildExecNode globCheck;
  1406. globCheck.Name = FASTBUILD_GLOB_CHECK_TARGET;
  1407. globCheck.ExecExecutable = cmSystemTools::GetCMakeCommand();
  1408. globCheck.ExecArguments =
  1409. cmStrCat("-P ", this->ConvertToFastbuildPath(globScript));
  1410. globCheck.ExecAlways = false;
  1411. globCheck.ExecUseStdOutAsOutput = false;
  1412. auto const cache = this->GetCMakeInstance()->GetGlobCacheEntries();
  1413. for (auto const& entry : cache) {
  1414. auto path = cmSystemTools::GetFilenamePath(entry.Expression);
  1415. auto expression = cmSystemTools::GetFilenameName(entry.Expression);
  1416. if (std::find(globCheck.ExecInputPath.begin(),
  1417. globCheck.ExecInputPath.end(),
  1418. path) == globCheck.ExecInputPath.end()) {
  1419. globCheck.ExecInputPath.emplace_back(std::move(path));
  1420. }
  1421. if (std::find(globCheck.ExecInputPattern.begin(),
  1422. globCheck.ExecInputPattern.end(),
  1423. expression) == globCheck.ExecInputPattern.end()) {
  1424. globCheck.ExecInputPattern.emplace_back(std::move(expression));
  1425. }
  1426. }
  1427. globCheck.ExecOutput = this->ConvertToFastbuildPath(
  1428. this->GetCMakeInstance()->GetGlobVerifyStamp());
  1429. this->AddTarget(std::move(globCheck));
  1430. }
  1431. }
  1432. void cmGlobalFastbuildGenerator::WriteSolution()
  1433. {
  1434. std::string const solutionName = LocalGenerators[0]->GetProjectName();
  1435. std::map<std::string /*folder*/, std::vector<std::string>> VSProjects;
  1436. std::vector<std::string> VSProjectsWithoutFolder;
  1437. for (auto const& IDEProj : IDEProjects) {
  1438. auto const VSProj = IDEProj.second.first;
  1439. VSProjects[VSProj.folder].emplace_back(VSProj.Alias);
  1440. }
  1441. WriteCommand("VSSolution", Quote("solution"));
  1442. *this->BuildFileStream << "{\n";
  1443. WriteVariable("SolutionOutput",
  1444. Quote(cmJoin({ "VisualStudio", solutionName + ".sln" }, "/")),
  1445. 1);
  1446. auto const& configs = IDEProjects.begin()->second.first.ProjectConfigs;
  1447. WriteIDEProjectConfig(configs, "SolutionConfigs");
  1448. int folderNumber = 0;
  1449. std::vector<std::string> folders;
  1450. for (auto& item : VSProjects) {
  1451. auto const& pathToFolder = item.first;
  1452. auto& projectsInFolder = item.second;
  1453. if (pathToFolder.empty()) {
  1454. std::move(projectsInFolder.begin(), projectsInFolder.end(),
  1455. std::back_inserter(VSProjectsWithoutFolder));
  1456. } else {
  1457. std::string folderName = cmStrCat("Folder_", ++folderNumber);
  1458. WriteStruct(
  1459. folderName,
  1460. { { "Path", Quote(pathToFolder) },
  1461. { "Projects",
  1462. cmStrCat("{", cmJoin(Wrap(projectsInFolder), ","), "}") } },
  1463. 1);
  1464. folders.emplace_back(std::move(folderName));
  1465. }
  1466. }
  1467. if (!folders.empty()) {
  1468. WriteArray("SolutionFolders ", Wrap(folders, ".", ""), 1);
  1469. }
  1470. if (!VSProjectsWithoutFolder.empty()) {
  1471. WriteArray("SolutionProjects", Wrap(VSProjectsWithoutFolder), 1);
  1472. }
  1473. *this->BuildFileStream << "}\n";
  1474. }
  1475. void cmGlobalFastbuildGenerator::WriteXCodeTopLevelProject()
  1476. {
  1477. std::string const projectName = LocalGenerators[0]->GetProjectName();
  1478. std::vector<std::string> XCodeProjects;
  1479. for (auto const& IDEProj : IDEProjects) {
  1480. auto const XCodeProj = IDEProj.second.second;
  1481. XCodeProjects.emplace_back(XCodeProj.Alias);
  1482. }
  1483. WriteCommand("XCodeProject", Quote("xcode"));
  1484. *this->BuildFileStream << "{\n";
  1485. WriteVariable(
  1486. "ProjectOutput",
  1487. Quote(
  1488. cmJoin({ "XCode", projectName + ".xcodeproj", "project.pbxproj" }, "/")),
  1489. 1);
  1490. WriteVariable("ProjectBasePath", Quote(FASTBUILD_XCODE_BASE_PATH), 1);
  1491. auto const& configs = IDEProjects.begin()->second.second.ProjectConfigs;
  1492. WriteIDEProjectConfig(configs);
  1493. WriteArray("ProjectFiles", Wrap(XCodeProjects), 1);
  1494. *this->BuildFileStream << "}\n";
  1495. }
  1496. void cmGlobalFastbuildGenerator::LogMessage(std::string const& m) const
  1497. {
  1498. static bool const verbose = GlobalSettingIsOn(FASTBUILD_VERBOSE_GENERATOR) ||
  1499. cmSystemTools::HasEnv(FASTBUILD_VERBOSE_GENERATOR);
  1500. if (verbose) {
  1501. cmSystemTools::Message(m);
  1502. }
  1503. }
  1504. void cmGlobalFastbuildGenerator::AddFileToClean(std::string const& file)
  1505. {
  1506. AllFilesToClean.insert(file);
  1507. }
  1508. std::string cmGlobalFastbuildGenerator::GetExternalShellExecutable()
  1509. {
  1510. // FindProgram is expensive - touches filesystem and makes syscalls, so cache
  1511. // it.
  1512. static std::string const cached =
  1513. #ifdef _WIN32
  1514. cmSystemTools::FindProgram(
  1515. "cmd.exe", std::vector<std::string>{ "C:\\Windows\\System32" });
  1516. #else
  1517. cmSystemTools::FindProgram("sh", std::vector<std::string>{ "/bin" });
  1518. #endif
  1519. return cached;
  1520. }
  1521. void cmGlobalFastbuildGenerator::WriteTargetRebuildBFF()
  1522. {
  1523. std::vector<std::string> implicitDeps;
  1524. for (auto& lg : LocalGenerators) {
  1525. std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles();
  1526. for (auto const& dep : lf) {
  1527. implicitDeps.push_back(this->ConvertToFastbuildPath(dep));
  1528. }
  1529. }
  1530. auto const* cmake = this->GetCMakeInstance();
  1531. std::string outDir = cmake->GetHomeOutputDirectory() + '/';
  1532. implicitDeps.push_back(outDir + "CMakeCache.txt");
  1533. FastbuildExecNode rebuildBFF;
  1534. rebuildBFF.Name = FASTBUILD_REBUILD_BFF_TARGET_NAME;
  1535. if (!this->GetCMakeInstance()->GetGlobVerifyScript().empty()) {
  1536. implicitDeps.emplace_back(this->GetCMakeInstance()->GetGlobVerifyStamp());
  1537. }
  1538. std::sort(implicitDeps.begin(), implicitDeps.end());
  1539. implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
  1540. implicitDeps.end());
  1541. std::string args =
  1542. cmStrCat("--regenerate-during-build",
  1543. (this->GetCMakeInstance()->GetIgnoreCompileWarningAsError()
  1544. ? " --compile-no-warning-as-error"
  1545. : ""),
  1546. (this->GetCMakeInstance()->GetIgnoreLinkWarningAsError()
  1547. ? " --link-no-warning-as-error"
  1548. : ""),
  1549. " -S", QuoteIfHasSpaces(cmake->GetHomeDirectory()), " -B",
  1550. QuoteIfHasSpaces(cmake->GetHomeOutputDirectory()));
  1551. rebuildBFF.ExecArguments = std::move(args);
  1552. rebuildBFF.ExecInput = implicitDeps;
  1553. rebuildBFF.ExecExecutable = cmSystemTools::GetCMakeCommand();
  1554. rebuildBFF.ExecWorkingDir = outDir;
  1555. rebuildBFF.ExecOutput = outDir + FASTBUILD_BUILD_FILE;
  1556. this->WriteExec(rebuildBFF, 0);
  1557. }
  1558. void cmGlobalFastbuildGenerator::WriteCleanScript()
  1559. {
  1560. std::string const path =
  1561. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), '/',
  1562. FASTBUILD_CLEAN_SCRIPT_NAME);
  1563. cmsys::ofstream scriptFile(path.c_str(), std::ios::out | std::ios::binary);
  1564. if (!scriptFile.is_open()) {
  1565. cmSystemTools::Error("Failed to open: " FASTBUILD_CLEAN_SCRIPT_NAME);
  1566. return;
  1567. }
  1568. for (std::string const& file : AllFilesToClean) {
  1569. #if defined(_WIN32)
  1570. scriptFile << "del /f /q "
  1571. << cmSystemTools::ConvertToWindowsOutputPath(file) << "\n";
  1572. #else
  1573. scriptFile << "rm -f " << file << '\n';
  1574. #endif
  1575. }
  1576. }
  1577. void cmGlobalFastbuildGenerator::WriteTargetClean()
  1578. {
  1579. if (AllFilesToClean.empty()) {
  1580. FastbuildAliasNode clean;
  1581. clean.Name = FASTBUILD_CLEAN_TARGET_NAME;
  1582. clean.PreBuildDependencies.emplace(FASTBUILD_CLEAN_FILE_NAME);
  1583. WriteAlias(clean, 0);
  1584. return;
  1585. }
  1586. WriteCleanScript();
  1587. FastbuildExecNode clean;
  1588. clean.Name = FASTBUILD_CLEAN_TARGET_NAME;
  1589. clean.ExecExecutable = GetExternalShellExecutable();
  1590. clean.ExecArguments =
  1591. FASTBUILD_SCRIPT_FILE_ARG FASTBUILD_1_INPUT_PLACEHOLDER;
  1592. clean.ExecInput = { FASTBUILD_CLEAN_SCRIPT_NAME };
  1593. clean.ExecAlways = true;
  1594. clean.ExecUseStdOutAsOutput = true;
  1595. clean.ExecOutput = FASTBUILD_CLEAN_FILE_NAME;
  1596. clean.ExecWorkingDir = this->GetCMakeInstance()->GetHomeOutputDirectory();
  1597. WriteExec(clean, 0);
  1598. }
  1599. void cmGlobalFastbuildGenerator::WriteTargets()
  1600. {
  1601. std::string const outputDir = this->CMakeInstance->GetHomeOutputDirectory();
  1602. LogMessage("GetHomeOutputDirectory: " + outputDir);
  1603. // Noop file that 'all' can alias to if we don't have any other targets...
  1604. // The exact location of the "noop" file is verified in one of the tests in
  1605. // "RunCMake.CMakePresetsPackage" test suite.
  1606. cmSystemTools::Touch(cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  1607. '/', FASTBUILD_NOOP_FILE_NAME),
  1608. true);
  1609. cmSystemTools::Touch(cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  1610. '/', FASTBUILD_CLEAN_FILE_NAME),
  1611. true);
  1612. // Add "all" utility target before sorting, so we can correctly sort
  1613. // targets that depend on it
  1614. AddTargetAll();
  1615. TopologicalSort(FastbuildTargets);
  1616. AddGlobCheckExec();
  1617. for (auto const& targetBase : FastbuildTargets) {
  1618. this->WriteComment("Target definition: " + targetBase->Name);
  1619. // Target start.
  1620. *BuildFileStream << "{\n";
  1621. if (targetBase->Type == FastbuildTargetType::EXEC) {
  1622. this->WriteExec(static_cast<FastbuildExecNode const&>(*targetBase));
  1623. } else if (targetBase->Type == FastbuildTargetType::ALIAS) {
  1624. this->WriteAlias(static_cast<FastbuildAliasNode const&>(*targetBase));
  1625. } else if (targetBase->Type == FastbuildTargetType::LINK) {
  1626. auto const& target = static_cast<FastbuildTarget const&>(*targetBase);
  1627. this->WriteTarget(target);
  1628. }
  1629. // Target end.
  1630. *BuildFileStream << "}\n";
  1631. }
  1632. if (!this->GetCMakeInstance()->GetIsInTryCompile()) {
  1633. if (!IDEProjects.empty()) {
  1634. this->WriteIDEProjects();
  1635. }
  1636. }
  1637. this->WriteTargetClean();
  1638. this->WriteTargetRebuildBFF();
  1639. }
  1640. std::string cmGlobalFastbuildGenerator::GetTargetName(
  1641. cmGeneratorTarget const* GeneratorTarget) const
  1642. {
  1643. std::string targetName =
  1644. GeneratorTarget->GetLocalGenerator()->GetCurrentBinaryDirectory();
  1645. targetName += "/";
  1646. targetName += GeneratorTarget->GetName();
  1647. targetName = this->ConvertToFastbuildPath(targetName);
  1648. return targetName;
  1649. }
  1650. cm::optional<FastbuildTarget>
  1651. cmGlobalFastbuildGenerator::GetTargetByOutputName(
  1652. std::string const& output) const
  1653. {
  1654. for (auto const& targetBase : FastbuildTargets) {
  1655. if (targetBase->Type == FastbuildTargetType::LINK) {
  1656. auto const& target = static_cast<FastbuildTarget const&>(*targetBase);
  1657. if (std::any_of(target.LinkerNode.begin(), target.LinkerNode.end(),
  1658. [&output](FastbuildLinkerNode const& target_) {
  1659. return target_.LinkerOutput == output;
  1660. })) {
  1661. return target;
  1662. }
  1663. }
  1664. }
  1665. return cm::nullopt;
  1666. }
  1667. void cmGlobalFastbuildGenerator::AddIDEProject(FastbuildTarget const& target,
  1668. std::string const& config)
  1669. {
  1670. auto const& configs = GetConfigNames();
  1671. if (std::find(configs.begin(), configs.end(), config) == configs.end()) {
  1672. LogMessage("Config " + config + " doesn't exist, IDE projest for " +
  1673. target.Name + " won't be generated");
  1674. return;
  1675. }
  1676. auto& IDEProject = IDEProjects[target.BaseName];
  1677. auto const relativeSubdir = cmSystemTools::RelativePath(
  1678. this->GetCMakeInstance()->GetHomeDirectory(), target.BasePath);
  1679. // VS
  1680. auto& VSProject = IDEProject.first;
  1681. VSProject.Alias = target.BaseName + "-vcxproj";
  1682. VSProject.ProjectOutput = cmStrCat("VisualStudio/Projects/", relativeSubdir,
  1683. '/', target.BaseName + ".vcxproj");
  1684. VSProject.ProjectBasePath = target.BasePath;
  1685. VSProject.folder = relativeSubdir;
  1686. // XCode
  1687. auto& XCodeProject = IDEProject.second;
  1688. XCodeProject.Alias = target.BaseName + "-xcodeproj";
  1689. XCodeProject.ProjectOutput =
  1690. cmStrCat("XCode/Projects/", relativeSubdir, '/',
  1691. target.BaseName + ".xcodeproj/project.pbxproj");
  1692. XCodeProject.ProjectBasePath = target.BasePath;
  1693. IDEProjectConfig VSConfig;
  1694. VSConfig.Platform = "X64";
  1695. IDEProjectConfig XCodeConfig;
  1696. VSConfig.Target = XCodeConfig.Target = target.Name;
  1697. VSConfig.Config = XCodeConfig.Config = config.empty() ? "DEFAULT" : config;
  1698. VSProject.ProjectConfigs.emplace_back(std::move(VSConfig));
  1699. XCodeProject.ProjectConfigs.emplace_back(std::move(XCodeConfig));
  1700. }
  1701. bool cmGlobalFastbuildGenerator::IsExcluded(cmGeneratorTarget* target)
  1702. {
  1703. return cmGlobalGenerator::IsExcluded(LocalGenerators[0].get(), target);
  1704. }
  1705. std::vector<std::string> const& cmGlobalFastbuildGenerator::GetConfigNames()
  1706. const
  1707. {
  1708. return static_cast<cmLocalFastbuildGenerator const*>(
  1709. this->LocalGenerators.front().get())
  1710. ->GetConfigNames();
  1711. }
  1712. bool cmGlobalFastbuildGenerator::Open(std::string const& bindir,
  1713. std::string const& projectName,
  1714. bool dryRun)
  1715. {
  1716. #ifdef _WIN32
  1717. std::string sln = bindir + "/VisualStudio/" + projectName + ".sln";
  1718. if (dryRun) {
  1719. return cmSystemTools::FileExists(sln, true);
  1720. }
  1721. sln = cmSystemTools::ConvertToOutputPath(sln);
  1722. auto OpenSolution = [](std::string pathToSolution) {
  1723. HRESULT comInitialized =
  1724. CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  1725. if (FAILED(comInitialized)) {
  1726. return false;
  1727. }
  1728. HINSTANCE hi = ShellExecuteA(NULL, "open", pathToSolution.c_str(), NULL,
  1729. NULL, SW_SHOWNORMAL);
  1730. CoUninitialize();
  1731. return reinterpret_cast<intptr_t>(hi) > 32;
  1732. };
  1733. return std::async(std::launch::async, OpenSolution, sln).get();
  1734. #else
  1735. return cmGlobalCommonGenerator::Open(bindir, projectName, dryRun);
  1736. #endif
  1737. }