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