cmGlobalNinjaGenerator.cxx 89 KB

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