cmGlobalNinjaGenerator.cxx 110 KB

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