cmGlobalNinjaGenerator.cxx 110 KB

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