cmGlobalNinjaGenerator.cxx 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmGlobalNinjaGenerator.h"
  4. #include <algorithm>
  5. #include <cctype>
  6. #include <cstdio>
  7. #include <sstream>
  8. #include <cm/iterator>
  9. #include <cm/memory>
  10. #include <cm/optional>
  11. #include <cm/string_view>
  12. #include <cmext/algorithm>
  13. #include <cmext/memory>
  14. #include <cm3p/json/reader.h>
  15. #include <cm3p/json/value.h>
  16. #include <cm3p/json/writer.h>
  17. #include "cmsys/FStream.hxx"
  18. #include "cmDocumentationEntry.h"
  19. #include "cmFortranParser.h"
  20. #include "cmGeneratedFileStream.h"
  21. #include "cmGeneratorExpressionEvaluationFile.h"
  22. #include "cmGeneratorTarget.h"
  23. #include "cmGlobalGenerator.h"
  24. #include "cmLinkLineComputer.h"
  25. #include "cmListFileCache.h"
  26. #include "cmLocalGenerator.h"
  27. #include "cmLocalNinjaGenerator.h"
  28. #include "cmMakefile.h"
  29. #include "cmMessageType.h"
  30. #include "cmNinjaLinkLineComputer.h"
  31. #include "cmOutputConverter.h"
  32. #include "cmProperty.h"
  33. #include "cmRange.h"
  34. #include "cmScanDepFormat.h"
  35. #include "cmState.h"
  36. #include "cmStateDirectory.h"
  37. #include "cmStateSnapshot.h"
  38. #include "cmStateTypes.h"
  39. #include "cmStringAlgorithms.h"
  40. #include "cmSystemTools.h"
  41. #include "cmTarget.h"
  42. #include "cmTargetDepend.h"
  43. #include "cmVersion.h"
  44. #include "cmake.h"
  45. const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
  46. const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE =
  47. "CMakeFiles/rules.ninja";
  48. const char* cmGlobalNinjaGenerator::INDENT = " ";
  49. #ifdef _WIN32
  50. std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "cd .";
  51. #else
  52. std::string const cmGlobalNinjaGenerator::SHELL_NOOP = ":";
  53. #endif
  54. bool operator==(
  55. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& lhs,
  56. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& rhs)
  57. {
  58. return lhs.Target == rhs.Target && lhs.Config == rhs.Config &&
  59. lhs.GenexOutput == rhs.GenexOutput;
  60. }
  61. bool operator!=(
  62. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& lhs,
  63. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& rhs)
  64. {
  65. return !(lhs == rhs);
  66. }
  67. bool operator<(
  68. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& lhs,
  69. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& rhs)
  70. {
  71. return lhs.Target < rhs.Target ||
  72. (lhs.Target == rhs.Target &&
  73. (lhs.Config < rhs.Config ||
  74. (lhs.Config == rhs.Config && lhs.GenexOutput < rhs.GenexOutput)));
  75. }
  76. bool operator>(
  77. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& lhs,
  78. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& rhs)
  79. {
  80. return rhs < lhs;
  81. }
  82. bool operator<=(
  83. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& lhs,
  84. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& rhs)
  85. {
  86. return !(lhs > rhs);
  87. }
  88. bool operator>=(
  89. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& lhs,
  90. const cmGlobalNinjaGenerator::ByConfig::TargetDependsClosureKey& rhs)
  91. {
  92. return rhs <= lhs;
  93. }
  94. void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
  95. {
  96. for (int i = 0; i < count; ++i) {
  97. os << cmGlobalNinjaGenerator::INDENT;
  98. }
  99. }
  100. void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
  101. {
  102. os << "# ======================================"
  103. "=======================================\n";
  104. }
  105. void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
  106. const std::string& comment)
  107. {
  108. if (comment.empty()) {
  109. return;
  110. }
  111. std::string::size_type lpos = 0;
  112. std::string::size_type rpos;
  113. os << "\n#############################################\n";
  114. while ((rpos = comment.find('\n', lpos)) != std::string::npos) {
  115. os << "# " << comment.substr(lpos, rpos - lpos) << "\n";
  116. lpos = rpos + 1;
  117. }
  118. os << "# " << comment.substr(lpos) << "\n\n";
  119. }
  120. std::unique_ptr<cmLinkLineComputer>
  121. cmGlobalNinjaGenerator::CreateLinkLineComputer(
  122. cmOutputConverter* outputConverter,
  123. cmStateDirectory const& /* stateDir */) const
  124. {
  125. return std::unique_ptr<cmLinkLineComputer>(
  126. cm::make_unique<cmNinjaLinkLineComputer>(
  127. outputConverter,
  128. this->LocalGenerators[0]->GetStateSnapshot().GetDirectory(), this));
  129. }
  130. std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name)
  131. {
  132. // Ninja rule names must match "[a-zA-Z0-9_.-]+". Use ".xx" to encode
  133. // "." and all invalid characters as hexadecimal.
  134. std::string encoded;
  135. for (char i : name) {
  136. if (isalnum(i) || i == '_' || i == '-') {
  137. encoded += i;
  138. } else {
  139. char buf[16];
  140. sprintf(buf, ".%02x", static_cast<unsigned int>(i));
  141. encoded += buf;
  142. }
  143. }
  144. return encoded;
  145. }
  146. std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit)
  147. {
  148. std::string result = lit;
  149. cmSystemTools::ReplaceString(result, "$", "$$");
  150. cmSystemTools::ReplaceString(result, "\n", "$\n");
  151. if (this->IsMultiConfig()) {
  152. cmSystemTools::ReplaceString(result,
  153. cmStrCat('$', this->GetCMakeCFGIntDir()),
  154. this->GetCMakeCFGIntDir());
  155. }
  156. return result;
  157. }
  158. std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path)
  159. {
  160. std::string result = path;
  161. #ifdef _WIN32
  162. if (this->IsGCCOnWindows())
  163. std::replace(result.begin(), result.end(), '\\', '/');
  164. else
  165. std::replace(result.begin(), result.end(), '/', '\\');
  166. #endif
  167. result = this->EncodeLiteral(result);
  168. cmSystemTools::ReplaceString(result, " ", "$ ");
  169. cmSystemTools::ReplaceString(result, ":", "$:");
  170. return result;
  171. }
  172. void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os,
  173. cmNinjaBuild const& build,
  174. int cmdLineLimit,
  175. bool* usedResponseFile)
  176. {
  177. // Make sure there is a rule.
  178. if (build.Rule.empty()) {
  179. cmSystemTools::Error(cmStrCat(
  180. "No rule for WriteBuild! called with comment: ", build.Comment));
  181. return;
  182. }
  183. // Make sure there is at least one output file.
  184. if (build.Outputs.empty()) {
  185. cmSystemTools::Error(cmStrCat(
  186. "No output files for WriteBuild! called with comment: ", build.Comment));
  187. return;
  188. }
  189. cmGlobalNinjaGenerator::WriteComment(os, build.Comment);
  190. // Write output files.
  191. std::string buildStr("build");
  192. {
  193. // Write explicit outputs
  194. for (std::string const& output : build.Outputs) {
  195. buildStr += cmStrCat(' ', this->EncodePath(output));
  196. if (this->ComputingUnknownDependencies) {
  197. this->CombinedBuildOutputs.insert(output);
  198. }
  199. }
  200. // Write implicit outputs
  201. if (!build.ImplicitOuts.empty()) {
  202. buildStr += " |";
  203. for (std::string const& implicitOut : build.ImplicitOuts) {
  204. buildStr += cmStrCat(' ', this->EncodePath(implicitOut));
  205. }
  206. }
  207. buildStr += ':';
  208. // Write the rule.
  209. buildStr += cmStrCat(' ', build.Rule);
  210. }
  211. std::string arguments;
  212. {
  213. // TODO: Better formatting for when there are multiple input/output files.
  214. // Write explicit dependencies.
  215. for (std::string const& explicitDep : build.ExplicitDeps) {
  216. arguments += cmStrCat(' ', this->EncodePath(explicitDep));
  217. }
  218. // Write implicit dependencies.
  219. if (!build.ImplicitDeps.empty()) {
  220. arguments += " |";
  221. for (std::string const& implicitDep : build.ImplicitDeps) {
  222. arguments += cmStrCat(' ', this->EncodePath(implicitDep));
  223. }
  224. }
  225. // Write order-only dependencies.
  226. if (!build.OrderOnlyDeps.empty()) {
  227. arguments += " ||";
  228. for (std::string const& orderOnlyDep : build.OrderOnlyDeps) {
  229. arguments += cmStrCat(' ', this->EncodePath(orderOnlyDep));
  230. }
  231. }
  232. arguments += '\n';
  233. }
  234. // Write the variables bound to this build statement.
  235. std::string assignments;
  236. {
  237. std::ostringstream variable_assignments;
  238. for (auto const& variable : build.Variables) {
  239. cmGlobalNinjaGenerator::WriteVariable(
  240. variable_assignments, variable.first, variable.second, "", 1);
  241. }
  242. // check if a response file rule should be used
  243. assignments = variable_assignments.str();
  244. bool useResponseFile = false;
  245. if (cmdLineLimit < 0 ||
  246. (cmdLineLimit > 0 &&
  247. (arguments.size() + buildStr.size() + assignments.size() + 1000) >
  248. static_cast<size_t>(cmdLineLimit))) {
  249. variable_assignments.str(std::string());
  250. cmGlobalNinjaGenerator::WriteVariable(variable_assignments, "RSP_FILE",
  251. build.RspFile, "", 1);
  252. assignments += variable_assignments.str();
  253. useResponseFile = true;
  254. }
  255. if (usedResponseFile) {
  256. *usedResponseFile = useResponseFile;
  257. }
  258. }
  259. if (build.Variables.count("dyndep") > 0) {
  260. // The ninja 'cleandead' operation does not account for outputs
  261. // discovered by 'dyndep' bindings. Avoid removing them.
  262. this->DisableCleandead = true;
  263. }
  264. os << buildStr << arguments << assignments << "\n";
  265. }
  266. void cmGlobalNinjaGenerator::AddCustomCommandRule()
  267. {
  268. cmNinjaRule rule("CUSTOM_COMMAND");
  269. rule.Command = "$COMMAND";
  270. rule.Description = "$DESC";
  271. rule.Comment = "Rule for running custom commands.";
  272. this->AddRule(rule);
  273. }
  274. void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
  275. const std::string& command, const std::string& description,
  276. const std::string& comment, const std::string& depfile,
  277. const std::string& job_pool, bool uses_terminal, bool restat,
  278. const cmNinjaDeps& outputs, const std::string& config,
  279. const cmNinjaDeps& explicitDeps, const cmNinjaDeps& orderOnlyDeps)
  280. {
  281. this->AddCustomCommandRule();
  282. {
  283. cmNinjaBuild build("CUSTOM_COMMAND");
  284. build.Comment = comment;
  285. build.Outputs = outputs;
  286. build.ExplicitDeps = explicitDeps;
  287. build.OrderOnlyDeps = orderOnlyDeps;
  288. cmNinjaVars& vars = build.Variables;
  289. {
  290. std::string cmd = command; // NOLINT(*)
  291. #ifdef _WIN32
  292. if (cmd.empty())
  293. // TODO Shouldn't an empty command be handled by ninja?
  294. cmd = "cmd.exe /c";
  295. #endif
  296. vars["COMMAND"] = std::move(cmd);
  297. }
  298. vars["DESC"] = this->EncodeLiteral(description);
  299. if (restat) {
  300. vars["restat"] = "1";
  301. }
  302. if (uses_terminal && this->SupportsConsolePool()) {
  303. vars["pool"] = "console";
  304. } else if (!job_pool.empty()) {
  305. vars["pool"] = job_pool;
  306. }
  307. if (!depfile.empty()) {
  308. vars["depfile"] = depfile;
  309. }
  310. if (config.empty()) {
  311. this->WriteBuild(*this->GetCommonFileStream(), build);
  312. } else {
  313. this->WriteBuild(*this->GetImplFileStream(config), build);
  314. }
  315. }
  316. if (this->ComputingUnknownDependencies) {
  317. // we need to track every dependency that comes in, since we are trying
  318. // to find dependencies that are side effects of build commands
  319. for (std::string const& dep : explicitDeps) {
  320. this->CombinedCustomCommandExplicitDependencies.insert(dep);
  321. }
  322. }
  323. }
  324. void cmGlobalNinjaGenerator::AddMacOSXContentRule()
  325. {
  326. cmNinjaRule rule("COPY_OSX_CONTENT");
  327. rule.Command = cmStrCat(this->CMakeCmd(), " -E copy $in $out");
  328. rule.Description = "Copying OS X Content $out";
  329. rule.Comment = "Rule for copying OS X bundle content file.";
  330. this->AddRule(rule);
  331. }
  332. void cmGlobalNinjaGenerator::WriteMacOSXContentBuild(std::string input,
  333. std::string output,
  334. const std::string& config)
  335. {
  336. this->AddMacOSXContentRule();
  337. {
  338. cmNinjaBuild build("COPY_OSX_CONTENT");
  339. build.Outputs.push_back(std::move(output));
  340. build.ExplicitDeps.push_back(std::move(input));
  341. this->WriteBuild(*this->GetImplFileStream(config), build);
  342. }
  343. }
  344. void cmGlobalNinjaGenerator::WriteRule(std::ostream& os,
  345. cmNinjaRule const& rule)
  346. {
  347. // -- Parameter checks
  348. // Make sure the rule has a name.
  349. if (rule.Name.empty()) {
  350. cmSystemTools::Error(cmStrCat(
  351. "No name given for WriteRule! called with comment: ", rule.Comment));
  352. return;
  353. }
  354. // Make sure a command is given.
  355. if (rule.Command.empty()) {
  356. cmSystemTools::Error(cmStrCat(
  357. "No command given for WriteRule! called with comment: ", rule.Comment));
  358. return;
  359. }
  360. // Make sure response file content is given
  361. if (!rule.RspFile.empty() && rule.RspContent.empty()) {
  362. cmSystemTools::Error(
  363. cmStrCat("rspfile but no rspfile_content given for WriteRule! "
  364. "called with comment: ",
  365. rule.Comment));
  366. return;
  367. }
  368. // -- Write rule
  369. // Write rule intro
  370. cmGlobalNinjaGenerator::WriteComment(os, rule.Comment);
  371. os << "rule " << rule.Name << '\n';
  372. // Write rule key/value pairs
  373. auto writeKV = [&os](const char* key, std::string const& value) {
  374. if (!value.empty()) {
  375. cmGlobalNinjaGenerator::Indent(os, 1);
  376. os << key << " = " << value << '\n';
  377. }
  378. };
  379. writeKV("depfile", rule.DepFile);
  380. writeKV("deps", rule.DepType);
  381. writeKV("command", rule.Command);
  382. writeKV("description", rule.Description);
  383. if (!rule.RspFile.empty()) {
  384. writeKV("rspfile", rule.RspFile);
  385. writeKV("rspfile_content", rule.RspContent);
  386. }
  387. writeKV("restat", rule.Restat);
  388. if (rule.Generator) {
  389. writeKV("generator", "1");
  390. }
  391. // Finish rule
  392. os << '\n';
  393. }
  394. void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os,
  395. const std::string& name,
  396. const std::string& value,
  397. const std::string& comment,
  398. int indent)
  399. {
  400. // Make sure we have a name.
  401. if (name.empty()) {
  402. cmSystemTools::Error(cmStrCat("No name given for WriteVariable! called "
  403. "with comment: ",
  404. comment));
  405. return;
  406. }
  407. // Do not add a variable if the value is empty.
  408. std::string val = cmTrimWhitespace(value);
  409. if (val.empty()) {
  410. return;
  411. }
  412. cmGlobalNinjaGenerator::WriteComment(os, comment);
  413. cmGlobalNinjaGenerator::Indent(os, indent);
  414. os << name << " = " << val << "\n";
  415. }
  416. void cmGlobalNinjaGenerator::WriteInclude(std::ostream& os,
  417. const std::string& filename,
  418. const std::string& comment)
  419. {
  420. cmGlobalNinjaGenerator::WriteComment(os, comment);
  421. os << "include " << filename << "\n";
  422. }
  423. void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
  424. const cmNinjaDeps& targets,
  425. const std::string& comment)
  426. {
  427. cmGlobalNinjaGenerator::WriteComment(os, comment);
  428. os << "default";
  429. for (std::string const& target : targets) {
  430. os << " " << target;
  431. }
  432. os << "\n";
  433. }
  434. cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm)
  435. : cmGlobalCommonGenerator(cm)
  436. {
  437. #ifdef _WIN32
  438. cm->GetState()->SetWindowsShell(true);
  439. #endif
  440. this->FindMakeProgramFile = "CMakeNinjaFindMake.cmake";
  441. }
  442. // Virtual public methods.
  443. std::unique_ptr<cmLocalGenerator> cmGlobalNinjaGenerator::CreateLocalGenerator(
  444. cmMakefile* mf)
  445. {
  446. return std::unique_ptr<cmLocalGenerator>(
  447. cm::make_unique<cmLocalNinjaGenerator>(this, mf));
  448. }
  449. codecvt::Encoding cmGlobalNinjaGenerator::GetMakefileEncoding() const
  450. {
  451. return this->NinjaExpectedEncoding;
  452. }
  453. void cmGlobalNinjaGenerator::GetDocumentation(cmDocumentationEntry& entry)
  454. {
  455. entry.Name = cmGlobalNinjaGenerator::GetActualName();
  456. entry.Brief = "Generates build.ninja files.";
  457. }
  458. // Implemented in all cmGlobaleGenerator sub-classes.
  459. // Used in:
  460. // Source/cmLocalGenerator.cxx
  461. // Source/cmake.cxx
  462. void cmGlobalNinjaGenerator::Generate()
  463. {
  464. // Check minimum Ninja version.
  465. if (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  466. this->NinjaVersion.c_str(),
  467. RequiredNinjaVersion().c_str())) {
  468. std::ostringstream msg;
  469. msg << "The detected version of Ninja (" << this->NinjaVersion;
  470. msg << ") is less than the version of Ninja required by CMake (";
  471. msg << cmGlobalNinjaGenerator::RequiredNinjaVersion() << ").";
  472. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  473. msg.str());
  474. return;
  475. }
  476. if (!this->InspectConfigTypeVariables()) {
  477. return;
  478. }
  479. if (!this->OpenBuildFileStreams()) {
  480. return;
  481. }
  482. if (!this->OpenRulesFileStream()) {
  483. return;
  484. }
  485. for (auto& it : this->Configs) {
  486. it.second.TargetDependsClosures.clear();
  487. }
  488. this->InitOutputPathPrefix();
  489. this->TargetAll = this->NinjaOutputPath("all");
  490. this->CMakeCacheFile = this->NinjaOutputPath("CMakeCache.txt");
  491. this->DisableCleandead = false;
  492. this->DiagnosedCxxModuleSupport = false;
  493. this->PolicyCMP0058 =
  494. this->LocalGenerators[0]->GetMakefile()->GetPolicyStatus(
  495. cmPolicies::CMP0058);
  496. this->ComputingUnknownDependencies =
  497. (this->PolicyCMP0058 == cmPolicies::OLD ||
  498. this->PolicyCMP0058 == cmPolicies::WARN);
  499. this->cmGlobalGenerator::Generate();
  500. this->WriteAssumedSourceDependencies();
  501. this->WriteTargetAliases(*this->GetCommonFileStream());
  502. this->WriteFolderTargets(*this->GetCommonFileStream());
  503. this->WriteUnknownExplicitDependencies(*this->GetCommonFileStream());
  504. this->WriteBuiltinTargets(*this->GetCommonFileStream());
  505. if (cmSystemTools::GetErrorOccuredFlag()) {
  506. this->RulesFileStream->setstate(std::ios::failbit);
  507. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  508. cmMakefile::IncludeEmptyConfig)) {
  509. this->GetImplFileStream(config)->setstate(std::ios::failbit);
  510. this->GetConfigFileStream(config)->setstate(std::ios::failbit);
  511. }
  512. this->GetCommonFileStream()->setstate(std::ios::failbit);
  513. }
  514. this->CloseCompileCommandsStream();
  515. this->CloseRulesFileStream();
  516. this->CloseBuildFileStreams();
  517. #ifdef _WIN32
  518. // Older ninja tools will not be able to update metadata on Windows
  519. // when we are re-generating inside an existing 'ninja' invocation
  520. // because the outer tool has the files open for write.
  521. if (this->NinjaSupportsMetadataOnRegeneration ||
  522. !this->GetCMakeInstance()->GetRegenerateDuringBuild())
  523. #endif
  524. {
  525. this->CleanMetaData();
  526. }
  527. }
  528. void cmGlobalNinjaGenerator::CleanMetaData()
  529. {
  530. auto run_ninja_tool = [this](std::vector<char const*> const& args) {
  531. std::vector<std::string> command;
  532. command.push_back(this->NinjaCommand);
  533. command.emplace_back("-C");
  534. command.emplace_back(this->GetCMakeInstance()->GetHomeOutputDirectory());
  535. command.emplace_back("-t");
  536. for (auto const& arg : args) {
  537. command.emplace_back(arg);
  538. }
  539. std::string error;
  540. if (!cmSystemTools::RunSingleCommand(command, nullptr, &error, nullptr,
  541. nullptr,
  542. cmSystemTools::OUTPUT_NONE)) {
  543. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  544. cmStrCat("Running\n '",
  545. cmJoin(command, "' '"),
  546. "'\n"
  547. "failed with:\n ",
  548. error));
  549. cmSystemTools::SetFatalErrorOccured();
  550. }
  551. };
  552. // Can the tools below expect 'build.ninja' to be loadable?
  553. bool const expectBuildManifest =
  554. !this->IsMultiConfig() && this->OutputPathPrefix.empty();
  555. // Skip some ninja tools if they need 'build.ninja' but it is missing.
  556. bool const missingBuildManifest = expectBuildManifest &&
  557. this->NinjaSupportsUnconditionalRecompactTool &&
  558. !cmSystemTools::FileExists("build.ninja");
  559. // The `recompact` tool loads the manifest. As above, we don't have a single
  560. // `build.ninja` to load for this in Ninja-Multi. This may be relaxed in the
  561. // future pending further investigation into how Ninja works upstream
  562. // (ninja#1721).
  563. if (this->NinjaSupportsUnconditionalRecompactTool &&
  564. !this->GetCMakeInstance()->GetRegenerateDuringBuild() &&
  565. expectBuildManifest && !missingBuildManifest) {
  566. run_ninja_tool({ "recompact" });
  567. }
  568. if (this->NinjaSupportsRestatTool && this->OutputPathPrefix.empty()) {
  569. // XXX(ninja): We only list `build.ninja` entry files here because CMake
  570. // *always* rewrites these files on a reconfigure. If CMake ever gets
  571. // smarter about this, all CMake-time created/edited files listed as
  572. // outputs for the reconfigure build statement will need to be listed here.
  573. cmNinjaDeps outputs;
  574. this->AddRebuildManifestOutputs(outputs);
  575. std::vector<const char*> args;
  576. args.reserve(outputs.size() + 1);
  577. args.push_back("restat");
  578. for (auto const& output : outputs) {
  579. args.push_back(output.c_str());
  580. }
  581. run_ninja_tool(args);
  582. }
  583. }
  584. bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
  585. {
  586. if (!this->cmGlobalGenerator::FindMakeProgram(mf)) {
  587. return false;
  588. }
  589. if (cmProp ninjaCommand = mf->GetDefinition("CMAKE_MAKE_PROGRAM")) {
  590. this->NinjaCommand = *ninjaCommand;
  591. std::vector<std::string> command;
  592. command.push_back(this->NinjaCommand);
  593. command.emplace_back("--version");
  594. std::string version;
  595. std::string error;
  596. if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr,
  597. nullptr,
  598. cmSystemTools::OUTPUT_NONE)) {
  599. mf->IssueMessage(MessageType::FATAL_ERROR,
  600. cmStrCat("Running\n '", cmJoin(command, "' '"),
  601. "'\n"
  602. "failed with:\n ",
  603. error));
  604. cmSystemTools::SetFatalErrorOccured();
  605. return false;
  606. }
  607. this->NinjaVersion = cmTrimWhitespace(version);
  608. this->CheckNinjaFeatures();
  609. }
  610. return true;
  611. }
  612. void cmGlobalNinjaGenerator::CheckNinjaFeatures()
  613. {
  614. this->NinjaSupportsConsolePool = !cmSystemTools::VersionCompare(
  615. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  616. RequiredNinjaVersionForConsolePool().c_str());
  617. this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare(
  618. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  619. cmGlobalNinjaGenerator::RequiredNinjaVersionForImplicitOuts().c_str());
  620. this->NinjaSupportsManifestRestat = !cmSystemTools::VersionCompare(
  621. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  622. RequiredNinjaVersionForManifestRestat().c_str());
  623. this->NinjaSupportsMultilineDepfile = !cmSystemTools::VersionCompare(
  624. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  625. RequiredNinjaVersionForMultilineDepfile().c_str());
  626. this->NinjaSupportsDyndeps = !cmSystemTools::VersionCompare(
  627. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  628. RequiredNinjaVersionForDyndeps().c_str());
  629. if (!this->NinjaSupportsDyndeps) {
  630. // The ninja version number is not new enough to have upstream support.
  631. // Our ninja branch adds ".dyndep-#" to its version number,
  632. // where '#' is a feature-specific version number. Extract it.
  633. static std::string const k_DYNDEP_ = ".dyndep-";
  634. std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_);
  635. if (pos != std::string::npos) {
  636. const char* fv = &this->NinjaVersion[pos + k_DYNDEP_.size()];
  637. unsigned long dyndep = 0;
  638. cmStrToULong(fv, &dyndep);
  639. if (dyndep == 1) {
  640. this->NinjaSupportsDyndeps = true;
  641. }
  642. }
  643. }
  644. this->NinjaSupportsUnconditionalRecompactTool =
  645. !cmSystemTools::VersionCompare(
  646. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  647. RequiredNinjaVersionForUnconditionalRecompactTool().c_str());
  648. this->NinjaSupportsRestatTool = !cmSystemTools::VersionCompare(
  649. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  650. RequiredNinjaVersionForRestatTool().c_str());
  651. this->NinjaSupportsMultipleOutputs = !cmSystemTools::VersionCompare(
  652. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  653. RequiredNinjaVersionForMultipleOutputs().c_str());
  654. this->NinjaSupportsMetadataOnRegeneration = !cmSystemTools::VersionCompare(
  655. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  656. RequiredNinjaVersionForMetadataOnRegeneration().c_str());
  657. #ifdef _WIN32
  658. this->NinjaSupportsCodePage = !cmSystemTools::VersionCompare(
  659. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  660. RequiredNinjaVersionForCodePage().c_str());
  661. if (this->NinjaSupportsCodePage) {
  662. this->CheckNinjaCodePage();
  663. } else {
  664. this->NinjaExpectedEncoding = codecvt::ANSI;
  665. }
  666. #endif
  667. }
  668. void cmGlobalNinjaGenerator::CheckNinjaCodePage()
  669. {
  670. std::vector<std::string> command{ this->NinjaCommand, "-t", "wincodepage" };
  671. std::string output;
  672. std::string error;
  673. int result;
  674. if (!cmSystemTools::RunSingleCommand(command, &output, &error, &result,
  675. nullptr, cmSystemTools::OUTPUT_NONE)) {
  676. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  677. cmStrCat("Running\n '",
  678. cmJoin(command, "' '"),
  679. "'\n"
  680. "failed with:\n ",
  681. error));
  682. cmSystemTools::SetFatalErrorOccured();
  683. } else if (result == 0) {
  684. std::istringstream outputStream(output);
  685. std::string line;
  686. bool found = false;
  687. while (cmSystemTools::GetLineFromStream(outputStream, line)) {
  688. if (cmHasLiteralPrefix(line, "Build file encoding: ")) {
  689. cm::string_view lineView(line);
  690. cm::string_view encoding =
  691. lineView.substr(cmStrLen("Build file encoding: "));
  692. if (encoding == "UTF-8") {
  693. // Ninja expects UTF-8. We use that internally. No conversion needed.
  694. this->NinjaExpectedEncoding = codecvt::None;
  695. } else {
  696. this->NinjaExpectedEncoding = codecvt::ANSI;
  697. }
  698. found = true;
  699. break;
  700. }
  701. }
  702. if (!found) {
  703. this->GetCMakeInstance()->IssueMessage(
  704. MessageType::WARNING,
  705. "Could not determine Ninja's code page, defaulting to UTF-8");
  706. this->NinjaExpectedEncoding = codecvt::None;
  707. }
  708. } else {
  709. this->NinjaExpectedEncoding = codecvt::ANSI;
  710. }
  711. }
  712. bool cmGlobalNinjaGenerator::CheckLanguages(
  713. std::vector<std::string> const& languages, cmMakefile* mf) const
  714. {
  715. if (cm::contains(languages, "Fortran")) {
  716. return this->CheckFortran(mf);
  717. }
  718. if (cm::contains(languages, "ISPC")) {
  719. return this->CheckISPC(mf);
  720. }
  721. if (cm::contains(languages, "Swift")) {
  722. const std::string architectures =
  723. mf->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  724. if (architectures.find_first_of(';') != std::string::npos) {
  725. mf->IssueMessage(MessageType::FATAL_ERROR,
  726. "multiple values for CMAKE_OSX_ARCHITECTURES not "
  727. "supported with Swift");
  728. cmSystemTools::SetFatalErrorOccured();
  729. return false;
  730. }
  731. }
  732. return true;
  733. }
  734. bool cmGlobalNinjaGenerator::CheckCxxModuleSupport()
  735. {
  736. bool const diagnose = !this->DiagnosedCxxModuleSupport &&
  737. !this->CMakeInstance->GetIsInTryCompile();
  738. if (diagnose) {
  739. this->DiagnosedCxxModuleSupport = true;
  740. this->GetCMakeInstance()->IssueMessage(
  741. MessageType::AUTHOR_WARNING,
  742. "C++20 modules support via CMAKE_EXPERIMENTAL_CXX_MODULE_DYNDEP "
  743. "is experimental. It is meant only for compiler developers to try.");
  744. }
  745. if (this->NinjaSupportsDyndeps) {
  746. return true;
  747. }
  748. if (diagnose) {
  749. std::ostringstream e;
  750. /* clang-format off */
  751. e <<
  752. "The Ninja generator does not support C++20 modules "
  753. "using Ninja version \n"
  754. " " << this->NinjaVersion << "\n"
  755. "due to lack of required features. "
  756. "Ninja " << RequiredNinjaVersionForDyndeps() << " or higher is required."
  757. ;
  758. /* clang-format on */
  759. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str());
  760. cmSystemTools::SetFatalErrorOccured();
  761. }
  762. return false;
  763. }
  764. bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const
  765. {
  766. if (this->NinjaSupportsDyndeps) {
  767. return true;
  768. }
  769. std::ostringstream e;
  770. /* clang-format off */
  771. e <<
  772. "The Ninja generator does not support Fortran using Ninja version\n"
  773. " " << this->NinjaVersion << "\n"
  774. "due to lack of required features. "
  775. "Ninja " << RequiredNinjaVersionForDyndeps() << " or higher is required."
  776. ;
  777. /* clang-format on */
  778. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  779. cmSystemTools::SetFatalErrorOccured();
  780. return false;
  781. }
  782. bool cmGlobalNinjaGenerator::CheckISPC(cmMakefile* mf) const
  783. {
  784. if (this->NinjaSupportsMultipleOutputs) {
  785. return true;
  786. }
  787. std::ostringstream e;
  788. /* clang-format off */
  789. e <<
  790. "The Ninja generator does not support ISPC using Ninja version\n"
  791. " " << this->NinjaVersion << "\n"
  792. "due to lack of required features. "
  793. "Ninja " << RequiredNinjaVersionForMultipleOutputs() <<
  794. " or higher is required."
  795. ;
  796. /* clang-format on */
  797. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  798. cmSystemTools::SetFatalErrorOccured();
  799. return false;
  800. }
  801. void cmGlobalNinjaGenerator::EnableLanguage(
  802. std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
  803. {
  804. if (this->IsMultiConfig()) {
  805. if (!mf->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  806. mf->AddCacheDefinition(
  807. "CMAKE_CONFIGURATION_TYPES", "Debug;Release;RelWithDebInfo",
  808. "Semicolon separated list of supported configuration types, only "
  809. "supports Debug, Release, MinSizeRel, and RelWithDebInfo, anything "
  810. "else will be ignored",
  811. cmStateEnums::STRING);
  812. }
  813. }
  814. this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
  815. for (std::string const& l : langs) {
  816. if (l == "NONE") {
  817. continue;
  818. }
  819. this->ResolveLanguageCompiler(l, mf, optional);
  820. }
  821. #ifdef _WIN32
  822. const bool clangGnuMode =
  823. ((mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "Clang") &&
  824. (mf->GetSafeDefinition("CMAKE_C_COMPILER_FRONTEND_VARIANT") == "GNU")) ||
  825. ((mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "Clang") &&
  826. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_FRONTEND_VARIANT") == "GNU"));
  827. if (clangGnuMode ||
  828. ((mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID") != "MSVC") &&
  829. (mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID") != "MSVC") &&
  830. (mf->IsOn("CMAKE_COMPILER_IS_MINGW") ||
  831. (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "GNU") ||
  832. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "GNU") ||
  833. (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "Clang") ||
  834. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "Clang") ||
  835. (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "QCC") ||
  836. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "QCC")))) {
  837. this->UsingGCCOnWindows = true;
  838. }
  839. #endif
  840. }
  841. // Implemented by:
  842. // cmGlobalUnixMakefileGenerator3
  843. // cmGlobalGhsMultiGenerator
  844. // cmGlobalVisualStudio10Generator
  845. // cmGlobalVisualStudio7Generator
  846. // cmGlobalXCodeGenerator
  847. // Called by:
  848. // cmGlobalGenerator::Build()
  849. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  850. cmGlobalNinjaGenerator::GenerateBuildCommand(
  851. const std::string& makeProgram, const std::string& /*projectName*/,
  852. const std::string& /*projectDir*/,
  853. std::vector<std::string> const& targetNames, const std::string& config,
  854. bool /*fast*/, int jobs, bool verbose,
  855. std::vector<std::string> const& makeOptions)
  856. {
  857. GeneratedMakeCommand makeCommand;
  858. makeCommand.Add(this->SelectMakeProgram(makeProgram));
  859. if (verbose) {
  860. makeCommand.Add("-v");
  861. }
  862. if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
  863. (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
  864. makeCommand.Add("-j", std::to_string(jobs));
  865. }
  866. this->AppendNinjaFileArgument(makeCommand, config);
  867. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  868. for (const auto& tname : targetNames) {
  869. if (!tname.empty()) {
  870. makeCommand.Add(tname);
  871. }
  872. }
  873. return { std::move(makeCommand) };
  874. }
  875. // Non-virtual public methods.
  876. void cmGlobalNinjaGenerator::AddRule(cmNinjaRule const& rule)
  877. {
  878. // Do not add the same rule twice.
  879. if (!this->Rules.insert(rule.Name).second) {
  880. return;
  881. }
  882. // Store command length
  883. this->RuleCmdLength[rule.Name] = static_cast<int>(rule.Command.size());
  884. // Write rule
  885. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream, rule);
  886. }
  887. bool cmGlobalNinjaGenerator::HasRule(const std::string& name)
  888. {
  889. return (this->Rules.find(name) != this->Rules.end());
  890. }
  891. // Private virtual overrides
  892. std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const
  893. {
  894. // Ninja by design does not run interactive tools in the terminal,
  895. // so our only choice is cmake-gui.
  896. return cmSystemTools::GetCMakeGUICommand();
  897. }
  898. void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory(
  899. cmGeneratorTarget* gt) const
  900. {
  901. // Compute full path to object file directory for this target.
  902. std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
  903. '/', gt->LocalGenerator->GetTargetDirectory(gt),
  904. '/', this->GetCMakeCFGIntDir(), '/');
  905. gt->ObjectDirectory = dir;
  906. }
  907. // Private methods
  908. bool cmGlobalNinjaGenerator::OpenBuildFileStreams()
  909. {
  910. if (!this->OpenFileStream(this->BuildFileStream,
  911. cmGlobalNinjaGenerator::NINJA_BUILD_FILE)) {
  912. return false;
  913. }
  914. // Write a comment about this file.
  915. *this->BuildFileStream
  916. << "# This file contains all the build statements describing the\n"
  917. << "# compilation DAG.\n\n";
  918. return true;
  919. }
  920. bool cmGlobalNinjaGenerator::OpenFileStream(
  921. std::unique_ptr<cmGeneratedFileStream>& stream, const std::string& name)
  922. {
  923. // Get a stream where to generate things.
  924. if (!stream) {
  925. // Compute Ninja's build file path.
  926. std::string path =
  927. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), '/', name);
  928. stream = cm::make_unique<cmGeneratedFileStream>(
  929. path, false, this->GetMakefileEncoding());
  930. if (!(*stream)) {
  931. // An error message is generated by the constructor if it cannot
  932. // open the file.
  933. return false;
  934. }
  935. // Write the do not edit header.
  936. this->WriteDisclaimer(*stream);
  937. }
  938. return true;
  939. }
  940. cm::optional<std::set<std::string>> cmGlobalNinjaGenerator::ListSubsetWithAll(
  941. const std::set<std::string>& all, const std::set<std::string>& defaults,
  942. const std::vector<std::string>& items)
  943. {
  944. std::set<std::string> result;
  945. for (auto const& item : items) {
  946. if (item == "all") {
  947. if (items.size() == 1) {
  948. result = defaults;
  949. } else {
  950. return cm::nullopt;
  951. }
  952. } else if (all.count(item)) {
  953. result.insert(item);
  954. } else {
  955. return cm::nullopt;
  956. }
  957. }
  958. return cm::make_optional(result);
  959. }
  960. void cmGlobalNinjaGenerator::CloseBuildFileStreams()
  961. {
  962. if (this->BuildFileStream) {
  963. this->BuildFileStream.reset();
  964. } else {
  965. cmSystemTools::Error("Build file stream was not open.");
  966. }
  967. }
  968. bool cmGlobalNinjaGenerator::OpenRulesFileStream()
  969. {
  970. if (!this->OpenFileStream(this->RulesFileStream,
  971. cmGlobalNinjaGenerator::NINJA_RULES_FILE)) {
  972. return false;
  973. }
  974. // Write comment about this file.
  975. /* clang-format off */
  976. *this->RulesFileStream
  977. << "# This file contains all the rules used to get the outputs files\n"
  978. << "# built from the input files.\n"
  979. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  980. ;
  981. /* clang-format on */
  982. return true;
  983. }
  984. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  985. {
  986. if (this->RulesFileStream) {
  987. this->RulesFileStream.reset();
  988. } else {
  989. cmSystemTools::Error("Rules file stream was not open.");
  990. }
  991. }
  992. static void EnsureTrailingSlash(std::string& path)
  993. {
  994. if (path.empty()) {
  995. return;
  996. }
  997. std::string::value_type last = path.back();
  998. #ifdef _WIN32
  999. if (last != '\\') {
  1000. path += '\\';
  1001. }
  1002. #else
  1003. if (last != '/') {
  1004. path += '/';
  1005. }
  1006. #endif
  1007. }
  1008. std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath(
  1009. const std::string& path) const
  1010. {
  1011. auto const f = this->ConvertToNinjaPathCache.find(path);
  1012. if (f != this->ConvertToNinjaPathCache.end()) {
  1013. return f->second;
  1014. }
  1015. const auto& ng =
  1016. cm::static_reference_cast<cmLocalNinjaGenerator>(this->LocalGenerators[0]);
  1017. std::string const& bin_dir = ng.GetState()->GetBinaryDirectory();
  1018. std::string convPath = ng.MaybeConvertToRelativePath(bin_dir, path);
  1019. convPath = this->NinjaOutputPath(convPath);
  1020. #ifdef _WIN32
  1021. std::replace(convPath.begin(), convPath.end(), '/', '\\');
  1022. #endif
  1023. return this->ConvertToNinjaPathCache.emplace(path, std::move(convPath))
  1024. .first->second;
  1025. }
  1026. void cmGlobalNinjaGenerator::AddAdditionalCleanFile(std::string fileName,
  1027. const std::string& config)
  1028. {
  1029. this->Configs[config].AdditionalCleanFiles.emplace(std::move(fileName));
  1030. }
  1031. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  1032. const std::string& commandLine, const std::string& sourceFile)
  1033. {
  1034. // Compute Ninja's build file path.
  1035. std::string buildFileDir =
  1036. this->GetCMakeInstance()->GetHomeOutputDirectory();
  1037. if (!this->CompileCommandsStream) {
  1038. std::string buildFilePath =
  1039. cmStrCat(buildFileDir, "/compile_commands.json");
  1040. if (this->ComputingUnknownDependencies) {
  1041. this->CombinedBuildOutputs.insert(
  1042. this->NinjaOutputPath("compile_commands.json"));
  1043. }
  1044. // Get a stream where to generate things.
  1045. this->CompileCommandsStream =
  1046. cm::make_unique<cmGeneratedFileStream>(buildFilePath);
  1047. *this->CompileCommandsStream << "[\n";
  1048. } else {
  1049. *this->CompileCommandsStream << ",\n";
  1050. }
  1051. std::string sourceFileName = sourceFile;
  1052. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1053. sourceFileName = cmSystemTools::CollapseFullPath(
  1054. sourceFileName, this->GetCMakeInstance()->GetHomeOutputDirectory());
  1055. }
  1056. /* clang-format off */
  1057. *this->CompileCommandsStream << "{\n"
  1058. << R"( "directory": ")"
  1059. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  1060. << R"( "command": ")"
  1061. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  1062. << R"( "file": ")"
  1063. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  1064. << "}";
  1065. /* clang-format on */
  1066. }
  1067. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  1068. {
  1069. if (this->CompileCommandsStream) {
  1070. *this->CompileCommandsStream << "\n]";
  1071. this->CompileCommandsStream.reset();
  1072. }
  1073. }
  1074. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os) const
  1075. {
  1076. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1077. << "# Generated by \"" << this->GetName() << "\""
  1078. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1079. << cmVersion::GetMinorVersion() << "\n\n";
  1080. }
  1081. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  1082. {
  1083. for (auto const& asd : this->AssumedSourceDependencies) {
  1084. cmNinjaDeps orderOnlyDeps;
  1085. std::copy(asd.second.begin(), asd.second.end(),
  1086. std::back_inserter(orderOnlyDeps));
  1087. this->WriteCustomCommandBuild(
  1088. /*command=*/"", /*description=*/"",
  1089. "Assume dependencies for generated source file.",
  1090. /*depfile*/ "", /*job_pool*/ "",
  1091. /*uses_terminal*/ false,
  1092. /*restat*/ true, cmNinjaDeps(1, asd.first), "", cmNinjaDeps(),
  1093. orderOnlyDeps);
  1094. }
  1095. }
  1096. std::string cmGlobalNinjaGenerator::OrderDependsTargetForTarget(
  1097. cmGeneratorTarget const* target, const std::string& /*config*/) const
  1098. {
  1099. return cmStrCat("cmake_object_order_depends_target_", target->GetName());
  1100. }
  1101. void cmGlobalNinjaGenerator::AppendTargetOutputs(
  1102. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1103. const std::string& config, cmNinjaTargetDepends depends) const
  1104. {
  1105. // for frameworks, we want the real name, not smple name
  1106. // frameworks always appear versioned, and the build.ninja
  1107. // will always attempt to manage symbolic links instead
  1108. // of letting cmOSXBundleGenerator do it.
  1109. bool realname = target->IsFrameworkOnApple();
  1110. switch (target->GetType()) {
  1111. case cmStateEnums::SHARED_LIBRARY:
  1112. case cmStateEnums::STATIC_LIBRARY:
  1113. case cmStateEnums::MODULE_LIBRARY: {
  1114. if (depends == DependOnTargetOrdering) {
  1115. outputs.push_back(this->OrderDependsTargetForTarget(target, config));
  1116. break;
  1117. }
  1118. }
  1119. // FALLTHROUGH
  1120. case cmStateEnums::EXECUTABLE: {
  1121. outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath(
  1122. config, cmStateEnums::RuntimeBinaryArtifact, realname)));
  1123. break;
  1124. }
  1125. case cmStateEnums::OBJECT_LIBRARY: {
  1126. if (depends == DependOnTargetOrdering) {
  1127. outputs.push_back(this->OrderDependsTargetForTarget(target, config));
  1128. break;
  1129. }
  1130. }
  1131. // FALLTHROUGH
  1132. case cmStateEnums::GLOBAL_TARGET:
  1133. case cmStateEnums::INTERFACE_LIBRARY:
  1134. case cmStateEnums::UTILITY: {
  1135. std::string path =
  1136. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/',
  1137. target->GetName());
  1138. std::string output = this->ConvertToNinjaPath(path);
  1139. if (target->Target->IsPerConfig()) {
  1140. output = this->BuildAlias(output, config);
  1141. }
  1142. outputs.push_back(output);
  1143. break;
  1144. }
  1145. case cmStateEnums::UNKNOWN_LIBRARY:
  1146. break;
  1147. }
  1148. }
  1149. void cmGlobalNinjaGenerator::AppendTargetDepends(
  1150. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1151. const std::string& config, const std::string& fileConfig,
  1152. cmNinjaTargetDepends depends)
  1153. {
  1154. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1155. // These depend only on other CMake-provided targets, e.g. "all".
  1156. for (BT<std::pair<std::string, bool>> const& util :
  1157. target->GetUtilities()) {
  1158. std::string d =
  1159. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/',
  1160. util.Value.first);
  1161. outputs.push_back(this->BuildAlias(this->ConvertToNinjaPath(d), config));
  1162. }
  1163. } else {
  1164. cmNinjaDeps outs;
  1165. auto computeISPCOuputs = [](cmGlobalNinjaGenerator* gg,
  1166. cmGeneratorTarget const* depTarget,
  1167. cmNinjaDeps& outputDeps,
  1168. const std::string& targetConfig) {
  1169. if (depTarget->CanCompileSources()) {
  1170. auto headers = depTarget->GetGeneratedISPCHeaders(targetConfig);
  1171. if (!headers.empty()) {
  1172. std::transform(headers.begin(), headers.end(), headers.begin(),
  1173. gg->MapToNinjaPath());
  1174. outputDeps.insert(outputDeps.end(), headers.begin(), headers.end());
  1175. }
  1176. auto objs = depTarget->GetGeneratedISPCObjects(targetConfig);
  1177. if (!objs.empty()) {
  1178. std::transform(objs.begin(), objs.end(), objs.begin(),
  1179. gg->MapToNinjaPath());
  1180. outputDeps.insert(outputDeps.end(), objs.begin(), objs.end());
  1181. }
  1182. }
  1183. };
  1184. for (cmTargetDepend const& targetDep :
  1185. this->GetTargetDirectDepends(target)) {
  1186. if (!targetDep->IsInBuildSystem()) {
  1187. continue;
  1188. }
  1189. if (targetDep.IsCross()) {
  1190. this->AppendTargetOutputs(targetDep, outs, fileConfig, depends);
  1191. computeISPCOuputs(this, targetDep, outs, fileConfig);
  1192. } else {
  1193. this->AppendTargetOutputs(targetDep, outs, config, depends);
  1194. computeISPCOuputs(this, targetDep, outs, config);
  1195. }
  1196. }
  1197. std::sort(outs.begin(), outs.end());
  1198. cm::append(outputs, outs);
  1199. }
  1200. }
  1201. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  1202. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1203. const std::string& config, const std::string& fileConfig, bool genexOutput)
  1204. {
  1205. cmNinjaOuts outs;
  1206. this->AppendTargetDependsClosure(target, outs, config, fileConfig,
  1207. genexOutput, true);
  1208. cm::append(outputs, outs);
  1209. }
  1210. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  1211. cmGeneratorTarget const* target, cmNinjaOuts& outputs,
  1212. const std::string& config, const std::string& fileConfig, bool genexOutput,
  1213. bool omit_self)
  1214. {
  1215. // try to locate the target in the cache
  1216. ByConfig::TargetDependsClosureKey key{
  1217. target,
  1218. config,
  1219. genexOutput,
  1220. };
  1221. auto find = this->Configs[fileConfig].TargetDependsClosures.lower_bound(key);
  1222. if (find == this->Configs[fileConfig].TargetDependsClosures.end() ||
  1223. find->first != key) {
  1224. // We now calculate the closure outputs by inspecting the dependent
  1225. // targets recursively.
  1226. // For that we have to distinguish between a local result set that is only
  1227. // relevant for filling the cache entries properly isolated and a global
  1228. // result set that is relevant for the result of the top level call to
  1229. // AppendTargetDependsClosure.
  1230. cmNinjaOuts this_outs; // this will be the new cache entry
  1231. for (auto const& dep_target : this->GetTargetDirectDepends(target)) {
  1232. if (!dep_target->IsInBuildSystem()) {
  1233. continue;
  1234. }
  1235. if (!this->IsSingleConfigUtility(target) &&
  1236. !this->IsSingleConfigUtility(dep_target) &&
  1237. this->EnableCrossConfigBuild() && !dep_target.IsCross() &&
  1238. !genexOutput) {
  1239. continue;
  1240. }
  1241. if (dep_target.IsCross()) {
  1242. this->AppendTargetDependsClosure(dep_target, this_outs, fileConfig,
  1243. fileConfig, genexOutput, false);
  1244. } else {
  1245. this->AppendTargetDependsClosure(dep_target, this_outs, config,
  1246. fileConfig, genexOutput, false);
  1247. }
  1248. }
  1249. find = this->Configs[fileConfig].TargetDependsClosures.emplace_hint(
  1250. find, key, std::move(this_outs));
  1251. }
  1252. // now fill the outputs of the final result from the newly generated cache
  1253. // entry
  1254. outputs.insert(find->second.begin(), find->second.end());
  1255. // finally generate the outputs of the target itself, if applicable
  1256. cmNinjaDeps outs;
  1257. if (!omit_self) {
  1258. this->AppendTargetOutputs(target, outs, config, DependOnTargetArtifact);
  1259. }
  1260. outputs.insert(outs.begin(), outs.end());
  1261. }
  1262. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  1263. cmGeneratorTarget* target,
  1264. const std::string& config)
  1265. {
  1266. std::string outputPath = this->NinjaOutputPath(alias);
  1267. std::string buildAlias = this->BuildAlias(outputPath, config);
  1268. cmNinjaDeps outputs;
  1269. if (config != "all") {
  1270. this->AppendTargetOutputs(target, outputs, config, DependOnTargetArtifact);
  1271. }
  1272. // Mark the target's outputs as ambiguous to ensure that no other target
  1273. // uses the output as an alias.
  1274. for (std::string const& output : outputs) {
  1275. this->TargetAliases[output].GeneratorTarget = nullptr;
  1276. this->DefaultTargetAliases[output].GeneratorTarget = nullptr;
  1277. for (const std::string& config2 :
  1278. this->Makefiles.front()->GetGeneratorConfigs(
  1279. cmMakefile::IncludeEmptyConfig)) {
  1280. this->Configs[config2].TargetAliases[output].GeneratorTarget = nullptr;
  1281. }
  1282. }
  1283. // Insert the alias into the map. If the alias was already present in the
  1284. // map and referred to another target, mark it as ambiguous.
  1285. TargetAlias ta;
  1286. ta.GeneratorTarget = target;
  1287. ta.Config = config;
  1288. auto newAliasGlobal =
  1289. this->TargetAliases.insert(std::make_pair(buildAlias, ta));
  1290. if (newAliasGlobal.second &&
  1291. newAliasGlobal.first->second.GeneratorTarget != target) {
  1292. newAliasGlobal.first->second.GeneratorTarget = nullptr;
  1293. }
  1294. auto newAliasConfig =
  1295. this->Configs[config].TargetAliases.insert(std::make_pair(outputPath, ta));
  1296. if (newAliasConfig.second &&
  1297. newAliasConfig.first->second.GeneratorTarget != target) {
  1298. newAliasConfig.first->second.GeneratorTarget = nullptr;
  1299. }
  1300. if (this->DefaultConfigs.count(config)) {
  1301. auto newAliasDefaultGlobal =
  1302. this->DefaultTargetAliases.insert(std::make_pair(outputPath, ta));
  1303. if (newAliasDefaultGlobal.second &&
  1304. newAliasDefaultGlobal.first->second.GeneratorTarget != target) {
  1305. newAliasDefaultGlobal.first->second.GeneratorTarget = nullptr;
  1306. }
  1307. }
  1308. }
  1309. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  1310. {
  1311. cmGlobalNinjaGenerator::WriteDivider(os);
  1312. os << "# Target aliases.\n\n";
  1313. cmNinjaBuild build("phony");
  1314. build.Outputs.emplace_back();
  1315. for (auto const& ta : this->TargetAliases) {
  1316. // Don't write ambiguous aliases.
  1317. if (!ta.second.GeneratorTarget) {
  1318. continue;
  1319. }
  1320. // Don't write alias if there is a already a custom command with
  1321. // matching output
  1322. if (this->HasCustomCommandOutput(ta.first)) {
  1323. continue;
  1324. }
  1325. build.Outputs.front() = ta.first;
  1326. build.ExplicitDeps.clear();
  1327. if (ta.second.Config == "all") {
  1328. for (auto const& config : this->CrossConfigs) {
  1329. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1330. build.ExplicitDeps, config,
  1331. DependOnTargetArtifact);
  1332. }
  1333. } else {
  1334. this->AppendTargetOutputs(ta.second.GeneratorTarget, build.ExplicitDeps,
  1335. ta.second.Config, DependOnTargetArtifact);
  1336. }
  1337. this->WriteBuild(this->EnableCrossConfigBuild() &&
  1338. (ta.second.Config == "all" ||
  1339. this->CrossConfigs.count(ta.second.Config))
  1340. ? os
  1341. : *this->GetImplFileStream(ta.second.Config),
  1342. build);
  1343. }
  1344. if (this->IsMultiConfig()) {
  1345. for (auto const& config : this->Makefiles.front()->GetGeneratorConfigs(
  1346. cmMakefile::IncludeEmptyConfig)) {
  1347. for (auto const& ta : this->Configs[config].TargetAliases) {
  1348. // Don't write ambiguous aliases.
  1349. if (!ta.second.GeneratorTarget) {
  1350. continue;
  1351. }
  1352. // Don't write alias if there is a already a custom command with
  1353. // matching output
  1354. if (this->HasCustomCommandOutput(ta.first)) {
  1355. continue;
  1356. }
  1357. build.Outputs.front() = ta.first;
  1358. build.ExplicitDeps.clear();
  1359. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1360. build.ExplicitDeps, config,
  1361. DependOnTargetArtifact);
  1362. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1363. }
  1364. }
  1365. if (!this->DefaultConfigs.empty()) {
  1366. for (auto const& ta : this->DefaultTargetAliases) {
  1367. // Don't write ambiguous aliases.
  1368. if (!ta.second.GeneratorTarget) {
  1369. continue;
  1370. }
  1371. // Don't write alias if there is a already a custom command with
  1372. // matching output
  1373. if (this->HasCustomCommandOutput(ta.first)) {
  1374. continue;
  1375. }
  1376. build.Outputs.front() = ta.first;
  1377. build.ExplicitDeps.clear();
  1378. for (auto const& config : this->DefaultConfigs) {
  1379. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1380. build.ExplicitDeps, config,
  1381. DependOnTargetArtifact);
  1382. }
  1383. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1384. }
  1385. }
  1386. }
  1387. }
  1388. void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
  1389. {
  1390. cmGlobalNinjaGenerator::WriteDivider(os);
  1391. os << "# Folder targets.\n\n";
  1392. std::map<std::string, DirectoryTarget> dirTargets =
  1393. this->ComputeDirectoryTargets();
  1394. for (auto const& it : dirTargets) {
  1395. cmNinjaBuild build("phony");
  1396. cmGlobalNinjaGenerator::WriteDivider(os);
  1397. std::string const& currentBinaryDir = it.first;
  1398. DirectoryTarget const& dt = it.second;
  1399. std::vector<std::string> configs =
  1400. dt.LG->GetMakefile()->GetGeneratorConfigs(
  1401. cmMakefile::IncludeEmptyConfig);
  1402. // Setup target
  1403. cmNinjaDeps configDeps;
  1404. build.Comment = cmStrCat("Folder: ", currentBinaryDir);
  1405. build.Outputs.emplace_back();
  1406. std::string const buildDirAllTarget =
  1407. this->ConvertToNinjaPath(cmStrCat(currentBinaryDir, "/all"));
  1408. for (auto const& config : configs) {
  1409. build.ExplicitDeps.clear();
  1410. build.Outputs.front() = this->BuildAlias(buildDirAllTarget, config);
  1411. configDeps.emplace_back(build.Outputs.front());
  1412. for (DirectoryTarget::Target const& t : dt.Targets) {
  1413. if (!this->IsExcludedFromAllInConfig(t, config)) {
  1414. this->AppendTargetOutputs(t.GT, build.ExplicitDeps, config,
  1415. DependOnTargetArtifact);
  1416. }
  1417. }
  1418. for (DirectoryTarget::Dir const& d : dt.Children) {
  1419. if (!d.ExcludeFromAll) {
  1420. build.ExplicitDeps.emplace_back(this->BuildAlias(
  1421. this->ConvertToNinjaPath(cmStrCat(d.Path, "/all")), config));
  1422. }
  1423. }
  1424. // Write target
  1425. this->WriteBuild(this->EnableCrossConfigBuild() &&
  1426. this->CrossConfigs.count(config)
  1427. ? os
  1428. : *this->GetImplFileStream(config),
  1429. build);
  1430. }
  1431. // Add shortcut target
  1432. if (this->IsMultiConfig()) {
  1433. for (auto const& config : configs) {
  1434. build.ExplicitDeps = { this->BuildAlias(buildDirAllTarget, config) };
  1435. build.Outputs.front() = buildDirAllTarget;
  1436. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1437. }
  1438. if (!this->DefaultFileConfig.empty()) {
  1439. build.ExplicitDeps.clear();
  1440. for (auto const& config : this->DefaultConfigs) {
  1441. build.ExplicitDeps.push_back(
  1442. this->BuildAlias(buildDirAllTarget, config));
  1443. }
  1444. build.Outputs.front() = buildDirAllTarget;
  1445. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1446. }
  1447. }
  1448. // Add target for all configs
  1449. if (this->EnableCrossConfigBuild()) {
  1450. build.ExplicitDeps.clear();
  1451. for (auto const& config : this->CrossConfigs) {
  1452. build.ExplicitDeps.push_back(
  1453. this->BuildAlias(buildDirAllTarget, config));
  1454. }
  1455. build.Outputs.front() = this->BuildAlias(buildDirAllTarget, "all");
  1456. this->WriteBuild(os, build);
  1457. }
  1458. }
  1459. }
  1460. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  1461. {
  1462. if (!this->ComputingUnknownDependencies) {
  1463. return;
  1464. }
  1465. // We need to collect the set of known build outputs.
  1466. // Start with those generated by WriteBuild calls.
  1467. // No other method needs this so we can take ownership
  1468. // of the set locally and throw it out when we are done.
  1469. std::set<std::string> knownDependencies;
  1470. knownDependencies.swap(this->CombinedBuildOutputs);
  1471. // now write out the unknown explicit dependencies.
  1472. // union the configured files, evaluations files and the
  1473. // CombinedBuildOutputs,
  1474. // and then difference with CombinedExplicitDependencies to find the explicit
  1475. // dependencies that we have no rule for
  1476. cmGlobalNinjaGenerator::WriteDivider(os);
  1477. /* clang-format off */
  1478. os << "# Unknown Build Time Dependencies.\n"
  1479. << "# Tell Ninja that they may appear as side effects of build rules\n"
  1480. << "# otherwise ordered by order-only dependencies.\n\n";
  1481. /* clang-format on */
  1482. // get the list of files that cmake itself has generated as a
  1483. // product of configuration.
  1484. for (const auto& lg : this->LocalGenerators) {
  1485. // get the vector of files created by this makefile and convert them
  1486. // to ninja paths, which are all relative in respect to the build directory
  1487. for (std::string const& file : lg->GetMakefile()->GetOutputFiles()) {
  1488. knownDependencies.insert(this->ConvertToNinjaPath(file));
  1489. }
  1490. if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1491. // get list files which are implicit dependencies as well and will be
  1492. // phony for rebuild manifest
  1493. for (std::string const& j : lg->GetMakefile()->GetListFiles()) {
  1494. knownDependencies.insert(this->ConvertToNinjaPath(j));
  1495. }
  1496. }
  1497. for (const auto& li : lg->GetMakefile()->GetEvaluationFiles()) {
  1498. // get all the files created by generator expressions and convert them
  1499. // to ninja paths
  1500. for (std::string const& evaluationFile : li->GetFiles()) {
  1501. knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile));
  1502. }
  1503. }
  1504. }
  1505. knownDependencies.insert(this->CMakeCacheFile);
  1506. for (auto const& ta : this->TargetAliases) {
  1507. knownDependencies.insert(this->ConvertToNinjaPath(ta.first));
  1508. }
  1509. // remove all source files we know will exist.
  1510. for (auto const& i : this->AssumedSourceDependencies) {
  1511. knownDependencies.insert(this->ConvertToNinjaPath(i.first));
  1512. }
  1513. // now we difference with CombinedCustomCommandExplicitDependencies to find
  1514. // the list of items we know nothing about.
  1515. // We have encoded all the paths in CombinedCustomCommandExplicitDependencies
  1516. // and knownDependencies so no matter if unix or windows paths they
  1517. // should all match now.
  1518. std::vector<std::string> unknownExplicitDepends;
  1519. this->CombinedCustomCommandExplicitDependencies.erase(this->TargetAll);
  1520. std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(),
  1521. this->CombinedCustomCommandExplicitDependencies.end(),
  1522. knownDependencies.begin(), knownDependencies.end(),
  1523. std::back_inserter(unknownExplicitDepends));
  1524. std::vector<std::string> warnExplicitDepends;
  1525. if (!unknownExplicitDepends.empty()) {
  1526. cmake* cmk = this->GetCMakeInstance();
  1527. std::string const& buildRoot = cmk->GetHomeOutputDirectory();
  1528. bool const inSource = (buildRoot == cmk->GetHomeDirectory());
  1529. bool const warn = (!inSource && (this->PolicyCMP0058 == cmPolicies::WARN));
  1530. cmNinjaBuild build("phony");
  1531. build.Outputs.emplace_back("");
  1532. for (std::string const& ued : unknownExplicitDepends) {
  1533. // verify the file is in the build directory
  1534. std::string const absDepPath =
  1535. cmSystemTools::CollapseFullPath(ued, buildRoot);
  1536. if (cmSystemTools::IsSubDirectory(absDepPath, buildRoot)) {
  1537. // Generate phony build statement
  1538. build.Outputs[0] = ued;
  1539. this->WriteBuild(os, build);
  1540. // Add to warning on demand
  1541. if (warn && warnExplicitDepends.size() < 10) {
  1542. warnExplicitDepends.push_back(ued);
  1543. }
  1544. }
  1545. }
  1546. }
  1547. if (!warnExplicitDepends.empty()) {
  1548. std::ostringstream w;
  1549. /* clang-format off */
  1550. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0058) << "\n"
  1551. "This project specifies custom command DEPENDS on files "
  1552. "in the build tree that are not specified as the OUTPUT or "
  1553. "BYPRODUCTS of any add_custom_command or add_custom_target:\n"
  1554. " " << cmJoin(warnExplicitDepends, "\n ") <<
  1555. "\n"
  1556. "For compatibility with versions of CMake that did not have "
  1557. "the BYPRODUCTS option, CMake is generating phony rules for "
  1558. "such files to convince 'ninja' to build."
  1559. "\n"
  1560. "Project authors should add the missing BYPRODUCTS or OUTPUT "
  1561. "options to the custom commands that produce these files."
  1562. ;
  1563. /* clang-format on */
  1564. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1565. w.str());
  1566. }
  1567. }
  1568. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  1569. {
  1570. // Write headers.
  1571. cmGlobalNinjaGenerator::WriteDivider(os);
  1572. os << "# Built-in targets\n\n";
  1573. this->WriteTargetRebuildManifest(os);
  1574. this->WriteTargetClean(os);
  1575. this->WriteTargetHelp(os);
  1576. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  1577. cmMakefile::IncludeEmptyConfig)) {
  1578. this->WriteTargetDefault(*this->GetConfigFileStream(config));
  1579. }
  1580. if (!this->DefaultFileConfig.empty()) {
  1581. this->WriteTargetDefault(*this->GetDefaultFileStream());
  1582. }
  1583. }
  1584. void cmGlobalNinjaGenerator::WriteTargetDefault(std::ostream& os)
  1585. {
  1586. if (!this->HasOutputPathPrefix()) {
  1587. cmNinjaDeps all;
  1588. all.push_back(this->TargetAll);
  1589. cmGlobalNinjaGenerator::WriteDefault(os, all,
  1590. "Make the all target the default.");
  1591. }
  1592. }
  1593. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  1594. {
  1595. if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1596. return;
  1597. }
  1598. const auto& lg = this->LocalGenerators[0];
  1599. {
  1600. cmNinjaRule rule("RERUN_CMAKE");
  1601. rule.Command =
  1602. cmStrCat(this->CMakeCmd(), " --regenerate-during-build -S",
  1603. lg->ConvertToOutputFormat(lg->GetSourceDirectory(),
  1604. cmOutputConverter::SHELL),
  1605. " -B",
  1606. lg->ConvertToOutputFormat(lg->GetBinaryDirectory(),
  1607. cmOutputConverter::SHELL));
  1608. rule.Description = "Re-running CMake...";
  1609. rule.Comment = "Rule for re-running cmake.";
  1610. rule.Generator = true;
  1611. WriteRule(*this->RulesFileStream, rule);
  1612. }
  1613. cmNinjaBuild reBuild("RERUN_CMAKE");
  1614. reBuild.Comment = "Re-run CMake if any of its inputs changed.";
  1615. this->AddRebuildManifestOutputs(reBuild.Outputs);
  1616. for (const auto& localGen : this->LocalGenerators) {
  1617. for (std::string const& fi : localGen->GetMakefile()->GetListFiles()) {
  1618. reBuild.ImplicitDeps.push_back(this->ConvertToNinjaPath(fi));
  1619. }
  1620. }
  1621. reBuild.ImplicitDeps.push_back(this->CMakeCacheFile);
  1622. // Use 'console' pool to get non buffered output of the CMake re-run call
  1623. // Available since Ninja 1.5
  1624. if (this->SupportsConsolePool()) {
  1625. reBuild.Variables["pool"] = "console";
  1626. }
  1627. cmake* cm = this->GetCMakeInstance();
  1628. if (this->SupportsManifestRestat() && cm->DoWriteGlobVerifyTarget()) {
  1629. {
  1630. cmNinjaRule rule("VERIFY_GLOBS");
  1631. rule.Command =
  1632. cmStrCat(this->CMakeCmd(), " -P ",
  1633. lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1634. cmOutputConverter::SHELL));
  1635. rule.Description = "Re-checking globbed directories...";
  1636. rule.Comment = "Rule for re-checking globbed directories.";
  1637. rule.Generator = true;
  1638. this->WriteRule(*this->RulesFileStream, rule);
  1639. }
  1640. cmNinjaBuild phonyBuild("phony");
  1641. phonyBuild.Comment = "Phony target to force glob verification run.";
  1642. phonyBuild.Outputs.push_back(
  1643. cmStrCat(cm->GetGlobVerifyScript(), "_force"));
  1644. this->WriteBuild(os, phonyBuild);
  1645. reBuild.Variables["restat"] = "1";
  1646. std::string const verifyScriptFile =
  1647. this->NinjaOutputPath(cm->GetGlobVerifyScript());
  1648. std::string const verifyStampFile =
  1649. this->NinjaOutputPath(cm->GetGlobVerifyStamp());
  1650. {
  1651. cmNinjaBuild vgBuild("VERIFY_GLOBS");
  1652. vgBuild.Comment =
  1653. "Re-run CMake to check if globbed directories changed.";
  1654. vgBuild.Outputs.push_back(verifyStampFile);
  1655. vgBuild.ImplicitDeps = phonyBuild.Outputs;
  1656. vgBuild.Variables = reBuild.Variables;
  1657. this->WriteBuild(os, vgBuild);
  1658. }
  1659. reBuild.Variables.erase("restat");
  1660. reBuild.ImplicitDeps.push_back(verifyScriptFile);
  1661. reBuild.ExplicitDeps.push_back(verifyStampFile);
  1662. } else if (!this->SupportsManifestRestat() &&
  1663. cm->DoWriteGlobVerifyTarget()) {
  1664. std::ostringstream msg;
  1665. msg << "The detected version of Ninja:\n"
  1666. << " " << this->NinjaVersion << "\n"
  1667. << "is less than the version of Ninja required by CMake for adding "
  1668. "restat dependencies to the build.ninja manifest regeneration "
  1669. "target:\n"
  1670. << " "
  1671. << cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat()
  1672. << "\n";
  1673. msg << "Any pre-check scripts, such as those generated for file(GLOB "
  1674. "CONFIGURE_DEPENDS), will not be run by Ninja.";
  1675. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1676. msg.str());
  1677. }
  1678. std::sort(reBuild.ImplicitDeps.begin(), reBuild.ImplicitDeps.end());
  1679. reBuild.ImplicitDeps.erase(
  1680. std::unique(reBuild.ImplicitDeps.begin(), reBuild.ImplicitDeps.end()),
  1681. reBuild.ImplicitDeps.end());
  1682. this->WriteBuild(os, reBuild);
  1683. {
  1684. cmNinjaBuild build("phony");
  1685. build.Comment = "A missing CMake input file is not an error.";
  1686. std::set_difference(std::make_move_iterator(reBuild.ImplicitDeps.begin()),
  1687. std::make_move_iterator(reBuild.ImplicitDeps.end()),
  1688. this->CustomCommandOutputs.begin(),
  1689. this->CustomCommandOutputs.end(),
  1690. std::back_inserter(build.Outputs));
  1691. this->WriteBuild(os, build);
  1692. }
  1693. }
  1694. std::string cmGlobalNinjaGenerator::CMakeCmd() const
  1695. {
  1696. const auto& lgen = this->LocalGenerators.at(0);
  1697. return lgen->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  1698. cmOutputConverter::SHELL);
  1699. }
  1700. std::string cmGlobalNinjaGenerator::NinjaCmd() const
  1701. {
  1702. const auto& lgen = this->LocalGenerators[0];
  1703. if (lgen != nullptr) {
  1704. return lgen->ConvertToOutputFormat(this->NinjaCommand,
  1705. cmOutputConverter::SHELL);
  1706. }
  1707. return "ninja";
  1708. }
  1709. bool cmGlobalNinjaGenerator::SupportsConsolePool() const
  1710. {
  1711. return this->NinjaSupportsConsolePool;
  1712. }
  1713. bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const
  1714. {
  1715. return this->NinjaSupportsImplicitOuts;
  1716. }
  1717. bool cmGlobalNinjaGenerator::SupportsManifestRestat() const
  1718. {
  1719. return this->NinjaSupportsManifestRestat;
  1720. }
  1721. bool cmGlobalNinjaGenerator::SupportsMultilineDepfile() const
  1722. {
  1723. return this->NinjaSupportsMultilineDepfile;
  1724. }
  1725. bool cmGlobalNinjaGenerator::WriteTargetCleanAdditional(std::ostream& os)
  1726. {
  1727. const auto& lgr = this->LocalGenerators.at(0);
  1728. std::string cleanScriptRel = "CMakeFiles/clean_additional.cmake";
  1729. std::string cleanScriptAbs =
  1730. cmStrCat(lgr->GetBinaryDirectory(), '/', cleanScriptRel);
  1731. std::vector<std::string> configs =
  1732. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1733. // Check if there are additional files to clean
  1734. bool empty = true;
  1735. for (auto const& config : configs) {
  1736. auto const it = this->Configs.find(config);
  1737. if (it != this->Configs.end() &&
  1738. !it->second.AdditionalCleanFiles.empty()) {
  1739. empty = false;
  1740. break;
  1741. }
  1742. }
  1743. if (empty) {
  1744. // Remove cmake clean script file if it exists
  1745. cmSystemTools::RemoveFile(cleanScriptAbs);
  1746. return false;
  1747. }
  1748. // Write cmake clean script file
  1749. {
  1750. cmGeneratedFileStream fout(cleanScriptAbs);
  1751. if (!fout) {
  1752. return false;
  1753. }
  1754. fout << "# Additional clean files\ncmake_minimum_required(VERSION 3.16)\n";
  1755. for (auto const& config : configs) {
  1756. auto const it = this->Configs.find(config);
  1757. if (it != this->Configs.end() &&
  1758. !it->second.AdditionalCleanFiles.empty()) {
  1759. fout << "\nif(\"${CONFIG}\" STREQUAL \"\" OR \"${CONFIG}\" STREQUAL \""
  1760. << config << "\")\n";
  1761. fout << " file(REMOVE_RECURSE\n";
  1762. for (std::string const& acf : it->second.AdditionalCleanFiles) {
  1763. fout << " "
  1764. << cmOutputConverter::EscapeForCMake(
  1765. this->ConvertToNinjaPath(acf))
  1766. << '\n';
  1767. }
  1768. fout << " )\n";
  1769. fout << "endif()\n";
  1770. }
  1771. }
  1772. }
  1773. // Register clean script file
  1774. lgr->GetMakefile()->AddCMakeOutputFile(cleanScriptAbs);
  1775. // Write rule
  1776. {
  1777. cmNinjaRule rule("CLEAN_ADDITIONAL");
  1778. rule.Command = cmStrCat(
  1779. this->CMakeCmd(), " -DCONFIG=$CONFIG -P ",
  1780. lgr->ConvertToOutputFormat(this->NinjaOutputPath(cleanScriptRel),
  1781. cmOutputConverter::SHELL));
  1782. rule.Description = "Cleaning additional files...";
  1783. rule.Comment = "Rule for cleaning additional files.";
  1784. WriteRule(*this->RulesFileStream, rule);
  1785. }
  1786. // Write build
  1787. {
  1788. cmNinjaBuild build("CLEAN_ADDITIONAL");
  1789. build.Comment = "Clean additional files.";
  1790. build.Outputs.emplace_back();
  1791. for (auto const& config : configs) {
  1792. build.Outputs.front() = this->BuildAlias(
  1793. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()), config);
  1794. build.Variables["CONFIG"] = config;
  1795. this->WriteBuild(os, build);
  1796. }
  1797. if (this->IsMultiConfig()) {
  1798. build.Outputs.front() =
  1799. this->NinjaOutputPath(this->GetAdditionalCleanTargetName());
  1800. build.Variables["CONFIG"] = "";
  1801. this->WriteBuild(os, build);
  1802. }
  1803. }
  1804. // Return success
  1805. return true;
  1806. }
  1807. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1808. {
  1809. // -- Additional clean target
  1810. bool additionalFiles = this->WriteTargetCleanAdditional(os);
  1811. // -- Default clean target
  1812. // Write rule
  1813. {
  1814. cmNinjaRule rule("CLEAN");
  1815. rule.Command = cmStrCat(this->NinjaCmd(), " $FILE_ARG -t clean $TARGETS");
  1816. rule.Description = "Cleaning all built files...";
  1817. rule.Comment = "Rule for cleaning all built files.";
  1818. WriteRule(*this->RulesFileStream, rule);
  1819. }
  1820. auto const configs = this->Makefiles.front()->GetGeneratorConfigs(
  1821. cmMakefile::IncludeEmptyConfig);
  1822. // Write build
  1823. {
  1824. cmNinjaBuild build("CLEAN");
  1825. build.Comment = "Clean all the built files.";
  1826. build.Outputs.emplace_back();
  1827. for (auto const& config : configs) {
  1828. build.Outputs.front() = this->BuildAlias(
  1829. this->NinjaOutputPath(this->GetCleanTargetName()), config);
  1830. if (this->IsMultiConfig()) {
  1831. build.Variables["TARGETS"] =
  1832. cmStrCat(this->BuildAlias(GetByproductsForCleanTargetName(), config),
  1833. " ", GetByproductsForCleanTargetName());
  1834. }
  1835. build.ExplicitDeps.clear();
  1836. if (additionalFiles) {
  1837. build.ExplicitDeps.push_back(this->BuildAlias(
  1838. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()),
  1839. config));
  1840. }
  1841. for (auto const& fileConfig : configs) {
  1842. if (fileConfig != config && !this->EnableCrossConfigBuild()) {
  1843. continue;
  1844. }
  1845. if (this->IsMultiConfig()) {
  1846. build.Variables["FILE_ARG"] = cmStrCat(
  1847. "-f ",
  1848. cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(fileConfig));
  1849. }
  1850. this->WriteBuild(*this->GetImplFileStream(fileConfig), build);
  1851. }
  1852. }
  1853. if (this->EnableCrossConfigBuild()) {
  1854. build.Outputs.front() = this->BuildAlias(
  1855. this->NinjaOutputPath(this->GetCleanTargetName()), "all");
  1856. build.ExplicitDeps.clear();
  1857. if (additionalFiles) {
  1858. for (auto const& config : this->CrossConfigs) {
  1859. build.ExplicitDeps.push_back(this->BuildAlias(
  1860. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()),
  1861. config));
  1862. }
  1863. }
  1864. std::vector<std::string> byproducts;
  1865. for (auto const& config : this->CrossConfigs) {
  1866. byproducts.push_back(
  1867. this->BuildAlias(GetByproductsForCleanTargetName(), config));
  1868. }
  1869. byproducts.emplace_back(GetByproductsForCleanTargetName());
  1870. build.Variables["TARGETS"] = cmJoin(byproducts, " ");
  1871. for (auto const& fileConfig : configs) {
  1872. build.Variables["FILE_ARG"] = cmStrCat(
  1873. "-f ",
  1874. cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(fileConfig));
  1875. this->WriteBuild(*this->GetImplFileStream(fileConfig), build);
  1876. }
  1877. }
  1878. }
  1879. if (this->IsMultiConfig()) {
  1880. cmNinjaBuild build("phony");
  1881. build.Outputs.emplace_back(
  1882. this->NinjaOutputPath(this->GetCleanTargetName()));
  1883. build.ExplicitDeps.emplace_back();
  1884. for (auto const& config : configs) {
  1885. build.ExplicitDeps.front() = this->BuildAlias(
  1886. this->NinjaOutputPath(this->GetCleanTargetName()), config);
  1887. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1888. }
  1889. if (!this->DefaultConfigs.empty()) {
  1890. build.ExplicitDeps.clear();
  1891. for (auto const& config : this->DefaultConfigs) {
  1892. build.ExplicitDeps.push_back(this->BuildAlias(
  1893. this->NinjaOutputPath(this->GetCleanTargetName()), config));
  1894. }
  1895. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1896. }
  1897. }
  1898. // Write byproducts
  1899. if (this->IsMultiConfig()) {
  1900. cmNinjaBuild build("phony");
  1901. build.Comment = "Clean byproducts.";
  1902. build.Outputs.emplace_back(
  1903. this->ConvertToNinjaPath(GetByproductsForCleanTargetName()));
  1904. build.ExplicitDeps = this->ByproductsForCleanTarget;
  1905. this->WriteBuild(os, build);
  1906. for (auto const& config : configs) {
  1907. build.Outputs.front() = this->BuildAlias(
  1908. this->ConvertToNinjaPath(GetByproductsForCleanTargetName()), config);
  1909. build.ExplicitDeps = this->Configs[config].ByproductsForCleanTarget;
  1910. this->WriteBuild(os, build);
  1911. }
  1912. }
  1913. }
  1914. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1915. {
  1916. {
  1917. cmNinjaRule rule("HELP");
  1918. rule.Command = cmStrCat(this->NinjaCmd(), " -t targets");
  1919. rule.Description = "All primary targets available:";
  1920. rule.Comment = "Rule for printing all primary targets available.";
  1921. WriteRule(*this->RulesFileStream, rule);
  1922. }
  1923. {
  1924. cmNinjaBuild build("HELP");
  1925. build.Comment = "Print all primary targets available.";
  1926. build.Outputs.push_back(this->NinjaOutputPath("help"));
  1927. this->WriteBuild(os, build);
  1928. }
  1929. }
  1930. void cmGlobalNinjaGenerator::InitOutputPathPrefix()
  1931. {
  1932. this->OutputPathPrefix =
  1933. this->LocalGenerators[0]->GetMakefile()->GetSafeDefinition(
  1934. "CMAKE_NINJA_OUTPUT_PATH_PREFIX");
  1935. EnsureTrailingSlash(this->OutputPathPrefix);
  1936. }
  1937. std::string cmGlobalNinjaGenerator::NinjaOutputPath(
  1938. std::string const& path) const
  1939. {
  1940. if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) {
  1941. return path;
  1942. }
  1943. return cmStrCat(this->OutputPathPrefix, path);
  1944. }
  1945. void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix(
  1946. std::string& path)
  1947. {
  1948. if (path.empty()) {
  1949. return;
  1950. }
  1951. EnsureTrailingSlash(path);
  1952. cmStripSuffixIfExists(path, this->OutputPathPrefix);
  1953. }
  1954. #if !defined(CMAKE_BOOTSTRAP)
  1955. /*
  1956. We use the following approach to support Fortran. Each target already
  1957. has a <target>.dir/ directory used to hold intermediate files for CMake.
  1958. For each target, a FortranDependInfo.json file is generated by CMake with
  1959. information about include directories, module directories, and the locations
  1960. the per-target directories for target dependencies.
  1961. Compilation of source files within a target is split into the following steps:
  1962. 1. Preprocess all sources, scan preprocessed output for module dependencies.
  1963. This step is done with independent build statements for each source,
  1964. and can therefore be done in parallel.
  1965. rule Fortran_PREPROCESS
  1966. depfile = $DEP_FILE
  1967. command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out &&
  1968. cmake -E cmake_ninja_depends \
  1969. --tdi=FortranDependInfo.json --pp=$out --dep=$DEP_FILE \
  1970. --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE \
  1971. --lang=Fortran
  1972. build src.f90-pp.f90 | src.f90.o.ddi: Fortran_PREPROCESS src.f90
  1973. OBJ_FILE = src.f90.o
  1974. DEP_FILE = src.f90.o.d
  1975. DYNDEP_INTERMEDIATE_FILE = src.f90.o.ddi
  1976. The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output
  1977. and generates the ninja depfile for preprocessor dependencies. It also
  1978. generates a "ddi" file (in a format private to CMake) that lists the
  1979. object file that compilation will produce along with the module names
  1980. it provides and/or requires. The "ddi" file is an implicit output
  1981. because it should not appear in "$out" but is generated by the rule.
  1982. 2. Consolidate the per-source module dependencies saved in the "ddi"
  1983. files from all sources to produce a ninja "dyndep" file, ``Fortran.dd``.
  1984. rule Fortran_DYNDEP
  1985. command = cmake -E cmake_ninja_dyndep \
  1986. --tdi=FortranDependInfo.json --lang=Fortran --dd=$out $in
  1987. build Fortran.dd: Fortran_DYNDEP src1.f90.o.ddi src2.f90.o.ddi
  1988. The ``cmake -E cmake_ninja_dyndep`` tool reads the "ddi" files from all
  1989. sources in the target and the ``FortranModules.json`` files from targets
  1990. on which the target depends. It computes dependency edges on compilations
  1991. that require modules to those that provide the modules. This information
  1992. is placed in the ``Fortran.dd`` file for ninja to load later. It also
  1993. writes the expected location of modules provided by this target into
  1994. ``FortranModules.json`` for use by dependent targets.
  1995. 3. Compile all sources after loading dynamically discovered dependencies
  1996. of the compilation build statements from their ``dyndep`` bindings.
  1997. rule Fortran_COMPILE
  1998. command = gfortran $INCLUDES $FLAGS -c $in -o $out
  1999. build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd
  2000. dyndep = Fortran.dd
  2001. The "dyndep" binding tells ninja to load dynamically discovered
  2002. dependency information from ``Fortran.dd``. This adds information
  2003. such as:
  2004. build src1.f90.o | mod1.mod: dyndep
  2005. restat = 1
  2006. This tells ninja that ``mod1.mod`` is an implicit output of compiling
  2007. the object file ``src1.f90.o``. The ``restat`` binding tells it that
  2008. the timestamp of the output may not always change. Additionally:
  2009. build src2.f90.o: dyndep | mod1.mod
  2010. This tells ninja that ``mod1.mod`` is a dependency of compiling the
  2011. object file ``src2.f90.o``. This ensures that ``src1.f90.o`` and
  2012. ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built
  2013. (because the latter consumes the module).
  2014. */
  2015. namespace {
  2016. struct cmSourceInfo
  2017. {
  2018. cmScanDepInfo ScanDep;
  2019. std::vector<std::string> Includes;
  2020. };
  2021. cm::optional<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran(
  2022. std::string const& arg_tdi, std::string const& arg_pp);
  2023. }
  2024. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  2025. std::vector<std::string>::const_iterator argEnd)
  2026. {
  2027. std::string arg_tdi;
  2028. std::string arg_pp;
  2029. std::string arg_dep;
  2030. std::string arg_obj;
  2031. std::string arg_ddi;
  2032. std::string arg_lang;
  2033. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  2034. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  2035. arg_tdi = arg.substr(6);
  2036. } else if (cmHasLiteralPrefix(arg, "--pp=")) {
  2037. arg_pp = arg.substr(5);
  2038. } else if (cmHasLiteralPrefix(arg, "--dep=")) {
  2039. arg_dep = arg.substr(6);
  2040. } else if (cmHasLiteralPrefix(arg, "--obj=")) {
  2041. arg_obj = arg.substr(6);
  2042. } else if (cmHasLiteralPrefix(arg, "--ddi=")) {
  2043. arg_ddi = arg.substr(6);
  2044. } else if (cmHasLiteralPrefix(arg, "--lang=")) {
  2045. arg_lang = arg.substr(7);
  2046. } else {
  2047. cmSystemTools::Error(
  2048. cmStrCat("-E cmake_ninja_depends unknown argument: ", arg));
  2049. return 1;
  2050. }
  2051. }
  2052. if (arg_tdi.empty()) {
  2053. cmSystemTools::Error("-E cmake_ninja_depends requires value for --tdi=");
  2054. return 1;
  2055. }
  2056. if (arg_pp.empty()) {
  2057. cmSystemTools::Error("-E cmake_ninja_depends requires value for --pp=");
  2058. return 1;
  2059. }
  2060. if (arg_dep.empty()) {
  2061. cmSystemTools::Error("-E cmake_ninja_depends requires value for --dep=");
  2062. return 1;
  2063. }
  2064. if (arg_obj.empty()) {
  2065. cmSystemTools::Error("-E cmake_ninja_depends requires value for --obj=");
  2066. return 1;
  2067. }
  2068. if (arg_ddi.empty()) {
  2069. cmSystemTools::Error("-E cmake_ninja_depends requires value for --ddi=");
  2070. return 1;
  2071. }
  2072. if (arg_lang.empty()) {
  2073. cmSystemTools::Error("-E cmake_ninja_depends requires value for --lang=");
  2074. return 1;
  2075. }
  2076. cm::optional<cmSourceInfo> info;
  2077. if (arg_lang == "Fortran") {
  2078. info = cmcmd_cmake_ninja_depends_fortran(arg_tdi, arg_pp);
  2079. } else {
  2080. cmSystemTools::Error(
  2081. cmStrCat("-E cmake_ninja_depends does not understand the ", arg_lang,
  2082. " language"));
  2083. return 1;
  2084. }
  2085. if (!info) {
  2086. // The error message is already expected to have been output.
  2087. return 1;
  2088. }
  2089. info->ScanDep.PrimaryOutput = arg_obj;
  2090. {
  2091. cmGeneratedFileStream depfile(arg_dep);
  2092. depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":";
  2093. for (std::string const& include : info->Includes) {
  2094. depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include);
  2095. }
  2096. depfile << "\n";
  2097. }
  2098. if (!cmScanDepFormat_P1689_Write(arg_ddi, info->ScanDep)) {
  2099. cmSystemTools::Error(
  2100. cmStrCat("-E cmake_ninja_depends failed to write ", arg_ddi));
  2101. return 1;
  2102. }
  2103. return 0;
  2104. }
  2105. namespace {
  2106. cm::optional<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran(
  2107. std::string const& arg_tdi, std::string const& arg_pp)
  2108. {
  2109. cm::optional<cmSourceInfo> info;
  2110. cmFortranCompiler fc;
  2111. std::vector<std::string> includes;
  2112. {
  2113. Json::Value tdio;
  2114. Json::Value const& tdi = tdio;
  2115. {
  2116. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  2117. Json::Reader reader;
  2118. if (!reader.parse(tdif, tdio, false)) {
  2119. cmSystemTools::Error(
  2120. cmStrCat("-E cmake_ninja_depends failed to parse ", arg_tdi,
  2121. reader.getFormattedErrorMessages()));
  2122. return info;
  2123. }
  2124. }
  2125. Json::Value const& tdi_include_dirs = tdi["include-dirs"];
  2126. if (tdi_include_dirs.isArray()) {
  2127. for (auto const& tdi_include_dir : tdi_include_dirs) {
  2128. includes.push_back(tdi_include_dir.asString());
  2129. }
  2130. }
  2131. Json::Value const& tdi_compiler_id = tdi["compiler-id"];
  2132. fc.Id = tdi_compiler_id.asString();
  2133. Json::Value const& tdi_submodule_sep = tdi["submodule-sep"];
  2134. fc.SModSep = tdi_submodule_sep.asString();
  2135. Json::Value const& tdi_submodule_ext = tdi["submodule-ext"];
  2136. fc.SModExt = tdi_submodule_ext.asString();
  2137. }
  2138. cmFortranSourceInfo finfo;
  2139. std::set<std::string> defines;
  2140. cmFortranParser parser(fc, includes, defines, finfo);
  2141. if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) {
  2142. cmSystemTools::Error(
  2143. cmStrCat("-E cmake_ninja_depends failed to open ", arg_pp));
  2144. return info;
  2145. }
  2146. if (cmFortran_yyparse(parser.Scanner) != 0) {
  2147. // Failed to parse the file.
  2148. return info;
  2149. }
  2150. info = cmSourceInfo();
  2151. for (std::string const& provide : finfo.Provides) {
  2152. cmSourceReqInfo src_info;
  2153. src_info.LogicalName = provide;
  2154. src_info.CompiledModulePath = provide;
  2155. info->ScanDep.Provides.emplace_back(src_info);
  2156. }
  2157. for (std::string const& require : finfo.Requires) {
  2158. // Require modules not provided in the same source.
  2159. if (finfo.Provides.count(require)) {
  2160. continue;
  2161. }
  2162. cmSourceReqInfo src_info;
  2163. src_info.LogicalName = require;
  2164. src_info.CompiledModulePath = require;
  2165. info->ScanDep.Requires.emplace_back(src_info);
  2166. }
  2167. for (std::string const& include : finfo.Includes) {
  2168. info->Includes.push_back(include);
  2169. }
  2170. return info;
  2171. }
  2172. }
  2173. bool cmGlobalNinjaGenerator::WriteDyndepFile(
  2174. std::string const& dir_top_src, std::string const& dir_top_bld,
  2175. std::string const& dir_cur_src, std::string const& dir_cur_bld,
  2176. std::string const& arg_dd, std::vector<std::string> const& arg_ddis,
  2177. std::string const& module_dir,
  2178. std::vector<std::string> const& linked_target_dirs,
  2179. std::string const& arg_lang, std::string const& arg_modmapfmt)
  2180. {
  2181. // Setup path conversions.
  2182. {
  2183. cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot();
  2184. snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
  2185. snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
  2186. snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
  2187. snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str());
  2188. auto mfd = cm::make_unique<cmMakefile>(this, snapshot);
  2189. auto lgd = this->CreateLocalGenerator(mfd.get());
  2190. this->Makefiles.push_back(std::move(mfd));
  2191. this->LocalGenerators.push_back(std::move(lgd));
  2192. }
  2193. std::vector<cmScanDepInfo> objects;
  2194. for (std::string const& arg_ddi : arg_ddis) {
  2195. cmScanDepInfo info;
  2196. if (!cmScanDepFormat_P1689_Parse(arg_ddi, &info)) {
  2197. cmSystemTools::Error(
  2198. cmStrCat("-E cmake_ninja_dyndep failed to parse ddi file ", arg_ddi));
  2199. return false;
  2200. }
  2201. objects.push_back(std::move(info));
  2202. }
  2203. // Map from module name to module file path, if known.
  2204. std::map<std::string, std::string> mod_files;
  2205. // Populate the module map with those provided by linked targets first.
  2206. for (std::string const& linked_target_dir : linked_target_dirs) {
  2207. std::string const ltmn =
  2208. cmStrCat(linked_target_dir, "/", arg_lang, "Modules.json");
  2209. Json::Value ltm;
  2210. cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
  2211. Json::Reader reader;
  2212. if (ltmf && !reader.parse(ltmf, ltm, false)) {
  2213. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2214. linked_target_dir,
  2215. reader.getFormattedErrorMessages()));
  2216. return false;
  2217. }
  2218. if (ltm.isObject()) {
  2219. for (Json::Value::iterator i = ltm.begin(); i != ltm.end(); ++i) {
  2220. mod_files[i.key().asString()] = i->asString();
  2221. }
  2222. }
  2223. }
  2224. // Extend the module map with those provided by this target.
  2225. // We do this after loading the modules provided by linked targets
  2226. // in case we have one of the same name that must be preferred.
  2227. Json::Value tm = Json::objectValue;
  2228. for (cmScanDepInfo const& object : objects) {
  2229. for (auto const& p : object.Provides) {
  2230. std::string const mod = cmStrCat(
  2231. module_dir, cmSystemTools::GetFilenameName(p.CompiledModulePath));
  2232. mod_files[p.LogicalName] = mod;
  2233. tm[p.LogicalName] = mod;
  2234. }
  2235. }
  2236. cmGeneratedFileStream ddf(arg_dd);
  2237. ddf << "ninja_dyndep_version = 1.0\n";
  2238. {
  2239. cmNinjaBuild build("dyndep");
  2240. build.Outputs.emplace_back("");
  2241. for (cmScanDepInfo const& object : objects) {
  2242. build.Outputs[0] = this->ConvertToNinjaPath(object.PrimaryOutput);
  2243. build.ImplicitOuts.clear();
  2244. for (auto const& p : object.Provides) {
  2245. build.ImplicitOuts.push_back(
  2246. this->ConvertToNinjaPath(mod_files[p.LogicalName]));
  2247. }
  2248. build.ImplicitDeps.clear();
  2249. for (auto const& r : object.Requires) {
  2250. auto mit = mod_files.find(r.LogicalName);
  2251. if (mit != mod_files.end()) {
  2252. build.ImplicitDeps.push_back(this->ConvertToNinjaPath(mit->second));
  2253. }
  2254. }
  2255. build.Variables.clear();
  2256. if (!object.Provides.empty()) {
  2257. build.Variables.emplace("restat", "1");
  2258. }
  2259. if (arg_modmapfmt.empty()) {
  2260. // nothing to do.
  2261. } else {
  2262. std::stringstream mm;
  2263. if (arg_modmapfmt == "gcc") {
  2264. // Documented in GCC's documentation. The format is a series of lines
  2265. // with a module name and the associated filename separated by
  2266. // spaces. The first line may use `$root` as the module name to
  2267. // specify a "repository root". That is used to anchor any relative
  2268. // paths present in the file (CMake should never generate any).
  2269. // Write the root directory to use for module paths.
  2270. mm << "$root .\n";
  2271. for (auto const& l : object.Provides) {
  2272. auto m = mod_files.find(l.LogicalName);
  2273. if (m != mod_files.end()) {
  2274. mm << l.LogicalName << " " << this->ConvertToNinjaPath(m->second)
  2275. << "\n";
  2276. }
  2277. }
  2278. for (auto const& r : object.Requires) {
  2279. auto m = mod_files.find(r.LogicalName);
  2280. if (m != mod_files.end()) {
  2281. mm << r.LogicalName << " " << this->ConvertToNinjaPath(m->second)
  2282. << "\n";
  2283. }
  2284. }
  2285. } else {
  2286. cmSystemTools::Error(
  2287. cmStrCat("-E cmake_ninja_dyndep does not understand the ",
  2288. arg_modmapfmt, " module map format"));
  2289. return false;
  2290. }
  2291. // XXX(modmap): If changing this path construction, change
  2292. // `cmNinjaTargetGenerator::WriteObjectBuildStatements` to generate the
  2293. // corresponding file path.
  2294. cmGeneratedFileStream mmf(cmStrCat(object.PrimaryOutput, ".modmap"));
  2295. mmf << mm.str();
  2296. }
  2297. this->WriteBuild(ddf, build);
  2298. }
  2299. }
  2300. // Store the map of modules provided by this target in a file for
  2301. // use by dependents that reference this target in linked-target-dirs.
  2302. std::string const target_mods_file = cmStrCat(
  2303. cmSystemTools::GetFilenamePath(arg_dd), '/', arg_lang, "Modules.json");
  2304. cmGeneratedFileStream tmf(target_mods_file);
  2305. tmf << tm;
  2306. return true;
  2307. }
  2308. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  2309. std::vector<std::string>::const_iterator argEnd)
  2310. {
  2311. std::vector<std::string> arg_full =
  2312. cmSystemTools::HandleResponseFile(argBeg, argEnd);
  2313. std::string arg_dd;
  2314. std::string arg_lang;
  2315. std::string arg_tdi;
  2316. std::string arg_modmapfmt;
  2317. std::vector<std::string> arg_ddis;
  2318. for (std::string const& arg : arg_full) {
  2319. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  2320. arg_tdi = arg.substr(6);
  2321. } else if (cmHasLiteralPrefix(arg, "--lang=")) {
  2322. arg_lang = arg.substr(7);
  2323. } else if (cmHasLiteralPrefix(arg, "--dd=")) {
  2324. arg_dd = arg.substr(5);
  2325. } else if (cmHasLiteralPrefix(arg, "--modmapfmt=")) {
  2326. arg_modmapfmt = arg.substr(12);
  2327. } else if (!cmHasLiteralPrefix(arg, "--") &&
  2328. cmHasLiteralSuffix(arg, ".ddi")) {
  2329. arg_ddis.push_back(arg);
  2330. } else {
  2331. cmSystemTools::Error(
  2332. cmStrCat("-E cmake_ninja_dyndep unknown argument: ", arg));
  2333. return 1;
  2334. }
  2335. }
  2336. if (arg_tdi.empty()) {
  2337. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --tdi=");
  2338. return 1;
  2339. }
  2340. if (arg_lang.empty()) {
  2341. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --lang=");
  2342. return 1;
  2343. }
  2344. if (arg_dd.empty()) {
  2345. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --dd=");
  2346. return 1;
  2347. }
  2348. Json::Value tdio;
  2349. Json::Value const& tdi = tdio;
  2350. {
  2351. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  2352. Json::Reader reader;
  2353. if (!reader.parse(tdif, tdio, false)) {
  2354. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2355. arg_tdi,
  2356. reader.getFormattedErrorMessages()));
  2357. return 1;
  2358. }
  2359. }
  2360. std::string const dir_cur_bld = tdi["dir-cur-bld"].asString();
  2361. std::string const dir_cur_src = tdi["dir-cur-src"].asString();
  2362. std::string const dir_top_bld = tdi["dir-top-bld"].asString();
  2363. std::string const dir_top_src = tdi["dir-top-src"].asString();
  2364. std::string module_dir = tdi["module-dir"].asString();
  2365. if (!module_dir.empty() && !cmHasLiteralSuffix(module_dir, "/")) {
  2366. module_dir += '/';
  2367. }
  2368. std::vector<std::string> linked_target_dirs;
  2369. Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
  2370. if (tdi_linked_target_dirs.isArray()) {
  2371. for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) {
  2372. linked_target_dirs.push_back(tdi_linked_target_dir.asString());
  2373. }
  2374. }
  2375. cmake cm(cmake::RoleInternal, cmState::Unknown);
  2376. cm.SetHomeDirectory(dir_top_src);
  2377. cm.SetHomeOutputDirectory(dir_top_bld);
  2378. auto ggd = cm.CreateGlobalGenerator("Ninja");
  2379. if (!ggd ||
  2380. !cm::static_reference_cast<cmGlobalNinjaGenerator>(ggd).WriteDyndepFile(
  2381. dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld, arg_dd, arg_ddis,
  2382. module_dir, linked_target_dirs, arg_lang, arg_modmapfmt)) {
  2383. return 1;
  2384. }
  2385. return 0;
  2386. }
  2387. #endif
  2388. bool cmGlobalNinjaGenerator::EnableCrossConfigBuild() const
  2389. {
  2390. return !this->CrossConfigs.empty();
  2391. }
  2392. void cmGlobalNinjaGenerator::AppendDirectoryForConfig(
  2393. const std::string& prefix, const std::string& config,
  2394. const std::string& suffix, std::string& dir)
  2395. {
  2396. if (!config.empty() && this->IsMultiConfig()) {
  2397. dir += cmStrCat(prefix, config, suffix);
  2398. }
  2399. }
  2400. std::set<std::string> cmGlobalNinjaGenerator::GetCrossConfigs(
  2401. const std::string& fileConfig) const
  2402. {
  2403. auto result = this->CrossConfigs;
  2404. result.insert(fileConfig);
  2405. return result;
  2406. }
  2407. bool cmGlobalNinjaGenerator::IsSingleConfigUtility(
  2408. cmGeneratorTarget const* target) const
  2409. {
  2410. return target->GetType() == cmStateEnums::UTILITY &&
  2411. !this->PerConfigUtilityTargets.count(target->GetName());
  2412. }
  2413. const char* cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE =
  2414. "CMakeFiles/common.ninja";
  2415. const char* cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION = ".ninja";
  2416. cmGlobalNinjaMultiGenerator::cmGlobalNinjaMultiGenerator(cmake* cm)
  2417. : cmGlobalNinjaGenerator(cm)
  2418. {
  2419. cm->GetState()->SetIsGeneratorMultiConfig(true);
  2420. cm->GetState()->SetNinjaMulti(true);
  2421. }
  2422. void cmGlobalNinjaMultiGenerator::GetDocumentation(cmDocumentationEntry& entry)
  2423. {
  2424. entry.Name = cmGlobalNinjaMultiGenerator::GetActualName();
  2425. entry.Brief = "Generates build-<Config>.ninja files.";
  2426. }
  2427. std::string cmGlobalNinjaMultiGenerator::ExpandCFGIntDir(
  2428. const std::string& str, const std::string& config) const
  2429. {
  2430. std::string result = str;
  2431. cmSystemTools::ReplaceString(result, this->GetCMakeCFGIntDir(), config);
  2432. return result;
  2433. }
  2434. bool cmGlobalNinjaMultiGenerator::OpenBuildFileStreams()
  2435. {
  2436. if (!this->OpenFileStream(this->CommonFileStream,
  2437. cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE)) {
  2438. return false;
  2439. }
  2440. if (!this->OpenFileStream(this->DefaultFileStream, NINJA_BUILD_FILE)) {
  2441. return false;
  2442. }
  2443. *this->DefaultFileStream << "# Build using rules for '"
  2444. << this->DefaultFileConfig << "'.\n\n"
  2445. << "include "
  2446. << GetNinjaImplFilename(this->DefaultFileConfig)
  2447. << "\n\n";
  2448. // Write a comment about this file.
  2449. *this->CommonFileStream
  2450. << "# This file contains build statements common to all "
  2451. "configurations.\n\n";
  2452. auto const& configs =
  2453. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2454. return std::all_of(
  2455. configs.begin(), configs.end(), [this](std::string const& config) -> bool {
  2456. // Open impl file.
  2457. if (!this->OpenFileStream(this->ImplFileStreams[config],
  2458. GetNinjaImplFilename(config))) {
  2459. return false;
  2460. }
  2461. // Write a comment about this file.
  2462. *this->ImplFileStreams[config]
  2463. << "# This file contains build statements specific to the \"" << config
  2464. << "\"\n# configuration.\n\n";
  2465. // Open config file.
  2466. if (!this->OpenFileStream(this->ConfigFileStreams[config],
  2467. GetNinjaConfigFilename(config))) {
  2468. return false;
  2469. }
  2470. // Write a comment about this file.
  2471. *this->ConfigFileStreams[config]
  2472. << "# This file contains aliases specific to the \"" << config
  2473. << "\"\n# configuration.\n\n"
  2474. << "include " << GetNinjaImplFilename(config) << "\n\n";
  2475. return true;
  2476. });
  2477. }
  2478. void cmGlobalNinjaMultiGenerator::CloseBuildFileStreams()
  2479. {
  2480. if (this->CommonFileStream) {
  2481. this->CommonFileStream.reset();
  2482. } else {
  2483. cmSystemTools::Error("Common file stream was not open.");
  2484. }
  2485. if (this->DefaultFileStream) {
  2486. this->DefaultFileStream.reset();
  2487. } // No error if it wasn't open
  2488. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  2489. cmMakefile::IncludeEmptyConfig)) {
  2490. if (this->ImplFileStreams[config]) {
  2491. this->ImplFileStreams[config].reset();
  2492. } else {
  2493. cmSystemTools::Error(
  2494. cmStrCat("Impl file stream for \"", config, "\" was not open."));
  2495. }
  2496. if (this->ConfigFileStreams[config]) {
  2497. this->ConfigFileStreams[config].reset();
  2498. } else {
  2499. cmSystemTools::Error(
  2500. cmStrCat("Config file stream for \"", config, "\" was not open."));
  2501. }
  2502. }
  2503. }
  2504. void cmGlobalNinjaMultiGenerator::AppendNinjaFileArgument(
  2505. GeneratedMakeCommand& command, const std::string& config) const
  2506. {
  2507. if (!config.empty()) {
  2508. command.Add("-f");
  2509. command.Add(GetNinjaConfigFilename(config));
  2510. }
  2511. }
  2512. std::string cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(
  2513. const std::string& config)
  2514. {
  2515. return cmStrCat("CMakeFiles/impl-", config,
  2516. cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION);
  2517. }
  2518. std::string cmGlobalNinjaMultiGenerator::GetNinjaConfigFilename(
  2519. const std::string& config)
  2520. {
  2521. return cmStrCat("build-", config,
  2522. cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION);
  2523. }
  2524. void cmGlobalNinjaMultiGenerator::AddRebuildManifestOutputs(
  2525. cmNinjaDeps& outputs) const
  2526. {
  2527. for (auto const& config : this->Makefiles.front()->GetGeneratorConfigs(
  2528. cmMakefile::IncludeEmptyConfig)) {
  2529. outputs.push_back(this->NinjaOutputPath(GetNinjaImplFilename(config)));
  2530. outputs.push_back(this->NinjaOutputPath(GetNinjaConfigFilename(config)));
  2531. }
  2532. if (!this->DefaultFileConfig.empty()) {
  2533. outputs.push_back(this->NinjaOutputPath(NINJA_BUILD_FILE));
  2534. }
  2535. }
  2536. void cmGlobalNinjaMultiGenerator::GetQtAutoGenConfigs(
  2537. std::vector<std::string>& configs) const
  2538. {
  2539. auto allConfigs =
  2540. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2541. configs.insert(configs.end(), cm::cbegin(allConfigs), cm::cend(allConfigs));
  2542. }
  2543. bool cmGlobalNinjaMultiGenerator::InspectConfigTypeVariables()
  2544. {
  2545. std::vector<std::string> configsVec;
  2546. cmExpandList(
  2547. this->Makefiles.front()->GetSafeDefinition("CMAKE_CONFIGURATION_TYPES"),
  2548. configsVec);
  2549. if (configsVec.empty()) {
  2550. configsVec.emplace_back();
  2551. }
  2552. std::set<std::string> configs(configsVec.cbegin(), configsVec.cend());
  2553. this->DefaultFileConfig =
  2554. this->Makefiles.front()->GetSafeDefinition("CMAKE_DEFAULT_BUILD_TYPE");
  2555. if (this->DefaultFileConfig.empty()) {
  2556. this->DefaultFileConfig = configsVec.front();
  2557. }
  2558. if (!configs.count(this->DefaultFileConfig)) {
  2559. std::ostringstream msg;
  2560. msg << "The configuration specified by "
  2561. << "CMAKE_DEFAULT_BUILD_TYPE (" << this->DefaultFileConfig
  2562. << ") is not present in CMAKE_CONFIGURATION_TYPES";
  2563. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2564. msg.str());
  2565. return false;
  2566. }
  2567. std::vector<std::string> crossConfigsVec;
  2568. cmExpandList(
  2569. this->Makefiles.front()->GetSafeDefinition("CMAKE_CROSS_CONFIGS"),
  2570. crossConfigsVec);
  2571. auto crossConfigs = ListSubsetWithAll(configs, configs, crossConfigsVec);
  2572. if (!crossConfigs) {
  2573. std::ostringstream msg;
  2574. msg << "CMAKE_CROSS_CONFIGS is not a subset of "
  2575. << "CMAKE_CONFIGURATION_TYPES";
  2576. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2577. msg.str());
  2578. return false;
  2579. }
  2580. this->CrossConfigs = *crossConfigs;
  2581. auto defaultConfigsString =
  2582. this->Makefiles.front()->GetSafeDefinition("CMAKE_DEFAULT_CONFIGS");
  2583. if (defaultConfigsString.empty()) {
  2584. defaultConfigsString = this->DefaultFileConfig;
  2585. }
  2586. if (!defaultConfigsString.empty() &&
  2587. defaultConfigsString != this->DefaultFileConfig &&
  2588. (this->DefaultFileConfig.empty() || this->CrossConfigs.empty())) {
  2589. std::ostringstream msg;
  2590. msg << "CMAKE_DEFAULT_CONFIGS cannot be used without "
  2591. << "CMAKE_DEFAULT_BUILD_TYPE or CMAKE_CROSS_CONFIGS";
  2592. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2593. msg.str());
  2594. return false;
  2595. }
  2596. std::vector<std::string> defaultConfigsVec;
  2597. cmExpandList(defaultConfigsString, defaultConfigsVec);
  2598. if (!this->DefaultFileConfig.empty()) {
  2599. auto defaultConfigs =
  2600. ListSubsetWithAll(this->GetCrossConfigs(this->DefaultFileConfig),
  2601. this->CrossConfigs, defaultConfigsVec);
  2602. if (!defaultConfigs) {
  2603. std::ostringstream msg;
  2604. msg << "CMAKE_DEFAULT_CONFIGS is not a subset of CMAKE_CROSS_CONFIGS";
  2605. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2606. msg.str());
  2607. return false;
  2608. }
  2609. this->DefaultConfigs = *defaultConfigs;
  2610. }
  2611. return true;
  2612. }
  2613. std::string cmGlobalNinjaMultiGenerator::GetDefaultBuildConfig() const
  2614. {
  2615. return "";
  2616. }
  2617. std::string cmGlobalNinjaMultiGenerator::OrderDependsTargetForTarget(
  2618. cmGeneratorTarget const* target, const std::string& config) const
  2619. {
  2620. return cmStrCat("cmake_object_order_depends_target_", target->GetName(), '_',
  2621. cmSystemTools::UpperCase(config));
  2622. }