cmGlobalNinjaGenerator.cxx 89 KB

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