cmGlobalNinjaGenerator.cxx 104 KB

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