cmGlobalNinjaGenerator.cxx 100 KB

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