cmGlobalNinjaGenerator.cxx 100 KB

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