cmGlobalNinjaGenerator.cxx 98 KB

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