cmGlobalNinjaGenerator.cxx 114 KB

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