cmGlobalNinjaGenerator.cxx 99 KB

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