cmGlobalNinjaGenerator.cxx 86 KB

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