cmGlobalNinjaGenerator.cxx 103 KB

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