cmGlobalNinjaGenerator.cxx 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161
  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. std::string val;
  458. static std::unordered_set<std::string> const variablesShouldNotBeTrimmed = {
  459. "CODE_CHECK", "LAUNCHER"
  460. };
  461. if (variablesShouldNotBeTrimmed.find(name) ==
  462. variablesShouldNotBeTrimmed.end()) {
  463. val = cmTrimWhitespace(value);
  464. } else {
  465. val = value;
  466. }
  467. // Do not add a variable if the value is empty.
  468. if (val.empty()) {
  469. return;
  470. }
  471. cmGlobalNinjaGenerator::WriteComment(os, comment);
  472. cmGlobalNinjaGenerator::Indent(os, indent);
  473. os << name << " = " << val << "\n";
  474. }
  475. void cmGlobalNinjaGenerator::WriteInclude(std::ostream& os,
  476. const std::string& filename,
  477. const std::string& comment)
  478. {
  479. cmGlobalNinjaGenerator::WriteComment(os, comment);
  480. os << "include " << filename << "\n";
  481. }
  482. void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
  483. const cmNinjaDeps& targets,
  484. const std::string& comment)
  485. {
  486. cmGlobalNinjaGenerator::WriteComment(os, comment);
  487. os << "default";
  488. for (std::string const& target : targets) {
  489. os << " " << target;
  490. }
  491. os << "\n";
  492. }
  493. cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm)
  494. : cmGlobalCommonGenerator(cm)
  495. {
  496. #ifdef _WIN32
  497. cm->GetState()->SetWindowsShell(true);
  498. #endif
  499. this->FindMakeProgramFile = "CMakeNinjaFindMake.cmake";
  500. }
  501. // Virtual public methods.
  502. std::unique_ptr<cmLocalGenerator> cmGlobalNinjaGenerator::CreateLocalGenerator(
  503. cmMakefile* mf)
  504. {
  505. return std::unique_ptr<cmLocalGenerator>(
  506. cm::make_unique<cmLocalNinjaGenerator>(this, mf));
  507. }
  508. codecvt_Encoding cmGlobalNinjaGenerator::GetMakefileEncoding() const
  509. {
  510. return this->NinjaExpectedEncoding;
  511. }
  512. cmDocumentationEntry cmGlobalNinjaGenerator::GetDocumentation()
  513. {
  514. return { cmGlobalNinjaGenerator::GetActualName(),
  515. "Generates build.ninja files." };
  516. }
  517. // Implemented in all cmGlobaleGenerator sub-classes.
  518. // Used in:
  519. // Source/cmLocalGenerator.cxx
  520. // Source/cmake.cxx
  521. void cmGlobalNinjaGenerator::Generate()
  522. {
  523. // Check minimum Ninja version.
  524. if (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  525. RequiredNinjaVersion())) {
  526. std::ostringstream msg;
  527. msg << "The detected version of Ninja (" << this->NinjaVersion;
  528. msg << ") is less than the version of Ninja required by CMake (";
  529. msg << cmGlobalNinjaGenerator::RequiredNinjaVersion() << ").";
  530. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  531. msg.str());
  532. return;
  533. }
  534. this->InitOutputPathPrefix();
  535. if (!this->OpenBuildFileStreams()) {
  536. return;
  537. }
  538. if (!this->OpenRulesFileStream()) {
  539. return;
  540. }
  541. for (auto& it : this->Configs) {
  542. it.second.TargetDependsClosures.clear();
  543. }
  544. this->TargetAll = this->NinjaOutputPath("all");
  545. this->CMakeCacheFile = this->NinjaOutputPath("CMakeCache.txt");
  546. this->DiagnosedCxxModuleNinjaSupport = false;
  547. this->ClangTidyExportFixesDirs.clear();
  548. this->ClangTidyExportFixesFiles.clear();
  549. this->PolicyCMP0058 =
  550. this->LocalGenerators[0]->GetMakefile()->GetPolicyStatus(
  551. cmPolicies::CMP0058);
  552. this->ComputingUnknownDependencies =
  553. (this->PolicyCMP0058 == cmPolicies::OLD ||
  554. this->PolicyCMP0058 == cmPolicies::WARN);
  555. this->cmGlobalGenerator::Generate();
  556. this->WriteAssumedSourceDependencies();
  557. this->WriteTargetAliases(*this->GetCommonFileStream());
  558. this->WriteFolderTargets(*this->GetCommonFileStream());
  559. this->WriteUnknownExplicitDependencies(*this->GetCommonFileStream());
  560. this->WriteBuiltinTargets(*this->GetCommonFileStream());
  561. if (cmSystemTools::GetErrorOccurredFlag()) {
  562. this->RulesFileStream->setstate(std::ios::failbit);
  563. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  564. cmMakefile::IncludeEmptyConfig)) {
  565. this->GetImplFileStream(config)->setstate(std::ios::failbit);
  566. this->GetConfigFileStream(config)->setstate(std::ios::failbit);
  567. }
  568. this->GetCommonFileStream()->setstate(std::ios::failbit);
  569. }
  570. this->CloseCompileCommandsStream();
  571. this->CloseRulesFileStream();
  572. this->CloseBuildFileStreams();
  573. #ifdef _WIN32
  574. // Older ninja tools will not be able to update metadata on Windows
  575. // when we are re-generating inside an existing 'ninja' invocation
  576. // because the outer tool has the files open for write.
  577. if (this->NinjaSupportsMetadataOnRegeneration ||
  578. !this->GetCMakeInstance()->GetRegenerateDuringBuild())
  579. #endif
  580. {
  581. this->CleanMetaData();
  582. }
  583. this->RemoveUnknownClangTidyExportFixesFiles();
  584. }
  585. void cmGlobalNinjaGenerator::CleanMetaData()
  586. {
  587. auto run_ninja_tool = [this](std::vector<char const*> const& args) {
  588. std::vector<std::string> command;
  589. command.push_back(this->NinjaCommand);
  590. command.emplace_back("-C");
  591. command.emplace_back(this->GetCMakeInstance()->GetHomeOutputDirectory());
  592. command.emplace_back("-t");
  593. for (auto const& arg : args) {
  594. command.emplace_back(arg);
  595. }
  596. std::string error;
  597. if (!cmSystemTools::RunSingleCommand(command, nullptr, &error, nullptr,
  598. nullptr,
  599. cmSystemTools::OUTPUT_NONE)) {
  600. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  601. cmStrCat("Running\n '",
  602. cmJoin(command, "' '"),
  603. "'\n"
  604. "failed with:\n ",
  605. error));
  606. cmSystemTools::SetFatalErrorOccurred();
  607. }
  608. };
  609. // Can the tools below expect 'build.ninja' to be loadable?
  610. bool const expectBuildManifest =
  611. !this->IsMultiConfig() && this->OutputPathPrefix.empty();
  612. // Skip some ninja tools if they need 'build.ninja' but it is missing.
  613. bool const missingBuildManifest = expectBuildManifest &&
  614. this->NinjaSupportsUnconditionalRecompactTool &&
  615. !cmSystemTools::FileExists("build.ninja");
  616. // The `recompact` tool loads the manifest. As above, we don't have a single
  617. // `build.ninja` to load for this in Ninja-Multi. This may be relaxed in the
  618. // future pending further investigation into how Ninja works upstream
  619. // (ninja#1721).
  620. if (this->NinjaSupportsUnconditionalRecompactTool &&
  621. !this->GetCMakeInstance()->GetRegenerateDuringBuild() &&
  622. expectBuildManifest && !missingBuildManifest) {
  623. run_ninja_tool({ "recompact" });
  624. }
  625. if (this->NinjaSupportsRestatTool && this->OutputPathPrefix.empty()) {
  626. // XXX(ninja): We only list `build.ninja` entry files here because CMake
  627. // *always* rewrites these files on a reconfigure. If CMake ever gets
  628. // smarter about this, all CMake-time created/edited files listed as
  629. // outputs for the reconfigure build statement will need to be listed here.
  630. cmNinjaDeps outputs;
  631. this->AddRebuildManifestOutputs(outputs);
  632. std::vector<const char*> args;
  633. args.reserve(outputs.size() + 1);
  634. args.push_back("restat");
  635. for (auto const& output : outputs) {
  636. args.push_back(output.c_str());
  637. }
  638. run_ninja_tool(args);
  639. }
  640. }
  641. bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
  642. {
  643. if (!this->cmGlobalGenerator::FindMakeProgram(mf)) {
  644. return false;
  645. }
  646. if (cmValue ninjaCommand = mf->GetDefinition("CMAKE_MAKE_PROGRAM")) {
  647. this->NinjaCommand = *ninjaCommand;
  648. std::vector<std::string> command;
  649. command.push_back(this->NinjaCommand);
  650. command.emplace_back("--version");
  651. std::string version;
  652. std::string error;
  653. if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr,
  654. nullptr,
  655. cmSystemTools::OUTPUT_NONE)) {
  656. mf->IssueMessage(MessageType::FATAL_ERROR,
  657. cmStrCat("Running\n '", cmJoin(command, "' '"),
  658. "'\n"
  659. "failed with:\n ",
  660. error));
  661. cmSystemTools::SetFatalErrorOccurred();
  662. return false;
  663. }
  664. this->NinjaVersion = cmTrimWhitespace(version);
  665. this->CheckNinjaFeatures();
  666. }
  667. return true;
  668. }
  669. void cmGlobalNinjaGenerator::CheckNinjaFeatures()
  670. {
  671. this->NinjaSupportsConsolePool =
  672. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  673. RequiredNinjaVersionForConsolePool());
  674. this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare(
  675. cmSystemTools::OP_LESS, this->NinjaVersion,
  676. cmGlobalNinjaGenerator::RequiredNinjaVersionForImplicitOuts());
  677. this->NinjaSupportsManifestRestat =
  678. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  679. RequiredNinjaVersionForManifestRestat());
  680. this->NinjaSupportsMultilineDepfile =
  681. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  682. RequiredNinjaVersionForMultilineDepfile());
  683. this->NinjaSupportsDyndepsCxx =
  684. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  685. RequiredNinjaVersionForDyndepsCxx());
  686. this->NinjaSupportsDyndepsFortran =
  687. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  688. RequiredNinjaVersionForDyndepsFortran());
  689. if (!this->NinjaSupportsDyndepsFortran) {
  690. // The ninja version number is not new enough to have upstream support.
  691. // Our ninja branch adds ".dyndep-#" to its version number,
  692. // where '#' is a feature-specific version number. Extract it.
  693. static std::string const k_DYNDEP_ = ".dyndep-";
  694. std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_);
  695. if (pos != std::string::npos) {
  696. const char* fv = &this->NinjaVersion[pos + k_DYNDEP_.size()];
  697. unsigned long dyndep = 0;
  698. cmStrToULong(fv, &dyndep);
  699. if (dyndep == 1) {
  700. this->NinjaSupportsDyndepsFortran = true;
  701. }
  702. }
  703. }
  704. this->NinjaSupportsUnconditionalRecompactTool =
  705. !cmSystemTools::VersionCompare(
  706. cmSystemTools::OP_LESS, this->NinjaVersion,
  707. RequiredNinjaVersionForUnconditionalRecompactTool());
  708. this->NinjaSupportsRestatTool =
  709. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  710. RequiredNinjaVersionForRestatTool());
  711. this->NinjaSupportsMultipleOutputs =
  712. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  713. RequiredNinjaVersionForMultipleOutputs());
  714. this->NinjaSupportsMetadataOnRegeneration = !cmSystemTools::VersionCompare(
  715. cmSystemTools::OP_LESS, this->NinjaVersion,
  716. RequiredNinjaVersionForMetadataOnRegeneration());
  717. #ifdef _WIN32
  718. this->NinjaSupportsCodePage =
  719. !cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion,
  720. RequiredNinjaVersionForCodePage());
  721. if (this->NinjaSupportsCodePage) {
  722. this->CheckNinjaCodePage();
  723. } else {
  724. this->NinjaExpectedEncoding = codecvt_Encoding::ANSI;
  725. }
  726. #endif
  727. }
  728. void cmGlobalNinjaGenerator::CheckNinjaCodePage()
  729. {
  730. std::vector<std::string> command{ this->NinjaCommand, "-t", "wincodepage" };
  731. std::string output;
  732. std::string error;
  733. int result;
  734. if (!cmSystemTools::RunSingleCommand(command, &output, &error, &result,
  735. nullptr, cmSystemTools::OUTPUT_NONE)) {
  736. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  737. cmStrCat("Running\n '",
  738. cmJoin(command, "' '"),
  739. "'\n"
  740. "failed with:\n ",
  741. error));
  742. cmSystemTools::SetFatalErrorOccurred();
  743. } else if (result == 0) {
  744. std::istringstream outputStream(output);
  745. std::string line;
  746. bool found = false;
  747. while (cmSystemTools::GetLineFromStream(outputStream, line)) {
  748. if (cmHasLiteralPrefix(line, "Build file encoding: ")) {
  749. cm::string_view lineView(line);
  750. cm::string_view encoding =
  751. lineView.substr(cmStrLen("Build file encoding: "));
  752. if (encoding == "UTF-8") {
  753. // Ninja expects UTF-8. We use that internally. No conversion needed.
  754. this->NinjaExpectedEncoding = codecvt_Encoding::None;
  755. } else {
  756. this->NinjaExpectedEncoding = codecvt_Encoding::ANSI;
  757. }
  758. found = true;
  759. break;
  760. }
  761. }
  762. if (!found) {
  763. this->GetCMakeInstance()->IssueMessage(
  764. MessageType::WARNING,
  765. "Could not determine Ninja's code page, defaulting to UTF-8");
  766. this->NinjaExpectedEncoding = codecvt_Encoding::None;
  767. }
  768. } else {
  769. this->NinjaExpectedEncoding = codecvt_Encoding::ANSI;
  770. }
  771. }
  772. bool cmGlobalNinjaGenerator::CheckLanguages(
  773. std::vector<std::string> const& languages, cmMakefile* mf) const
  774. {
  775. if (cm::contains(languages, "Fortran")) {
  776. return this->CheckFortran(mf);
  777. }
  778. if (cm::contains(languages, "ISPC")) {
  779. return this->CheckISPC(mf);
  780. }
  781. if (cm::contains(languages, "Swift")) {
  782. const std::string architectures =
  783. mf->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  784. if (architectures.find_first_of(';') != std::string::npos) {
  785. mf->IssueMessage(MessageType::FATAL_ERROR,
  786. "multiple values for CMAKE_OSX_ARCHITECTURES not "
  787. "supported with Swift");
  788. cmSystemTools::SetFatalErrorOccurred();
  789. return false;
  790. }
  791. }
  792. return true;
  793. }
  794. bool cmGlobalNinjaGenerator::CheckCxxModuleSupport()
  795. {
  796. if (this->NinjaSupportsDyndepsCxx) {
  797. return true;
  798. }
  799. bool const diagnose = !this->DiagnosedCxxModuleNinjaSupport &&
  800. !this->CMakeInstance->GetIsInTryCompile();
  801. if (diagnose) {
  802. std::ostringstream e;
  803. /* clang-format off */
  804. e <<
  805. "The Ninja generator does not support C++20 modules "
  806. "using Ninja version \n"
  807. " " << this->NinjaVersion << "\n"
  808. "due to lack of required features. "
  809. "Ninja " << RequiredNinjaVersionForDyndepsCxx() <<
  810. " or higher is required."
  811. ;
  812. /* clang-format on */
  813. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str());
  814. cmSystemTools::SetFatalErrorOccurred();
  815. }
  816. return false;
  817. }
  818. bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const
  819. {
  820. if (this->NinjaSupportsDyndepsFortran) {
  821. return true;
  822. }
  823. std::ostringstream e;
  824. /* clang-format off */
  825. e <<
  826. "The Ninja generator does not support Fortran using Ninja version\n"
  827. " " << this->NinjaVersion << "\n"
  828. "due to lack of required features. "
  829. "Ninja " << RequiredNinjaVersionForDyndepsFortran() <<
  830. " or higher is required."
  831. ;
  832. /* clang-format on */
  833. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  834. cmSystemTools::SetFatalErrorOccurred();
  835. return false;
  836. }
  837. bool cmGlobalNinjaGenerator::CheckISPC(cmMakefile* mf) const
  838. {
  839. if (this->NinjaSupportsMultipleOutputs) {
  840. return true;
  841. }
  842. std::ostringstream e;
  843. /* clang-format off */
  844. e <<
  845. "The Ninja generator does not support ISPC using Ninja version\n"
  846. " " << this->NinjaVersion << "\n"
  847. "due to lack of required features. "
  848. "Ninja " << RequiredNinjaVersionForMultipleOutputs() <<
  849. " or higher is required."
  850. ;
  851. /* clang-format on */
  852. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  853. cmSystemTools::SetFatalErrorOccurred();
  854. return false;
  855. }
  856. void cmGlobalNinjaGenerator::EnableLanguage(
  857. std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
  858. {
  859. if (this->IsMultiConfig()) {
  860. mf->InitCMAKE_CONFIGURATION_TYPES("Debug;Release;RelWithDebInfo");
  861. }
  862. this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
  863. for (std::string const& l : langs) {
  864. if (l == "NONE") {
  865. continue;
  866. }
  867. this->ResolveLanguageCompiler(l, mf, optional);
  868. #ifdef _WIN32
  869. std::string const& compilerId =
  870. mf->GetSafeDefinition(cmStrCat("CMAKE_", l, "_COMPILER_ID"));
  871. std::string const& simulateId =
  872. mf->GetSafeDefinition(cmStrCat("CMAKE_", l, "_SIMULATE_ID"));
  873. std::string const& compilerFrontendVariant = mf->GetSafeDefinition(
  874. cmStrCat("CMAKE_", l, "_COMPILER_FRONTEND_VARIANT"));
  875. if (DetectGCCOnWindows(compilerId, simulateId, compilerFrontendVariant)) {
  876. this->MarkAsGCCOnWindows();
  877. }
  878. #endif
  879. }
  880. }
  881. // Implemented by:
  882. // cmGlobalUnixMakefileGenerator3
  883. // cmGlobalGhsMultiGenerator
  884. // cmGlobalVisualStudio10Generator
  885. // cmGlobalVisualStudio7Generator
  886. // cmGlobalXCodeGenerator
  887. // Called by:
  888. // cmGlobalGenerator::Build()
  889. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  890. cmGlobalNinjaGenerator::GenerateBuildCommand(
  891. const std::string& makeProgram, const std::string& /*projectName*/,
  892. const std::string& /*projectDir*/,
  893. std::vector<std::string> const& targetNames, const std::string& config,
  894. int jobs, bool verbose, const cmBuildOptions& /*buildOptions*/,
  895. std::vector<std::string> const& makeOptions)
  896. {
  897. GeneratedMakeCommand makeCommand;
  898. makeCommand.Add(this->SelectMakeProgram(makeProgram));
  899. if (verbose) {
  900. makeCommand.Add("-v");
  901. }
  902. if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
  903. (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
  904. makeCommand.Add("-j", std::to_string(jobs));
  905. }
  906. this->AppendNinjaFileArgument(makeCommand, config);
  907. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  908. for (const auto& tname : targetNames) {
  909. if (!tname.empty()) {
  910. makeCommand.Add(tname);
  911. }
  912. }
  913. return { std::move(makeCommand) };
  914. }
  915. // Non-virtual public methods.
  916. void cmGlobalNinjaGenerator::AddRule(cmNinjaRule const& rule)
  917. {
  918. // Do not add the same rule twice.
  919. if (!this->Rules.insert(rule.Name).second) {
  920. return;
  921. }
  922. // Store command length
  923. this->RuleCmdLength[rule.Name] = static_cast<int>(rule.Command.size());
  924. // Write rule
  925. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream, rule);
  926. }
  927. bool cmGlobalNinjaGenerator::HasRule(const std::string& name)
  928. {
  929. return (this->Rules.find(name) != this->Rules.end());
  930. }
  931. // Private virtual overrides
  932. void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory(
  933. cmGeneratorTarget* gt) const
  934. {
  935. // Compute full path to object file directory for this target.
  936. std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
  937. '/', gt->LocalGenerator->GetTargetDirectory(gt),
  938. '/', this->GetCMakeCFGIntDir(), '/');
  939. gt->ObjectDirectory = dir;
  940. }
  941. // Private methods
  942. bool cmGlobalNinjaGenerator::OpenBuildFileStreams()
  943. {
  944. if (!this->OpenFileStream(this->BuildFileStream,
  945. cmGlobalNinjaGenerator::NINJA_BUILD_FILE)) {
  946. return false;
  947. }
  948. // Write a comment about this file.
  949. *this->BuildFileStream
  950. << "# This file contains all the build statements describing the\n"
  951. << "# compilation DAG.\n\n";
  952. return true;
  953. }
  954. bool cmGlobalNinjaGenerator::OpenFileStream(
  955. std::unique_ptr<cmGeneratedFileStream>& stream, const std::string& name)
  956. {
  957. // Get a stream where to generate things.
  958. if (!stream) {
  959. // Compute Ninja's build file path.
  960. std::string path =
  961. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), '/', name);
  962. stream = cm::make_unique<cmGeneratedFileStream>(
  963. path, false, this->GetMakefileEncoding());
  964. if (!(*stream)) {
  965. // An error message is generated by the constructor if it cannot
  966. // open the file.
  967. return false;
  968. }
  969. // Write the do not edit header.
  970. this->WriteDisclaimer(*stream);
  971. }
  972. return true;
  973. }
  974. cm::optional<std::set<std::string>> cmGlobalNinjaGenerator::ListSubsetWithAll(
  975. const std::set<std::string>& all, const std::set<std::string>& defaults,
  976. const std::vector<std::string>& items)
  977. {
  978. std::set<std::string> result;
  979. for (auto const& item : items) {
  980. if (item == "all") {
  981. if (items.size() == 1) {
  982. result = defaults;
  983. } else {
  984. return cm::nullopt;
  985. }
  986. } else if (all.count(item)) {
  987. result.insert(item);
  988. } else {
  989. return cm::nullopt;
  990. }
  991. }
  992. return cm::make_optional(result);
  993. }
  994. void cmGlobalNinjaGenerator::CloseBuildFileStreams()
  995. {
  996. if (this->BuildFileStream) {
  997. this->BuildFileStream.reset();
  998. } else {
  999. cmSystemTools::Error("Build file stream was not open.");
  1000. }
  1001. }
  1002. bool cmGlobalNinjaGenerator::OpenRulesFileStream()
  1003. {
  1004. if (!this->OpenFileStream(this->RulesFileStream,
  1005. cmGlobalNinjaGenerator::NINJA_RULES_FILE)) {
  1006. return false;
  1007. }
  1008. // Write comment about this file.
  1009. /* clang-format off */
  1010. *this->RulesFileStream
  1011. << "# This file contains all the rules used to get the outputs files\n"
  1012. << "# built from the input files.\n"
  1013. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  1014. ;
  1015. /* clang-format on */
  1016. return true;
  1017. }
  1018. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  1019. {
  1020. if (this->RulesFileStream) {
  1021. this->RulesFileStream.reset();
  1022. } else {
  1023. cmSystemTools::Error("Rules file stream was not open.");
  1024. }
  1025. }
  1026. static void EnsureTrailingSlash(std::string& path)
  1027. {
  1028. if (path.empty()) {
  1029. return;
  1030. }
  1031. std::string::value_type last = path.back();
  1032. #ifdef _WIN32
  1033. if (last != '\\') {
  1034. path += '\\';
  1035. }
  1036. #else
  1037. if (last != '/') {
  1038. path += '/';
  1039. }
  1040. #endif
  1041. }
  1042. std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath(
  1043. const std::string& path) const
  1044. {
  1045. auto const f = this->ConvertToNinjaPathCache.find(path);
  1046. if (f != this->ConvertToNinjaPathCache.end()) {
  1047. return f->second;
  1048. }
  1049. std::string convPath =
  1050. this->LocalGenerators[0]->MaybeRelativeToTopBinDir(path);
  1051. convPath = this->NinjaOutputPath(convPath);
  1052. #ifdef _WIN32
  1053. std::replace(convPath.begin(), convPath.end(), '/', '\\');
  1054. #endif
  1055. return this->ConvertToNinjaPathCache.emplace(path, std::move(convPath))
  1056. .first->second;
  1057. }
  1058. std::string cmGlobalNinjaGenerator::ConvertToNinjaAbsPath(
  1059. std::string path) const
  1060. {
  1061. #ifdef _WIN32
  1062. std::replace(path.begin(), path.end(), '/', '\\');
  1063. #endif
  1064. return path;
  1065. }
  1066. void cmGlobalNinjaGenerator::AddAdditionalCleanFile(std::string fileName,
  1067. const std::string& config)
  1068. {
  1069. this->Configs[config].AdditionalCleanFiles.emplace(std::move(fileName));
  1070. }
  1071. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  1072. const std::string& commandLine, const std::string& sourceFile,
  1073. const std::string& objPath)
  1074. {
  1075. // Compute Ninja's build file path.
  1076. std::string buildFileDir =
  1077. this->GetCMakeInstance()->GetHomeOutputDirectory();
  1078. if (!this->CompileCommandsStream) {
  1079. std::string buildFilePath =
  1080. cmStrCat(buildFileDir, "/compile_commands.json");
  1081. if (this->ComputingUnknownDependencies) {
  1082. this->CombinedBuildOutputs.insert(
  1083. this->NinjaOutputPath("compile_commands.json"));
  1084. }
  1085. // Get a stream where to generate things.
  1086. this->CompileCommandsStream =
  1087. cm::make_unique<cmGeneratedFileStream>(buildFilePath);
  1088. *this->CompileCommandsStream << "[\n";
  1089. } else {
  1090. *this->CompileCommandsStream << ",\n";
  1091. }
  1092. std::string sourceFileName = sourceFile;
  1093. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1094. sourceFileName = cmSystemTools::CollapseFullPath(
  1095. sourceFileName, this->GetCMakeInstance()->GetHomeOutputDirectory());
  1096. }
  1097. /* clang-format off */
  1098. *this->CompileCommandsStream << "{\n"
  1099. << R"( "directory": ")"
  1100. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  1101. << R"( "command": ")"
  1102. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  1103. << R"( "file": ")"
  1104. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\",\n"
  1105. << R"( "output": ")"
  1106. << cmGlobalGenerator::EscapeJSON(objPath) << "\"\n"
  1107. << "}";
  1108. /* clang-format on */
  1109. }
  1110. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  1111. {
  1112. if (this->CompileCommandsStream) {
  1113. *this->CompileCommandsStream << "\n]";
  1114. this->CompileCommandsStream.reset();
  1115. }
  1116. }
  1117. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os) const
  1118. {
  1119. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1120. << "# Generated by \"" << this->GetName() << "\""
  1121. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1122. << cmVersion::GetMinorVersion() << "\n\n";
  1123. }
  1124. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  1125. {
  1126. for (auto const& asd : this->AssumedSourceDependencies) {
  1127. CCOutputs outputs(this);
  1128. outputs.ExplicitOuts.emplace_back(asd.first);
  1129. cmNinjaDeps orderOnlyDeps;
  1130. std::copy(asd.second.begin(), asd.second.end(),
  1131. std::back_inserter(orderOnlyDeps));
  1132. this->WriteCustomCommandBuild(
  1133. /*command=*/"", /*description=*/"",
  1134. "Assume dependencies for generated source file.",
  1135. /*depfile*/ "", /*job_pool*/ "",
  1136. /*uses_terminal*/ false,
  1137. /*restat*/ true, std::string(), outputs, cmNinjaDeps(),
  1138. std::move(orderOnlyDeps));
  1139. }
  1140. }
  1141. std::string cmGlobalNinjaGenerator::OrderDependsTargetForTarget(
  1142. cmGeneratorTarget const* target, const std::string& /*config*/) const
  1143. {
  1144. return cmStrCat("cmake_object_order_depends_target_", target->GetName());
  1145. }
  1146. void cmGlobalNinjaGenerator::AppendTargetOutputs(
  1147. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1148. const std::string& config, cmNinjaTargetDepends depends) const
  1149. {
  1150. // for frameworks, we want the real name, not sample name
  1151. // frameworks always appear versioned, and the build.ninja
  1152. // will always attempt to manage symbolic links instead
  1153. // of letting cmOSXBundleGenerator do it.
  1154. bool realname = target->IsFrameworkOnApple();
  1155. switch (target->GetType()) {
  1156. case cmStateEnums::SHARED_LIBRARY:
  1157. case cmStateEnums::STATIC_LIBRARY:
  1158. case cmStateEnums::MODULE_LIBRARY: {
  1159. if (depends == DependOnTargetOrdering) {
  1160. outputs.push_back(this->OrderDependsTargetForTarget(target, config));
  1161. break;
  1162. }
  1163. }
  1164. CM_FALLTHROUGH;
  1165. case cmStateEnums::EXECUTABLE: {
  1166. if (target->IsApple() && target->HasImportLibrary(config)) {
  1167. outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath(
  1168. config, cmStateEnums::ImportLibraryArtifact, realname)));
  1169. }
  1170. outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath(
  1171. config, cmStateEnums::RuntimeBinaryArtifact, realname)));
  1172. break;
  1173. }
  1174. case cmStateEnums::OBJECT_LIBRARY: {
  1175. if (depends == DependOnTargetOrdering) {
  1176. outputs.push_back(this->OrderDependsTargetForTarget(target, config));
  1177. break;
  1178. }
  1179. }
  1180. CM_FALLTHROUGH;
  1181. case cmStateEnums::GLOBAL_TARGET:
  1182. case cmStateEnums::INTERFACE_LIBRARY:
  1183. case cmStateEnums::UTILITY: {
  1184. std::string path =
  1185. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/',
  1186. target->GetName());
  1187. std::string output = this->ConvertToNinjaPath(path);
  1188. if (target->Target->IsPerConfig()) {
  1189. output = this->BuildAlias(output, config);
  1190. }
  1191. outputs.push_back(output);
  1192. break;
  1193. }
  1194. case cmStateEnums::UNKNOWN_LIBRARY:
  1195. break;
  1196. }
  1197. }
  1198. void cmGlobalNinjaGenerator::AppendTargetDepends(
  1199. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1200. const std::string& config, const std::string& fileConfig,
  1201. cmNinjaTargetDepends depends)
  1202. {
  1203. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1204. // These depend only on other CMake-provided targets, e.g. "all".
  1205. for (BT<std::pair<std::string, bool>> const& util :
  1206. target->GetUtilities()) {
  1207. std::string d =
  1208. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/',
  1209. util.Value.first);
  1210. outputs.push_back(this->BuildAlias(this->ConvertToNinjaPath(d), config));
  1211. }
  1212. } else {
  1213. cmNinjaDeps outs;
  1214. auto computeISPCOuputs = [](cmGlobalNinjaGenerator* gg,
  1215. cmGeneratorTarget const* depTarget,
  1216. cmNinjaDeps& outputDeps,
  1217. const std::string& targetConfig) {
  1218. if (depTarget->CanCompileSources()) {
  1219. auto headers = depTarget->GetGeneratedISPCHeaders(targetConfig);
  1220. if (!headers.empty()) {
  1221. std::transform(headers.begin(), headers.end(), headers.begin(),
  1222. gg->MapToNinjaPath());
  1223. outputDeps.insert(outputDeps.end(), headers.begin(), headers.end());
  1224. }
  1225. auto objs = depTarget->GetGeneratedISPCObjects(targetConfig);
  1226. if (!objs.empty()) {
  1227. std::transform(objs.begin(), objs.end(), objs.begin(),
  1228. gg->MapToNinjaPath());
  1229. outputDeps.insert(outputDeps.end(), objs.begin(), objs.end());
  1230. }
  1231. }
  1232. };
  1233. for (cmTargetDepend const& targetDep :
  1234. this->GetTargetDirectDepends(target)) {
  1235. if (!targetDep->IsInBuildSystem()) {
  1236. continue;
  1237. }
  1238. if (targetDep.IsCross()) {
  1239. this->AppendTargetOutputs(targetDep, outs, fileConfig, depends);
  1240. computeISPCOuputs(this, targetDep, outs, fileConfig);
  1241. } else {
  1242. this->AppendTargetOutputs(targetDep, outs, config, depends);
  1243. computeISPCOuputs(this, targetDep, outs, config);
  1244. }
  1245. }
  1246. std::sort(outs.begin(), outs.end());
  1247. cm::append(outputs, outs);
  1248. }
  1249. }
  1250. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  1251. cmGeneratorTarget const* target, std::unordered_set<std::string>& outputs,
  1252. const std::string& config, const std::string& fileConfig, bool genexOutput,
  1253. bool omit_self)
  1254. {
  1255. // try to locate the target in the cache
  1256. ByConfig::TargetDependsClosureKey key{
  1257. target,
  1258. config,
  1259. genexOutput,
  1260. };
  1261. auto find = this->Configs[fileConfig].TargetDependsClosures.lower_bound(key);
  1262. if (find == this->Configs[fileConfig].TargetDependsClosures.end() ||
  1263. find->first != key) {
  1264. // We now calculate the closure outputs by inspecting the dependent
  1265. // targets recursively.
  1266. // For that we have to distinguish between a local result set that is only
  1267. // relevant for filling the cache entries properly isolated and a global
  1268. // result set that is relevant for the result of the top level call to
  1269. // AppendTargetDependsClosure.
  1270. std::unordered_set<std::string>
  1271. this_outs; // this will be the new cache entry
  1272. for (auto const& dep_target : this->GetTargetDirectDepends(target)) {
  1273. if (!dep_target->IsInBuildSystem()) {
  1274. continue;
  1275. }
  1276. if (!this->IsSingleConfigUtility(target) &&
  1277. !this->IsSingleConfigUtility(dep_target) &&
  1278. this->EnableCrossConfigBuild() && !dep_target.IsCross() &&
  1279. !genexOutput) {
  1280. continue;
  1281. }
  1282. if (dep_target.IsCross()) {
  1283. this->AppendTargetDependsClosure(dep_target, this_outs, fileConfig,
  1284. fileConfig, genexOutput, false);
  1285. } else {
  1286. this->AppendTargetDependsClosure(dep_target, this_outs, config,
  1287. fileConfig, genexOutput, false);
  1288. }
  1289. }
  1290. find = this->Configs[fileConfig].TargetDependsClosures.emplace_hint(
  1291. find, key, std::move(this_outs));
  1292. }
  1293. // now fill the outputs of the final result from the newly generated cache
  1294. // entry
  1295. outputs.insert(find->second.begin(), find->second.end());
  1296. // finally generate the outputs of the target itself, if applicable
  1297. cmNinjaDeps outs;
  1298. if (!omit_self) {
  1299. this->AppendTargetOutputs(target, outs, config, DependOnTargetArtifact);
  1300. }
  1301. outputs.insert(outs.begin(), outs.end());
  1302. }
  1303. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  1304. cmGeneratorTarget* target,
  1305. const std::string& config)
  1306. {
  1307. std::string outputPath = this->NinjaOutputPath(alias);
  1308. std::string buildAlias = this->BuildAlias(outputPath, config);
  1309. cmNinjaDeps outputs;
  1310. if (config != "all") {
  1311. this->AppendTargetOutputs(target, outputs, config, DependOnTargetArtifact);
  1312. }
  1313. // Mark the target's outputs as ambiguous to ensure that no other target
  1314. // uses the output as an alias.
  1315. for (std::string const& output : outputs) {
  1316. this->TargetAliases[output].GeneratorTarget = nullptr;
  1317. this->DefaultTargetAliases[output].GeneratorTarget = nullptr;
  1318. for (const std::string& config2 :
  1319. this->Makefiles.front()->GetGeneratorConfigs(
  1320. cmMakefile::IncludeEmptyConfig)) {
  1321. this->Configs[config2].TargetAliases[output].GeneratorTarget = nullptr;
  1322. }
  1323. }
  1324. // Insert the alias into the map. If the alias was already present in the
  1325. // map and referred to another target, mark it as ambiguous.
  1326. TargetAlias ta;
  1327. ta.GeneratorTarget = target;
  1328. ta.Config = config;
  1329. auto newAliasGlobal =
  1330. this->TargetAliases.insert(std::make_pair(buildAlias, ta));
  1331. if (newAliasGlobal.second &&
  1332. newAliasGlobal.first->second.GeneratorTarget != target) {
  1333. newAliasGlobal.first->second.GeneratorTarget = nullptr;
  1334. }
  1335. auto newAliasConfig =
  1336. this->Configs[config].TargetAliases.insert(std::make_pair(outputPath, ta));
  1337. if (newAliasConfig.second &&
  1338. newAliasConfig.first->second.GeneratorTarget != target) {
  1339. newAliasConfig.first->second.GeneratorTarget = nullptr;
  1340. }
  1341. if (this->DefaultConfigs.count(config)) {
  1342. auto newAliasDefaultGlobal =
  1343. this->DefaultTargetAliases.insert(std::make_pair(outputPath, ta));
  1344. if (newAliasDefaultGlobal.second &&
  1345. newAliasDefaultGlobal.first->second.GeneratorTarget != target) {
  1346. newAliasDefaultGlobal.first->second.GeneratorTarget = nullptr;
  1347. }
  1348. }
  1349. }
  1350. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  1351. {
  1352. cmGlobalNinjaGenerator::WriteDivider(os);
  1353. os << "# Target aliases.\n\n";
  1354. cmNinjaBuild build("phony");
  1355. build.Outputs.emplace_back();
  1356. for (auto const& ta : this->TargetAliases) {
  1357. // Don't write ambiguous aliases.
  1358. if (!ta.second.GeneratorTarget) {
  1359. continue;
  1360. }
  1361. // Don't write alias if there is a already a custom command with
  1362. // matching output
  1363. if (this->HasCustomCommandOutput(ta.first)) {
  1364. continue;
  1365. }
  1366. build.Outputs.front() = ta.first;
  1367. build.ExplicitDeps.clear();
  1368. if (ta.second.Config == "all") {
  1369. for (auto const& config : this->CrossConfigs) {
  1370. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1371. build.ExplicitDeps, config,
  1372. DependOnTargetArtifact);
  1373. }
  1374. } else {
  1375. this->AppendTargetOutputs(ta.second.GeneratorTarget, build.ExplicitDeps,
  1376. ta.second.Config, DependOnTargetArtifact);
  1377. }
  1378. this->WriteBuild(this->EnableCrossConfigBuild() &&
  1379. (ta.second.Config == "all" ||
  1380. this->CrossConfigs.count(ta.second.Config))
  1381. ? os
  1382. : *this->GetImplFileStream(ta.second.Config),
  1383. build);
  1384. }
  1385. if (this->IsMultiConfig()) {
  1386. for (auto const& config : this->Makefiles.front()->GetGeneratorConfigs(
  1387. cmMakefile::IncludeEmptyConfig)) {
  1388. for (auto const& ta : this->Configs[config].TargetAliases) {
  1389. // Don't write ambiguous aliases.
  1390. if (!ta.second.GeneratorTarget) {
  1391. continue;
  1392. }
  1393. // Don't write alias if there is a already a custom command with
  1394. // matching output
  1395. if (this->HasCustomCommandOutput(ta.first)) {
  1396. continue;
  1397. }
  1398. build.Outputs.front() = ta.first;
  1399. build.ExplicitDeps.clear();
  1400. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1401. build.ExplicitDeps, config,
  1402. DependOnTargetArtifact);
  1403. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1404. }
  1405. }
  1406. if (!this->DefaultConfigs.empty()) {
  1407. for (auto const& ta : this->DefaultTargetAliases) {
  1408. // Don't write ambiguous aliases.
  1409. if (!ta.second.GeneratorTarget) {
  1410. continue;
  1411. }
  1412. // Don't write alias if there is a already a custom command with
  1413. // matching output
  1414. if (this->HasCustomCommandOutput(ta.first)) {
  1415. continue;
  1416. }
  1417. build.Outputs.front() = ta.first;
  1418. build.ExplicitDeps.clear();
  1419. for (auto const& config : this->DefaultConfigs) {
  1420. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1421. build.ExplicitDeps, config,
  1422. DependOnTargetArtifact);
  1423. }
  1424. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
  1430. {
  1431. cmGlobalNinjaGenerator::WriteDivider(os);
  1432. os << "# Folder targets.\n\n";
  1433. std::map<std::string, DirectoryTarget> dirTargets =
  1434. this->ComputeDirectoryTargets();
  1435. for (auto const& it : dirTargets) {
  1436. cmNinjaBuild build("phony");
  1437. cmGlobalNinjaGenerator::WriteDivider(os);
  1438. std::string const& currentBinaryDir = it.first;
  1439. DirectoryTarget const& dt = it.second;
  1440. std::vector<std::string> configs =
  1441. dt.LG->GetMakefile()->GetGeneratorConfigs(
  1442. cmMakefile::IncludeEmptyConfig);
  1443. // Setup target
  1444. cmNinjaDeps configDeps;
  1445. build.Comment = cmStrCat("Folder: ", currentBinaryDir);
  1446. build.Outputs.emplace_back();
  1447. std::string const buildDirAllTarget =
  1448. this->ConvertToNinjaPath(cmStrCat(currentBinaryDir, "/all"));
  1449. for (auto const& config : configs) {
  1450. build.ExplicitDeps.clear();
  1451. build.Outputs.front() = this->BuildAlias(buildDirAllTarget, config);
  1452. configDeps.emplace_back(build.Outputs.front());
  1453. for (DirectoryTarget::Target const& t : dt.Targets) {
  1454. if (!this->IsExcludedFromAllInConfig(t, config)) {
  1455. this->AppendTargetOutputs(t.GT, build.ExplicitDeps, config,
  1456. DependOnTargetArtifact);
  1457. }
  1458. }
  1459. for (DirectoryTarget::Dir const& d : dt.Children) {
  1460. if (!d.ExcludeFromAll) {
  1461. build.ExplicitDeps.emplace_back(this->BuildAlias(
  1462. this->ConvertToNinjaPath(cmStrCat(d.Path, "/all")), config));
  1463. }
  1464. }
  1465. // Write target
  1466. this->WriteBuild(this->EnableCrossConfigBuild() &&
  1467. this->CrossConfigs.count(config)
  1468. ? os
  1469. : *this->GetImplFileStream(config),
  1470. build);
  1471. }
  1472. // Add shortcut target
  1473. if (this->IsMultiConfig()) {
  1474. for (auto const& config : configs) {
  1475. build.ExplicitDeps = { this->BuildAlias(buildDirAllTarget, config) };
  1476. build.Outputs.front() = buildDirAllTarget;
  1477. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1478. }
  1479. if (!this->DefaultFileConfig.empty()) {
  1480. build.ExplicitDeps.clear();
  1481. for (auto const& config : this->DefaultConfigs) {
  1482. build.ExplicitDeps.push_back(
  1483. this->BuildAlias(buildDirAllTarget, config));
  1484. }
  1485. build.Outputs.front() = buildDirAllTarget;
  1486. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1487. }
  1488. }
  1489. // Add target for all configs
  1490. if (this->EnableCrossConfigBuild()) {
  1491. build.ExplicitDeps.clear();
  1492. for (auto const& config : this->CrossConfigs) {
  1493. build.ExplicitDeps.push_back(
  1494. this->BuildAlias(buildDirAllTarget, config));
  1495. }
  1496. build.Outputs.front() = this->BuildAlias(buildDirAllTarget, "all");
  1497. this->WriteBuild(os, build);
  1498. }
  1499. }
  1500. }
  1501. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  1502. {
  1503. if (!this->ComputingUnknownDependencies) {
  1504. return;
  1505. }
  1506. // We need to collect the set of known build outputs.
  1507. // Start with those generated by WriteBuild calls.
  1508. // No other method needs this so we can take ownership
  1509. // of the set locally and throw it out when we are done.
  1510. std::set<std::string> knownDependencies;
  1511. knownDependencies.swap(this->CombinedBuildOutputs);
  1512. // now write out the unknown explicit dependencies.
  1513. // union the configured files, evaluations files and the
  1514. // CombinedBuildOutputs,
  1515. // and then difference with CombinedExplicitDependencies to find the explicit
  1516. // dependencies that we have no rule for
  1517. cmGlobalNinjaGenerator::WriteDivider(os);
  1518. /* clang-format off */
  1519. os << "# Unknown Build Time Dependencies.\n"
  1520. << "# Tell Ninja that they may appear as side effects of build rules\n"
  1521. << "# otherwise ordered by order-only dependencies.\n\n";
  1522. /* clang-format on */
  1523. // get the list of files that cmake itself has generated as a
  1524. // product of configuration.
  1525. for (const auto& lg : this->LocalGenerators) {
  1526. // get the vector of files created by this makefile and convert them
  1527. // to ninja paths, which are all relative in respect to the build directory
  1528. for (std::string const& file : lg->GetMakefile()->GetOutputFiles()) {
  1529. knownDependencies.insert(this->ConvertToNinjaPath(file));
  1530. }
  1531. if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1532. // get list files which are implicit dependencies as well and will be
  1533. // phony for rebuild manifest
  1534. for (std::string const& j : lg->GetMakefile()->GetListFiles()) {
  1535. knownDependencies.insert(this->ConvertToNinjaPath(j));
  1536. }
  1537. }
  1538. for (const auto& li : lg->GetMakefile()->GetEvaluationFiles()) {
  1539. // get all the files created by generator expressions and convert them
  1540. // to ninja paths
  1541. for (std::string const& evaluationFile : li->GetFiles()) {
  1542. knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile));
  1543. }
  1544. }
  1545. }
  1546. knownDependencies.insert(this->CMakeCacheFile);
  1547. for (auto const& ta : this->TargetAliases) {
  1548. knownDependencies.insert(this->ConvertToNinjaPath(ta.first));
  1549. }
  1550. // remove all source files we know will exist.
  1551. for (auto const& i : this->AssumedSourceDependencies) {
  1552. knownDependencies.insert(this->ConvertToNinjaPath(i.first));
  1553. }
  1554. // now we difference with CombinedCustomCommandExplicitDependencies to find
  1555. // the list of items we know nothing about.
  1556. // We have encoded all the paths in CombinedCustomCommandExplicitDependencies
  1557. // and knownDependencies so no matter if unix or windows paths they
  1558. // should all match now.
  1559. std::vector<std::string> unknownExplicitDepends;
  1560. this->CombinedCustomCommandExplicitDependencies.erase(this->TargetAll);
  1561. std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(),
  1562. this->CombinedCustomCommandExplicitDependencies.end(),
  1563. knownDependencies.begin(), knownDependencies.end(),
  1564. std::back_inserter(unknownExplicitDepends));
  1565. std::vector<std::string> warnExplicitDepends;
  1566. if (!unknownExplicitDepends.empty()) {
  1567. cmake* cmk = this->GetCMakeInstance();
  1568. std::string const& buildRoot = cmk->GetHomeOutputDirectory();
  1569. bool const inSource = (buildRoot == cmk->GetHomeDirectory());
  1570. bool const warn = (!inSource && (this->PolicyCMP0058 == cmPolicies::WARN));
  1571. cmNinjaBuild build("phony");
  1572. build.Outputs.emplace_back("");
  1573. for (std::string const& ued : unknownExplicitDepends) {
  1574. // verify the file is in the build directory
  1575. std::string const absDepPath =
  1576. cmSystemTools::CollapseFullPath(ued, buildRoot);
  1577. if (cmSystemTools::IsSubDirectory(absDepPath, buildRoot)) {
  1578. // Generate phony build statement
  1579. build.Outputs[0] = ued;
  1580. this->WriteBuild(os, build);
  1581. // Add to warning on demand
  1582. if (warn && warnExplicitDepends.size() < 10) {
  1583. warnExplicitDepends.push_back(ued);
  1584. }
  1585. }
  1586. }
  1587. }
  1588. if (!warnExplicitDepends.empty()) {
  1589. std::ostringstream w;
  1590. /* clang-format off */
  1591. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0058) << "\n"
  1592. "This project specifies custom command DEPENDS on files "
  1593. "in the build tree that are not specified as the OUTPUT or "
  1594. "BYPRODUCTS of any add_custom_command or add_custom_target:\n"
  1595. " " << cmJoin(warnExplicitDepends, "\n ") <<
  1596. "\n"
  1597. "For compatibility with versions of CMake that did not have "
  1598. "the BYPRODUCTS option, CMake is generating phony rules for "
  1599. "such files to convince 'ninja' to build."
  1600. "\n"
  1601. "Project authors should add the missing BYPRODUCTS or OUTPUT "
  1602. "options to the custom commands that produce these files."
  1603. ;
  1604. /* clang-format on */
  1605. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1606. w.str());
  1607. }
  1608. }
  1609. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  1610. {
  1611. // Write headers.
  1612. cmGlobalNinjaGenerator::WriteDivider(os);
  1613. os << "# Built-in targets\n\n";
  1614. this->WriteTargetRebuildManifest(os);
  1615. this->WriteTargetClean(os);
  1616. this->WriteTargetHelp(os);
  1617. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  1618. cmMakefile::IncludeEmptyConfig)) {
  1619. this->WriteTargetDefault(*this->GetConfigFileStream(config));
  1620. }
  1621. if (!this->DefaultFileConfig.empty()) {
  1622. this->WriteTargetDefault(*this->GetDefaultFileStream());
  1623. }
  1624. }
  1625. void cmGlobalNinjaGenerator::WriteTargetDefault(std::ostream& os)
  1626. {
  1627. if (!this->HasOutputPathPrefix()) {
  1628. cmNinjaDeps all;
  1629. all.push_back(this->TargetAll);
  1630. cmGlobalNinjaGenerator::WriteDefault(os, all,
  1631. "Make the all target the default.");
  1632. }
  1633. }
  1634. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  1635. {
  1636. if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1637. return;
  1638. }
  1639. cmake* cm = this->GetCMakeInstance();
  1640. const auto& lg = this->LocalGenerators[0];
  1641. {
  1642. cmNinjaRule rule("RERUN_CMAKE");
  1643. rule.Command = cmStrCat(
  1644. this->CMakeCmd(), " --regenerate-during-build",
  1645. cm->GetIgnoreWarningAsError() ? " --compile-no-warning-as-error" : "",
  1646. " -S",
  1647. lg->ConvertToOutputFormat(lg->GetSourceDirectory(),
  1648. cmOutputConverter::SHELL),
  1649. " -B",
  1650. lg->ConvertToOutputFormat(lg->GetBinaryDirectory(),
  1651. cmOutputConverter::SHELL));
  1652. rule.Description = "Re-running CMake...";
  1653. rule.Comment = "Rule for re-running cmake.";
  1654. rule.Generator = true;
  1655. WriteRule(*this->RulesFileStream, rule);
  1656. }
  1657. cmNinjaBuild reBuild("RERUN_CMAKE");
  1658. reBuild.Comment = "Re-run CMake if any of its inputs changed.";
  1659. this->AddRebuildManifestOutputs(reBuild.Outputs);
  1660. for (const auto& localGen : this->LocalGenerators) {
  1661. for (std::string const& fi : localGen->GetMakefile()->GetListFiles()) {
  1662. reBuild.ImplicitDeps.push_back(this->ConvertToNinjaPath(fi));
  1663. }
  1664. }
  1665. reBuild.ImplicitDeps.push_back(this->CMakeCacheFile);
  1666. // Use 'console' pool to get non buffered output of the CMake re-run call
  1667. // Available since Ninja 1.5
  1668. if (this->SupportsDirectConsole()) {
  1669. reBuild.Variables["pool"] = "console";
  1670. }
  1671. if (this->SupportsManifestRestat() && cm->DoWriteGlobVerifyTarget()) {
  1672. {
  1673. cmNinjaRule rule("VERIFY_GLOBS");
  1674. rule.Command =
  1675. cmStrCat(this->CMakeCmd(), " -P ",
  1676. lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1677. cmOutputConverter::SHELL));
  1678. rule.Description = "Re-checking globbed directories...";
  1679. rule.Comment = "Rule for re-checking globbed directories.";
  1680. rule.Generator = true;
  1681. this->WriteRule(*this->RulesFileStream, rule);
  1682. }
  1683. cmNinjaBuild phonyBuild("phony");
  1684. phonyBuild.Comment = "Phony target to force glob verification run.";
  1685. phonyBuild.Outputs.push_back(
  1686. cmStrCat(cm->GetGlobVerifyScript(), "_force"));
  1687. this->WriteBuild(os, phonyBuild);
  1688. reBuild.Variables["restat"] = "1";
  1689. std::string const verifyScriptFile =
  1690. this->NinjaOutputPath(cm->GetGlobVerifyScript());
  1691. std::string const verifyStampFile =
  1692. this->NinjaOutputPath(cm->GetGlobVerifyStamp());
  1693. {
  1694. cmNinjaBuild vgBuild("VERIFY_GLOBS");
  1695. vgBuild.Comment =
  1696. "Re-run CMake to check if globbed directories changed.";
  1697. vgBuild.Outputs.push_back(verifyStampFile);
  1698. vgBuild.ImplicitDeps = phonyBuild.Outputs;
  1699. vgBuild.Variables = reBuild.Variables;
  1700. this->WriteBuild(os, vgBuild);
  1701. }
  1702. reBuild.Variables.erase("restat");
  1703. reBuild.ImplicitDeps.push_back(verifyScriptFile);
  1704. reBuild.ExplicitDeps.push_back(verifyStampFile);
  1705. } else if (!this->SupportsManifestRestat() &&
  1706. cm->DoWriteGlobVerifyTarget()) {
  1707. std::ostringstream msg;
  1708. msg << "The detected version of Ninja:\n"
  1709. << " " << this->NinjaVersion << "\n"
  1710. << "is less than the version of Ninja required by CMake for adding "
  1711. "restat dependencies to the build.ninja manifest regeneration "
  1712. "target:\n"
  1713. << " "
  1714. << cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat()
  1715. << "\n";
  1716. msg << "Any pre-check scripts, such as those generated for file(GLOB "
  1717. "CONFIGURE_DEPENDS), will not be run by Ninja.";
  1718. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1719. msg.str());
  1720. }
  1721. std::sort(reBuild.ImplicitDeps.begin(), reBuild.ImplicitDeps.end());
  1722. reBuild.ImplicitDeps.erase(
  1723. std::unique(reBuild.ImplicitDeps.begin(), reBuild.ImplicitDeps.end()),
  1724. reBuild.ImplicitDeps.end());
  1725. this->WriteBuild(os, reBuild);
  1726. {
  1727. cmNinjaBuild build("phony");
  1728. build.Comment = "A missing CMake input file is not an error.";
  1729. std::set_difference(std::make_move_iterator(reBuild.ImplicitDeps.begin()),
  1730. std::make_move_iterator(reBuild.ImplicitDeps.end()),
  1731. this->CustomCommandOutputs.begin(),
  1732. this->CustomCommandOutputs.end(),
  1733. std::back_inserter(build.Outputs));
  1734. this->WriteBuild(os, build);
  1735. }
  1736. }
  1737. std::string cmGlobalNinjaGenerator::CMakeCmd() const
  1738. {
  1739. const auto& lgen = this->LocalGenerators.at(0);
  1740. return lgen->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  1741. cmOutputConverter::SHELL);
  1742. }
  1743. std::string cmGlobalNinjaGenerator::NinjaCmd() const
  1744. {
  1745. const auto& lgen = this->LocalGenerators[0];
  1746. if (lgen != nullptr) {
  1747. return lgen->ConvertToOutputFormat(this->NinjaCommand,
  1748. cmOutputConverter::SHELL);
  1749. }
  1750. return "ninja";
  1751. }
  1752. bool cmGlobalNinjaGenerator::SupportsDirectConsole() const
  1753. {
  1754. return this->NinjaSupportsConsolePool;
  1755. }
  1756. bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const
  1757. {
  1758. return this->NinjaSupportsImplicitOuts;
  1759. }
  1760. bool cmGlobalNinjaGenerator::SupportsManifestRestat() const
  1761. {
  1762. return this->NinjaSupportsManifestRestat;
  1763. }
  1764. bool cmGlobalNinjaGenerator::SupportsMultilineDepfile() const
  1765. {
  1766. return this->NinjaSupportsMultilineDepfile;
  1767. }
  1768. bool cmGlobalNinjaGenerator::WriteTargetCleanAdditional(std::ostream& os)
  1769. {
  1770. const auto& lgr = this->LocalGenerators.at(0);
  1771. std::string cleanScriptRel = "CMakeFiles/clean_additional.cmake";
  1772. std::string cleanScriptAbs =
  1773. cmStrCat(lgr->GetBinaryDirectory(), '/', cleanScriptRel);
  1774. std::vector<std::string> configs =
  1775. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1776. // Check if there are additional files to clean
  1777. bool empty = true;
  1778. for (auto const& config : configs) {
  1779. auto const it = this->Configs.find(config);
  1780. if (it != this->Configs.end() &&
  1781. !it->second.AdditionalCleanFiles.empty()) {
  1782. empty = false;
  1783. break;
  1784. }
  1785. }
  1786. if (empty) {
  1787. // Remove cmake clean script file if it exists
  1788. cmSystemTools::RemoveFile(cleanScriptAbs);
  1789. return false;
  1790. }
  1791. // Write cmake clean script file
  1792. {
  1793. cmGeneratedFileStream fout(cleanScriptAbs);
  1794. if (!fout) {
  1795. return false;
  1796. }
  1797. fout << "# Additional clean files\ncmake_minimum_required(VERSION 3.16)\n";
  1798. for (auto const& config : configs) {
  1799. auto const it = this->Configs.find(config);
  1800. if (it != this->Configs.end() &&
  1801. !it->second.AdditionalCleanFiles.empty()) {
  1802. fout << "\nif(\"${CONFIG}\" STREQUAL \"\" OR \"${CONFIG}\" STREQUAL \""
  1803. << config << "\")\n";
  1804. fout << " file(REMOVE_RECURSE\n";
  1805. for (std::string const& acf : it->second.AdditionalCleanFiles) {
  1806. fout << " "
  1807. << cmOutputConverter::EscapeForCMake(
  1808. this->ConvertToNinjaPath(acf))
  1809. << '\n';
  1810. }
  1811. fout << " )\n";
  1812. fout << "endif()\n";
  1813. }
  1814. }
  1815. }
  1816. // Register clean script file
  1817. lgr->GetMakefile()->AddCMakeOutputFile(cleanScriptAbs);
  1818. // Write rule
  1819. {
  1820. cmNinjaRule rule("CLEAN_ADDITIONAL");
  1821. rule.Command = cmStrCat(
  1822. this->CMakeCmd(), " -DCONFIG=$CONFIG -P ",
  1823. lgr->ConvertToOutputFormat(this->NinjaOutputPath(cleanScriptRel),
  1824. cmOutputConverter::SHELL));
  1825. rule.Description = "Cleaning additional files...";
  1826. rule.Comment = "Rule for cleaning additional files.";
  1827. WriteRule(*this->RulesFileStream, rule);
  1828. }
  1829. // Write build
  1830. {
  1831. cmNinjaBuild build("CLEAN_ADDITIONAL");
  1832. build.Comment = "Clean additional files.";
  1833. build.Outputs.emplace_back();
  1834. for (auto const& config : configs) {
  1835. build.Outputs.front() = this->BuildAlias(
  1836. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()), config);
  1837. build.Variables["CONFIG"] = config;
  1838. this->WriteBuild(os, build);
  1839. }
  1840. if (this->IsMultiConfig()) {
  1841. build.Outputs.front() =
  1842. this->NinjaOutputPath(this->GetAdditionalCleanTargetName());
  1843. build.Variables["CONFIG"] = "";
  1844. this->WriteBuild(os, build);
  1845. }
  1846. }
  1847. // Return success
  1848. return true;
  1849. }
  1850. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1851. {
  1852. // -- Additional clean target
  1853. bool additionalFiles = this->WriteTargetCleanAdditional(os);
  1854. // -- Default clean target
  1855. // Write rule
  1856. {
  1857. cmNinjaRule rule("CLEAN");
  1858. rule.Command = cmStrCat(this->NinjaCmd(), " $FILE_ARG -t clean $TARGETS");
  1859. rule.Description = "Cleaning all built files...";
  1860. rule.Comment = "Rule for cleaning all built files.";
  1861. WriteRule(*this->RulesFileStream, rule);
  1862. }
  1863. auto const configs = this->Makefiles.front()->GetGeneratorConfigs(
  1864. cmMakefile::IncludeEmptyConfig);
  1865. // Write build
  1866. {
  1867. cmNinjaBuild build("CLEAN");
  1868. build.Comment = "Clean all the built files.";
  1869. build.Outputs.emplace_back();
  1870. for (auto const& config : configs) {
  1871. build.Outputs.front() = this->BuildAlias(
  1872. this->NinjaOutputPath(this->GetCleanTargetName()), config);
  1873. if (this->IsMultiConfig()) {
  1874. build.Variables["TARGETS"] = cmStrCat(
  1875. this->BuildAlias(
  1876. this->NinjaOutputPath(GetByproductsForCleanTargetName()), config),
  1877. " ", this->NinjaOutputPath(GetByproductsForCleanTargetName()));
  1878. }
  1879. build.ExplicitDeps.clear();
  1880. if (additionalFiles) {
  1881. build.ExplicitDeps.push_back(this->BuildAlias(
  1882. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()),
  1883. config));
  1884. }
  1885. for (auto const& fileConfig : configs) {
  1886. if (fileConfig != config && !this->EnableCrossConfigBuild()) {
  1887. continue;
  1888. }
  1889. if (this->IsMultiConfig()) {
  1890. build.Variables["FILE_ARG"] = cmStrCat(
  1891. "-f ",
  1892. this->NinjaOutputPath(
  1893. cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(fileConfig)));
  1894. }
  1895. this->WriteBuild(*this->GetImplFileStream(fileConfig), build);
  1896. }
  1897. }
  1898. if (this->EnableCrossConfigBuild()) {
  1899. build.Outputs.front() = this->BuildAlias(
  1900. this->NinjaOutputPath(this->GetCleanTargetName()), "all");
  1901. build.ExplicitDeps.clear();
  1902. if (additionalFiles) {
  1903. for (auto const& config : this->CrossConfigs) {
  1904. build.ExplicitDeps.push_back(this->BuildAlias(
  1905. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()),
  1906. config));
  1907. }
  1908. }
  1909. std::vector<std::string> byproducts;
  1910. byproducts.reserve(this->CrossConfigs.size());
  1911. for (auto const& config : this->CrossConfigs) {
  1912. byproducts.push_back(this->BuildAlias(
  1913. this->NinjaOutputPath(GetByproductsForCleanTargetName()), config));
  1914. }
  1915. byproducts.emplace_back(GetByproductsForCleanTargetName());
  1916. build.Variables["TARGETS"] = cmJoin(byproducts, " ");
  1917. for (auto const& fileConfig : configs) {
  1918. build.Variables["FILE_ARG"] = cmStrCat(
  1919. "-f ",
  1920. this->NinjaOutputPath(
  1921. cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(fileConfig)));
  1922. this->WriteBuild(*this->GetImplFileStream(fileConfig), build);
  1923. }
  1924. }
  1925. }
  1926. if (this->IsMultiConfig()) {
  1927. cmNinjaBuild build("phony");
  1928. build.Outputs.emplace_back(
  1929. this->NinjaOutputPath(this->GetCleanTargetName()));
  1930. build.ExplicitDeps.emplace_back();
  1931. for (auto const& config : configs) {
  1932. build.ExplicitDeps.front() = this->BuildAlias(
  1933. this->NinjaOutputPath(this->GetCleanTargetName()), config);
  1934. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1935. }
  1936. if (!this->DefaultConfigs.empty()) {
  1937. build.ExplicitDeps.clear();
  1938. for (auto const& config : this->DefaultConfigs) {
  1939. build.ExplicitDeps.push_back(this->BuildAlias(
  1940. this->NinjaOutputPath(this->GetCleanTargetName()), config));
  1941. }
  1942. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1943. }
  1944. }
  1945. // Write byproducts
  1946. if (this->IsMultiConfig()) {
  1947. cmNinjaBuild build("phony");
  1948. build.Comment = "Clean byproducts.";
  1949. build.Outputs.emplace_back(
  1950. this->ConvertToNinjaPath(GetByproductsForCleanTargetName()));
  1951. build.ExplicitDeps = this->ByproductsForCleanTarget;
  1952. this->WriteBuild(os, build);
  1953. for (auto const& config : configs) {
  1954. build.Outputs.front() = this->BuildAlias(
  1955. this->ConvertToNinjaPath(GetByproductsForCleanTargetName()), config);
  1956. build.ExplicitDeps = this->Configs[config].ByproductsForCleanTarget;
  1957. this->WriteBuild(os, build);
  1958. }
  1959. }
  1960. }
  1961. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1962. {
  1963. {
  1964. cmNinjaRule rule("HELP");
  1965. rule.Command = cmStrCat(this->NinjaCmd(), " -t targets");
  1966. rule.Description = "All primary targets available:";
  1967. rule.Comment = "Rule for printing all primary targets available.";
  1968. WriteRule(*this->RulesFileStream, rule);
  1969. }
  1970. {
  1971. cmNinjaBuild build("HELP");
  1972. build.Comment = "Print all primary targets available.";
  1973. build.Outputs.push_back(this->NinjaOutputPath("help"));
  1974. this->WriteBuild(os, build);
  1975. }
  1976. }
  1977. void cmGlobalNinjaGenerator::InitOutputPathPrefix()
  1978. {
  1979. this->OutputPathPrefix =
  1980. this->LocalGenerators[0]->GetMakefile()->GetSafeDefinition(
  1981. "CMAKE_NINJA_OUTPUT_PATH_PREFIX");
  1982. EnsureTrailingSlash(this->OutputPathPrefix);
  1983. }
  1984. std::string cmGlobalNinjaGenerator::NinjaOutputPath(
  1985. std::string const& path) const
  1986. {
  1987. if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) {
  1988. return path;
  1989. }
  1990. return cmStrCat(this->OutputPathPrefix, path);
  1991. }
  1992. void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix(
  1993. std::string& path)
  1994. {
  1995. if (path.empty()) {
  1996. return;
  1997. }
  1998. EnsureTrailingSlash(path);
  1999. cmStripSuffixIfExists(path, this->OutputPathPrefix);
  2000. }
  2001. #if !defined(CMAKE_BOOTSTRAP)
  2002. /*
  2003. We use the following approach to support Fortran. Each target already
  2004. has a <target>.dir/ directory used to hold intermediate files for CMake.
  2005. For each target, a FortranDependInfo.json file is generated by CMake with
  2006. information about include directories, module directories, and the locations
  2007. the per-target directories for target dependencies.
  2008. Compilation of source files within a target is split into the following steps:
  2009. 1. Preprocess all sources, scan preprocessed output for module dependencies.
  2010. This step is done with independent build statements for each source,
  2011. and can therefore be done in parallel.
  2012. rule Fortran_PREPROCESS
  2013. depfile = $DEP_FILE
  2014. command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out &&
  2015. cmake -E cmake_ninja_depends \
  2016. --tdi=FortranDependInfo.json --lang=Fortran \
  2017. --src=$out --out=$out --dep=$DEP_FILE --obj=$OBJ_FILE \
  2018. --ddi=$DYNDEP_INTERMEDIATE_FILE
  2019. build src.f90-pp.f90 | src.f90.o.ddi: Fortran_PREPROCESS src.f90
  2020. OBJ_FILE = src.f90.o
  2021. DEP_FILE = src.f90.o.d
  2022. DYNDEP_INTERMEDIATE_FILE = src.f90.o.ddi
  2023. The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output
  2024. and generates the ninja depfile for preprocessor dependencies. It also
  2025. generates a "ddi" file (in a format private to CMake) that lists the
  2026. object file that compilation will produce along with the module names
  2027. it provides and/or requires. The "ddi" file is an implicit output
  2028. because it should not appear in "$out" but is generated by the rule.
  2029. 2. Consolidate the per-source module dependencies saved in the "ddi"
  2030. files from all sources to produce a ninja "dyndep" file, ``Fortran.dd``.
  2031. rule Fortran_DYNDEP
  2032. command = cmake -E cmake_ninja_dyndep \
  2033. --tdi=FortranDependInfo.json --lang=Fortran --dd=$out $in
  2034. build Fortran.dd: Fortran_DYNDEP src1.f90.o.ddi src2.f90.o.ddi
  2035. The ``cmake -E cmake_ninja_dyndep`` tool reads the "ddi" files from all
  2036. sources in the target and the ``FortranModules.json`` files from targets
  2037. on which the target depends. It computes dependency edges on compilations
  2038. that require modules to those that provide the modules. This information
  2039. is placed in the ``Fortran.dd`` file for ninja to load later. It also
  2040. writes the expected location of modules provided by this target into
  2041. ``FortranModules.json`` for use by dependent targets.
  2042. 3. Compile all sources after loading dynamically discovered dependencies
  2043. of the compilation build statements from their ``dyndep`` bindings.
  2044. rule Fortran_COMPILE
  2045. command = gfortran $INCLUDES $FLAGS -c $in -o $out
  2046. build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd
  2047. dyndep = Fortran.dd
  2048. The "dyndep" binding tells ninja to load dynamically discovered
  2049. dependency information from ``Fortran.dd``. This adds information
  2050. such as:
  2051. build src1.f90.o | mod1.mod: dyndep
  2052. restat = 1
  2053. This tells ninja that ``mod1.mod`` is an implicit output of compiling
  2054. the object file ``src1.f90.o``. The ``restat`` binding tells it that
  2055. the timestamp of the output may not always change. Additionally:
  2056. build src2.f90.o: dyndep | mod1.mod
  2057. This tells ninja that ``mod1.mod`` is a dependency of compiling the
  2058. object file ``src2.f90.o``. This ensures that ``src1.f90.o`` and
  2059. ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built
  2060. (because the latter consumes the module).
  2061. */
  2062. namespace {
  2063. struct cmSourceInfo
  2064. {
  2065. cmScanDepInfo ScanDep;
  2066. std::vector<std::string> Includes;
  2067. };
  2068. cm::optional<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran(
  2069. std::string const& arg_tdi, std::string const& arg_src);
  2070. }
  2071. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  2072. std::vector<std::string>::const_iterator argEnd)
  2073. {
  2074. std::string arg_tdi;
  2075. std::string arg_src;
  2076. std::string arg_out;
  2077. std::string arg_dep;
  2078. std::string arg_obj;
  2079. std::string arg_ddi;
  2080. std::string arg_lang;
  2081. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  2082. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  2083. arg_tdi = arg.substr(6);
  2084. } else if (cmHasLiteralPrefix(arg, "--src=")) {
  2085. arg_src = arg.substr(6);
  2086. } else if (cmHasLiteralPrefix(arg, "--out=")) {
  2087. arg_out = arg.substr(6);
  2088. } else if (cmHasLiteralPrefix(arg, "--dep=")) {
  2089. arg_dep = arg.substr(6);
  2090. } else if (cmHasLiteralPrefix(arg, "--obj=")) {
  2091. arg_obj = arg.substr(6);
  2092. } else if (cmHasLiteralPrefix(arg, "--ddi=")) {
  2093. arg_ddi = arg.substr(6);
  2094. } else if (cmHasLiteralPrefix(arg, "--lang=")) {
  2095. arg_lang = arg.substr(7);
  2096. } else if (cmHasLiteralPrefix(arg, "--pp=")) {
  2097. // CMake 3.26 and below used '--pp=' instead of '--src=' and '--out='.
  2098. arg_src = arg.substr(5);
  2099. arg_out = arg_src;
  2100. } else {
  2101. cmSystemTools::Error(
  2102. cmStrCat("-E cmake_ninja_depends unknown argument: ", arg));
  2103. return 1;
  2104. }
  2105. }
  2106. if (arg_tdi.empty()) {
  2107. cmSystemTools::Error("-E cmake_ninja_depends requires value for --tdi=");
  2108. return 1;
  2109. }
  2110. if (arg_src.empty()) {
  2111. cmSystemTools::Error("-E cmake_ninja_depends requires value for --src=");
  2112. return 1;
  2113. }
  2114. if (arg_out.empty()) {
  2115. cmSystemTools::Error("-E cmake_ninja_depends requires value for --out=");
  2116. return 1;
  2117. }
  2118. if (arg_dep.empty()) {
  2119. cmSystemTools::Error("-E cmake_ninja_depends requires value for --dep=");
  2120. return 1;
  2121. }
  2122. if (arg_obj.empty()) {
  2123. cmSystemTools::Error("-E cmake_ninja_depends requires value for --obj=");
  2124. return 1;
  2125. }
  2126. if (arg_ddi.empty()) {
  2127. cmSystemTools::Error("-E cmake_ninja_depends requires value for --ddi=");
  2128. return 1;
  2129. }
  2130. if (arg_lang.empty()) {
  2131. cmSystemTools::Error("-E cmake_ninja_depends requires value for --lang=");
  2132. return 1;
  2133. }
  2134. cm::optional<cmSourceInfo> info;
  2135. if (arg_lang == "Fortran") {
  2136. info = cmcmd_cmake_ninja_depends_fortran(arg_tdi, arg_src);
  2137. } else {
  2138. cmSystemTools::Error(
  2139. cmStrCat("-E cmake_ninja_depends does not understand the ", arg_lang,
  2140. " language"));
  2141. return 1;
  2142. }
  2143. if (!info) {
  2144. // The error message is already expected to have been output.
  2145. return 1;
  2146. }
  2147. info->ScanDep.PrimaryOutput = arg_obj;
  2148. {
  2149. cmGeneratedFileStream depfile(arg_dep);
  2150. depfile << cmSystemTools::ConvertToUnixOutputPath(arg_out) << ":";
  2151. for (std::string const& include : info->Includes) {
  2152. depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include);
  2153. }
  2154. depfile << "\n";
  2155. }
  2156. if (!cmScanDepFormat_P1689_Write(arg_ddi, info->ScanDep)) {
  2157. cmSystemTools::Error(
  2158. cmStrCat("-E cmake_ninja_depends failed to write ", arg_ddi));
  2159. return 1;
  2160. }
  2161. return 0;
  2162. }
  2163. namespace {
  2164. cm::optional<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran(
  2165. std::string const& arg_tdi, std::string const& arg_src)
  2166. {
  2167. cm::optional<cmSourceInfo> info;
  2168. cmFortranCompiler fc;
  2169. std::vector<std::string> includes;
  2170. std::string dir_top_bld;
  2171. std::string module_dir;
  2172. {
  2173. Json::Value tdio;
  2174. Json::Value const& tdi = tdio;
  2175. {
  2176. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  2177. Json::Reader reader;
  2178. if (!reader.parse(tdif, tdio, false)) {
  2179. cmSystemTools::Error(
  2180. cmStrCat("-E cmake_ninja_depends failed to parse ", arg_tdi,
  2181. reader.getFormattedErrorMessages()));
  2182. return info;
  2183. }
  2184. }
  2185. dir_top_bld = tdi["dir-top-bld"].asString();
  2186. if (!dir_top_bld.empty() && !cmHasLiteralSuffix(dir_top_bld, "/")) {
  2187. dir_top_bld += '/';
  2188. }
  2189. Json::Value const& tdi_include_dirs = tdi["include-dirs"];
  2190. if (tdi_include_dirs.isArray()) {
  2191. for (auto const& tdi_include_dir : tdi_include_dirs) {
  2192. includes.push_back(tdi_include_dir.asString());
  2193. }
  2194. }
  2195. Json::Value const& tdi_module_dir = tdi["module-dir"];
  2196. module_dir = tdi_module_dir.asString();
  2197. if (!module_dir.empty() && !cmHasLiteralSuffix(module_dir, "/")) {
  2198. module_dir += '/';
  2199. }
  2200. Json::Value const& tdi_compiler_id = tdi["compiler-id"];
  2201. fc.Id = tdi_compiler_id.asString();
  2202. Json::Value const& tdi_submodule_sep = tdi["submodule-sep"];
  2203. fc.SModSep = tdi_submodule_sep.asString();
  2204. Json::Value const& tdi_submodule_ext = tdi["submodule-ext"];
  2205. fc.SModExt = tdi_submodule_ext.asString();
  2206. }
  2207. cmFortranSourceInfo finfo;
  2208. std::set<std::string> defines;
  2209. cmFortranParser parser(fc, includes, defines, finfo);
  2210. if (!cmFortranParser_FilePush(&parser, arg_src.c_str())) {
  2211. cmSystemTools::Error(
  2212. cmStrCat("-E cmake_ninja_depends failed to open ", arg_src));
  2213. return info;
  2214. }
  2215. if (cmFortran_yyparse(parser.Scanner) != 0) {
  2216. // Failed to parse the file.
  2217. return info;
  2218. }
  2219. info = cmSourceInfo();
  2220. for (std::string const& provide : finfo.Provides) {
  2221. cmSourceReqInfo src_info;
  2222. src_info.LogicalName = provide;
  2223. if (!module_dir.empty()) {
  2224. std::string mod = cmStrCat(module_dir, provide);
  2225. if (!dir_top_bld.empty() && cmHasPrefix(mod, dir_top_bld)) {
  2226. mod = mod.substr(dir_top_bld.size());
  2227. }
  2228. src_info.CompiledModulePath = std::move(mod);
  2229. }
  2230. info->ScanDep.Provides.emplace_back(src_info);
  2231. }
  2232. for (std::string const& require : finfo.Requires) {
  2233. // Require modules not provided in the same source.
  2234. if (finfo.Provides.count(require)) {
  2235. continue;
  2236. }
  2237. cmSourceReqInfo src_info;
  2238. src_info.LogicalName = require;
  2239. info->ScanDep.Requires.emplace_back(src_info);
  2240. }
  2241. for (std::string const& include : finfo.Includes) {
  2242. info->Includes.push_back(include);
  2243. }
  2244. return info;
  2245. }
  2246. }
  2247. bool cmGlobalNinjaGenerator::WriteDyndepFile(
  2248. std::string const& dir_top_src, std::string const& dir_top_bld,
  2249. std::string const& dir_cur_src, std::string const& dir_cur_bld,
  2250. std::string const& arg_dd, std::vector<std::string> const& arg_ddis,
  2251. std::string const& module_dir,
  2252. std::vector<std::string> const& linked_target_dirs,
  2253. std::string const& arg_lang, std::string const& arg_modmapfmt,
  2254. cmCxxModuleExportInfo const& export_info)
  2255. {
  2256. // Setup path conversions.
  2257. {
  2258. cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot();
  2259. snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
  2260. snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
  2261. auto mfd = cm::make_unique<cmMakefile>(this, snapshot);
  2262. auto lgd = this->CreateLocalGenerator(mfd.get());
  2263. lgd->SetRelativePathTop(dir_top_src, dir_top_bld);
  2264. this->Makefiles.push_back(std::move(mfd));
  2265. this->LocalGenerators.push_back(std::move(lgd));
  2266. }
  2267. std::vector<cmScanDepInfo> objects;
  2268. for (std::string const& arg_ddi : arg_ddis) {
  2269. cmScanDepInfo info;
  2270. if (!cmScanDepFormat_P1689_Parse(arg_ddi, &info)) {
  2271. cmSystemTools::Error(
  2272. cmStrCat("-E cmake_ninja_dyndep failed to parse ddi file ", arg_ddi));
  2273. return false;
  2274. }
  2275. objects.push_back(std::move(info));
  2276. }
  2277. CxxModuleUsage usages;
  2278. // Map from module name to module file path, if known.
  2279. struct AvailableModuleInfo
  2280. {
  2281. std::string BmiPath;
  2282. bool IsPrivate;
  2283. };
  2284. std::map<std::string, AvailableModuleInfo> mod_files;
  2285. // Populate the module map with those provided by linked targets first.
  2286. for (std::string const& linked_target_dir : linked_target_dirs) {
  2287. std::string const ltmn =
  2288. cmStrCat(linked_target_dir, '/', arg_lang, "Modules.json");
  2289. Json::Value ltm;
  2290. cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
  2291. if (!ltmf) {
  2292. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to open ",
  2293. ltmn, " for module information"));
  2294. return false;
  2295. }
  2296. Json::Reader reader;
  2297. if (!reader.parse(ltmf, ltm, false)) {
  2298. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2299. linked_target_dir,
  2300. reader.getFormattedErrorMessages()));
  2301. return false;
  2302. }
  2303. if (ltm.isObject()) {
  2304. Json::Value const& target_modules = ltm["modules"];
  2305. if (target_modules.isObject()) {
  2306. for (auto i = target_modules.begin(); i != target_modules.end(); ++i) {
  2307. Json::Value const& visible_module = *i;
  2308. if (visible_module.isObject()) {
  2309. Json::Value const& bmi_path = visible_module["bmi"];
  2310. Json::Value const& is_private = visible_module["is-private"];
  2311. mod_files[i.key().asString()] = AvailableModuleInfo{
  2312. bmi_path.asString(),
  2313. is_private.asBool(),
  2314. };
  2315. }
  2316. }
  2317. }
  2318. Json::Value const& target_modules_references = ltm["references"];
  2319. if (target_modules_references.isObject()) {
  2320. for (auto i = target_modules_references.begin();
  2321. i != target_modules_references.end(); ++i) {
  2322. if (i->isObject()) {
  2323. Json::Value const& reference_path = (*i)["path"];
  2324. CxxModuleReference module_reference;
  2325. if (reference_path.isString()) {
  2326. module_reference.Path = reference_path.asString();
  2327. }
  2328. Json::Value const& reference_method = (*i)["lookup-method"];
  2329. if (reference_method.isString()) {
  2330. std::string reference = reference_method.asString();
  2331. if (reference == "by-name") {
  2332. module_reference.Method = LookupMethod::ByName;
  2333. } else if (reference == "include-angle") {
  2334. module_reference.Method = LookupMethod::IncludeAngle;
  2335. } else if (reference == "include-quote") {
  2336. module_reference.Method = LookupMethod::IncludeQuote;
  2337. }
  2338. }
  2339. usages.Reference[i.key().asString()] = module_reference;
  2340. }
  2341. }
  2342. }
  2343. Json::Value const& target_modules_usage = ltm["usages"];
  2344. if (target_modules_usage.isObject()) {
  2345. for (auto i = target_modules_usage.begin();
  2346. i != target_modules_usage.end(); ++i) {
  2347. if (i->isArray()) {
  2348. for (auto j = i->begin(); j != i->end(); ++j) {
  2349. usages.Usage[i.key().asString()].insert(j->asString());
  2350. }
  2351. }
  2352. }
  2353. }
  2354. }
  2355. }
  2356. cm::optional<CxxModuleMapFormat> modmap_fmt;
  2357. if (arg_modmapfmt.empty()) {
  2358. // nothing to do.
  2359. } else if (arg_modmapfmt == "clang") {
  2360. modmap_fmt = CxxModuleMapFormat::Clang;
  2361. } else if (arg_modmapfmt == "gcc") {
  2362. modmap_fmt = CxxModuleMapFormat::Gcc;
  2363. } else if (arg_modmapfmt == "msvc") {
  2364. modmap_fmt = CxxModuleMapFormat::Msvc;
  2365. } else {
  2366. cmSystemTools::Error(
  2367. cmStrCat("-E cmake_ninja_dyndep does not understand the ", arg_modmapfmt,
  2368. " module map format"));
  2369. return false;
  2370. }
  2371. auto module_ext = CxxModuleMapExtension(modmap_fmt);
  2372. // Extend the module map with those provided by this target.
  2373. // We do this after loading the modules provided by linked targets
  2374. // in case we have one of the same name that must be preferred.
  2375. Json::Value target_modules = Json::objectValue;
  2376. for (cmScanDepInfo const& object : objects) {
  2377. for (auto const& p : object.Provides) {
  2378. std::string mod;
  2379. if (!p.CompiledModulePath.empty()) {
  2380. // The scanner provided the path to the module file.
  2381. mod = p.CompiledModulePath;
  2382. if (!cmSystemTools::FileIsFullPath(mod)) {
  2383. // Treat relative to work directory (top of build tree).
  2384. mod = cmSystemTools::CollapseFullPath(mod, dir_top_bld);
  2385. }
  2386. } else {
  2387. // Assume the module file path matches the logical module name.
  2388. std::string safe_logical_name =
  2389. p.LogicalName; // TODO: needs fixing for header units
  2390. cmSystemTools::ReplaceString(safe_logical_name, ":", "-");
  2391. mod = cmStrCat(module_dir, safe_logical_name, module_ext);
  2392. }
  2393. mod_files[p.LogicalName] = AvailableModuleInfo{
  2394. mod,
  2395. false, // Always visible within our own target.
  2396. };
  2397. Json::Value& module_info = target_modules[p.LogicalName] =
  2398. Json::objectValue;
  2399. module_info["bmi"] = mod;
  2400. module_info["is-private"] =
  2401. cmDyndepCollation::IsObjectPrivate(object.PrimaryOutput, export_info);
  2402. }
  2403. }
  2404. cmGeneratedFileStream ddf(arg_dd);
  2405. ddf << "ninja_dyndep_version = 1.0\n";
  2406. {
  2407. CxxModuleLocations locs;
  2408. locs.RootDirectory = ".";
  2409. locs.PathForGenerator = [this](std::string path) -> std::string {
  2410. path = this->ConvertToNinjaPath(path);
  2411. # ifdef _WIN32
  2412. if (this->IsGCCOnWindows()) {
  2413. std::replace(path.begin(), path.end(), '\\', '/');
  2414. }
  2415. # endif
  2416. return path;
  2417. };
  2418. locs.BmiLocationForModule =
  2419. [&mod_files](std::string const& logical) -> CxxBmiLocation {
  2420. auto m = mod_files.find(logical);
  2421. if (m != mod_files.end()) {
  2422. if (m->second.IsPrivate) {
  2423. return CxxBmiLocation::Private();
  2424. }
  2425. return CxxBmiLocation::Known(m->second.BmiPath);
  2426. }
  2427. return CxxBmiLocation::Unknown();
  2428. };
  2429. // Insert information about the current target's modules.
  2430. if (modmap_fmt) {
  2431. auto cycle_modules = CxxModuleUsageSeed(locs, objects, usages);
  2432. if (!cycle_modules.empty()) {
  2433. cmSystemTools::Error(
  2434. cmStrCat("Circular dependency detected in the C++ module import "
  2435. "graph. See modules named: \"",
  2436. cmJoin(cycle_modules, R"(", ")"_s), '"'));
  2437. return false;
  2438. }
  2439. }
  2440. cmNinjaBuild build("dyndep");
  2441. build.Outputs.emplace_back("");
  2442. for (cmScanDepInfo const& object : objects) {
  2443. build.Outputs[0] = this->ConvertToNinjaPath(object.PrimaryOutput);
  2444. build.ImplicitOuts.clear();
  2445. for (auto const& p : object.Provides) {
  2446. build.ImplicitOuts.push_back(
  2447. this->ConvertToNinjaPath(mod_files[p.LogicalName].BmiPath));
  2448. }
  2449. build.ImplicitDeps.clear();
  2450. for (auto const& r : object.Requires) {
  2451. auto mit = mod_files.find(r.LogicalName);
  2452. if (mit != mod_files.end()) {
  2453. build.ImplicitDeps.push_back(
  2454. this->ConvertToNinjaPath(mit->second.BmiPath));
  2455. }
  2456. }
  2457. build.Variables.clear();
  2458. if (!object.Provides.empty()) {
  2459. build.Variables.emplace("restat", "1");
  2460. }
  2461. if (modmap_fmt) {
  2462. auto mm = CxxModuleMapContent(*modmap_fmt, locs, object, usages);
  2463. // XXX(modmap): If changing this path construction, change
  2464. // `cmNinjaTargetGenerator::WriteObjectBuildStatements` to generate the
  2465. // corresponding file path.
  2466. cmGeneratedFileStream mmf(cmStrCat(object.PrimaryOutput, ".modmap"));
  2467. mmf << mm;
  2468. }
  2469. this->WriteBuild(ddf, build);
  2470. }
  2471. }
  2472. Json::Value target_module_info = Json::objectValue;
  2473. target_module_info["modules"] = target_modules;
  2474. auto& target_usages = target_module_info["usages"] = Json::objectValue;
  2475. for (auto const& u : usages.Usage) {
  2476. auto& mod_usage = target_usages[u.first] = Json::arrayValue;
  2477. for (auto const& v : u.second) {
  2478. mod_usage.append(v);
  2479. }
  2480. }
  2481. auto name_for_method = [](LookupMethod method) -> cm::static_string_view {
  2482. switch (method) {
  2483. case LookupMethod::ByName:
  2484. return "by-name"_s;
  2485. case LookupMethod::IncludeAngle:
  2486. return "include-angle"_s;
  2487. case LookupMethod::IncludeQuote:
  2488. return "include-quote"_s;
  2489. }
  2490. assert(false && "unsupported lookup method");
  2491. return ""_s;
  2492. };
  2493. auto& target_references = target_module_info["references"] =
  2494. Json::objectValue;
  2495. for (auto const& r : usages.Reference) {
  2496. auto& mod_ref = target_references[r.first] = Json::objectValue;
  2497. mod_ref["path"] = r.second.Path;
  2498. mod_ref["lookup-method"] = std::string(name_for_method(r.second.Method));
  2499. }
  2500. // Store the map of modules provided by this target in a file for
  2501. // use by dependents that reference this target in linked-target-dirs.
  2502. std::string const target_mods_file = cmStrCat(
  2503. cmSystemTools::GetFilenamePath(arg_dd), '/', arg_lang, "Modules.json");
  2504. cmGeneratedFileStream tmf(target_mods_file);
  2505. tmf << target_module_info;
  2506. cmDyndepMetadataCallbacks cb;
  2507. cb.ModuleFile =
  2508. [mod_files](std::string const& name) -> cm::optional<std::string> {
  2509. auto m = mod_files.find(name);
  2510. if (m != mod_files.end()) {
  2511. return m->second.BmiPath;
  2512. }
  2513. return {};
  2514. };
  2515. return cmDyndepCollation::WriteDyndepMetadata(arg_lang, objects, export_info,
  2516. cb);
  2517. }
  2518. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  2519. std::vector<std::string>::const_iterator argEnd)
  2520. {
  2521. std::vector<std::string> arg_full =
  2522. cmSystemTools::HandleResponseFile(argBeg, argEnd);
  2523. std::string arg_dd;
  2524. std::string arg_lang;
  2525. std::string arg_tdi;
  2526. std::string arg_modmapfmt;
  2527. std::vector<std::string> arg_ddis;
  2528. for (std::string const& arg : arg_full) {
  2529. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  2530. arg_tdi = arg.substr(6);
  2531. } else if (cmHasLiteralPrefix(arg, "--lang=")) {
  2532. arg_lang = arg.substr(7);
  2533. } else if (cmHasLiteralPrefix(arg, "--dd=")) {
  2534. arg_dd = arg.substr(5);
  2535. } else if (cmHasLiteralPrefix(arg, "--modmapfmt=")) {
  2536. arg_modmapfmt = arg.substr(12);
  2537. } else if (!cmHasLiteralPrefix(arg, "--") &&
  2538. cmHasLiteralSuffix(arg, ".ddi")) {
  2539. arg_ddis.push_back(arg);
  2540. } else {
  2541. cmSystemTools::Error(
  2542. cmStrCat("-E cmake_ninja_dyndep unknown argument: ", arg));
  2543. return 1;
  2544. }
  2545. }
  2546. if (arg_tdi.empty()) {
  2547. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --tdi=");
  2548. return 1;
  2549. }
  2550. if (arg_lang.empty()) {
  2551. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --lang=");
  2552. return 1;
  2553. }
  2554. if (arg_dd.empty()) {
  2555. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --dd=");
  2556. return 1;
  2557. }
  2558. Json::Value tdio;
  2559. Json::Value const& tdi = tdio;
  2560. {
  2561. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  2562. Json::Reader reader;
  2563. if (!reader.parse(tdif, tdio, false)) {
  2564. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2565. arg_tdi,
  2566. reader.getFormattedErrorMessages()));
  2567. return 1;
  2568. }
  2569. }
  2570. std::string const dir_cur_bld = tdi["dir-cur-bld"].asString();
  2571. std::string const dir_cur_src = tdi["dir-cur-src"].asString();
  2572. std::string const dir_top_bld = tdi["dir-top-bld"].asString();
  2573. std::string const dir_top_src = tdi["dir-top-src"].asString();
  2574. std::string module_dir = tdi["module-dir"].asString();
  2575. if (!module_dir.empty() && !cmHasLiteralSuffix(module_dir, "/")) {
  2576. module_dir += '/';
  2577. }
  2578. std::vector<std::string> linked_target_dirs;
  2579. Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
  2580. if (tdi_linked_target_dirs.isArray()) {
  2581. for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) {
  2582. linked_target_dirs.push_back(tdi_linked_target_dir.asString());
  2583. }
  2584. }
  2585. std::string const compilerId = tdi["compiler-id"].asString();
  2586. std::string const simulateId = tdi["compiler-simulate-id"].asString();
  2587. std::string const compilerFrontendVariant =
  2588. tdi["compiler-frontend-variant"].asString();
  2589. auto export_info = cmDyndepCollation::ParseExportInfo(tdi);
  2590. cmake cm(cmake::RoleInternal, cmState::Unknown);
  2591. cm.SetHomeDirectory(dir_top_src);
  2592. cm.SetHomeOutputDirectory(dir_top_bld);
  2593. auto ggd = cm.CreateGlobalGenerator("Ninja");
  2594. if (!ggd) {
  2595. return 1;
  2596. }
  2597. cmGlobalNinjaGenerator& gg =
  2598. cm::static_reference_cast<cmGlobalNinjaGenerator>(ggd);
  2599. # ifdef _WIN32
  2600. if (DetectGCCOnWindows(compilerId, simulateId, compilerFrontendVariant)) {
  2601. gg.MarkAsGCCOnWindows();
  2602. }
  2603. # endif
  2604. return gg.WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld,
  2605. arg_dd, arg_ddis, module_dir, linked_target_dirs,
  2606. arg_lang, arg_modmapfmt, *export_info)
  2607. ? 0
  2608. : 1;
  2609. }
  2610. #endif
  2611. bool cmGlobalNinjaGenerator::EnableCrossConfigBuild() const
  2612. {
  2613. return !this->CrossConfigs.empty();
  2614. }
  2615. void cmGlobalNinjaGenerator::AppendDirectoryForConfig(
  2616. const std::string& prefix, const std::string& config,
  2617. const std::string& suffix, std::string& dir)
  2618. {
  2619. if (!config.empty() && this->IsMultiConfig()) {
  2620. dir += cmStrCat(prefix, config, suffix);
  2621. }
  2622. }
  2623. std::set<std::string> cmGlobalNinjaGenerator::GetCrossConfigs(
  2624. const std::string& fileConfig) const
  2625. {
  2626. auto result = this->CrossConfigs;
  2627. result.insert(fileConfig);
  2628. return result;
  2629. }
  2630. bool cmGlobalNinjaGenerator::IsSingleConfigUtility(
  2631. cmGeneratorTarget const* target) const
  2632. {
  2633. return target->GetType() == cmStateEnums::UTILITY &&
  2634. !this->PerConfigUtilityTargets.count(target->GetName());
  2635. }
  2636. const char* cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE =
  2637. "CMakeFiles/common.ninja";
  2638. const char* cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION = ".ninja";
  2639. cmGlobalNinjaMultiGenerator::cmGlobalNinjaMultiGenerator(cmake* cm)
  2640. : cmGlobalNinjaGenerator(cm)
  2641. {
  2642. cm->GetState()->SetIsGeneratorMultiConfig(true);
  2643. cm->GetState()->SetNinjaMulti(true);
  2644. }
  2645. cmDocumentationEntry cmGlobalNinjaMultiGenerator::GetDocumentation()
  2646. {
  2647. return { cmGlobalNinjaMultiGenerator::GetActualName(),
  2648. "Generates build-<Config>.ninja files." };
  2649. }
  2650. std::string cmGlobalNinjaMultiGenerator::ExpandCFGIntDir(
  2651. const std::string& str, const std::string& config) const
  2652. {
  2653. std::string result = str;
  2654. cmSystemTools::ReplaceString(result, this->GetCMakeCFGIntDir(), config);
  2655. return result;
  2656. }
  2657. bool cmGlobalNinjaMultiGenerator::OpenBuildFileStreams()
  2658. {
  2659. if (!this->OpenFileStream(this->CommonFileStream,
  2660. cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE)) {
  2661. return false;
  2662. }
  2663. if (!this->OpenFileStream(this->DefaultFileStream, NINJA_BUILD_FILE)) {
  2664. return false;
  2665. }
  2666. *this->DefaultFileStream << "# Build using rules for '"
  2667. << this->DefaultFileConfig << "'.\n\n"
  2668. << "include "
  2669. << this->NinjaOutputPath(
  2670. GetNinjaImplFilename(this->DefaultFileConfig))
  2671. << "\n\n";
  2672. // Write a comment about this file.
  2673. *this->CommonFileStream
  2674. << "# This file contains build statements common to all "
  2675. "configurations.\n\n";
  2676. auto const& configs =
  2677. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2678. return std::all_of(
  2679. configs.begin(), configs.end(), [this](std::string const& config) -> bool {
  2680. // Open impl file.
  2681. if (!this->OpenFileStream(this->ImplFileStreams[config],
  2682. GetNinjaImplFilename(config))) {
  2683. return false;
  2684. }
  2685. // Write a comment about this file.
  2686. *this->ImplFileStreams[config]
  2687. << "# This file contains build statements specific to the \"" << config
  2688. << "\"\n# configuration.\n\n";
  2689. // Open config file.
  2690. if (!this->OpenFileStream(this->ConfigFileStreams[config],
  2691. GetNinjaConfigFilename(config))) {
  2692. return false;
  2693. }
  2694. // Write a comment about this file.
  2695. *this->ConfigFileStreams[config]
  2696. << "# This file contains aliases specific to the \"" << config
  2697. << "\"\n# configuration.\n\n"
  2698. << "include " << this->NinjaOutputPath(GetNinjaImplFilename(config))
  2699. << "\n\n";
  2700. return true;
  2701. });
  2702. }
  2703. void cmGlobalNinjaMultiGenerator::CloseBuildFileStreams()
  2704. {
  2705. if (this->CommonFileStream) {
  2706. this->CommonFileStream.reset();
  2707. } else {
  2708. cmSystemTools::Error("Common file stream was not open.");
  2709. }
  2710. if (this->DefaultFileStream) {
  2711. this->DefaultFileStream.reset();
  2712. } // No error if it wasn't open
  2713. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  2714. cmMakefile::IncludeEmptyConfig)) {
  2715. if (this->ImplFileStreams[config]) {
  2716. this->ImplFileStreams[config].reset();
  2717. } else {
  2718. cmSystemTools::Error(
  2719. cmStrCat("Impl file stream for \"", config, "\" was not open."));
  2720. }
  2721. if (this->ConfigFileStreams[config]) {
  2722. this->ConfigFileStreams[config].reset();
  2723. } else {
  2724. cmSystemTools::Error(
  2725. cmStrCat("Config file stream for \"", config, "\" was not open."));
  2726. }
  2727. }
  2728. }
  2729. void cmGlobalNinjaMultiGenerator::AppendNinjaFileArgument(
  2730. GeneratedMakeCommand& command, const std::string& config) const
  2731. {
  2732. if (!config.empty()) {
  2733. command.Add("-f");
  2734. command.Add(GetNinjaConfigFilename(config));
  2735. }
  2736. }
  2737. std::string cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(
  2738. const std::string& config)
  2739. {
  2740. return cmStrCat("CMakeFiles/impl-", config,
  2741. cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION);
  2742. }
  2743. std::string cmGlobalNinjaMultiGenerator::GetNinjaConfigFilename(
  2744. const std::string& config)
  2745. {
  2746. return cmStrCat("build-", config,
  2747. cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION);
  2748. }
  2749. void cmGlobalNinjaMultiGenerator::AddRebuildManifestOutputs(
  2750. cmNinjaDeps& outputs) const
  2751. {
  2752. for (auto const& config : this->Makefiles.front()->GetGeneratorConfigs(
  2753. cmMakefile::IncludeEmptyConfig)) {
  2754. outputs.push_back(this->NinjaOutputPath(GetNinjaImplFilename(config)));
  2755. outputs.push_back(this->NinjaOutputPath(GetNinjaConfigFilename(config)));
  2756. }
  2757. if (!this->DefaultFileConfig.empty()) {
  2758. outputs.push_back(this->NinjaOutputPath(NINJA_BUILD_FILE));
  2759. }
  2760. }
  2761. void cmGlobalNinjaMultiGenerator::GetQtAutoGenConfigs(
  2762. std::vector<std::string>& configs) const
  2763. {
  2764. auto allConfigs =
  2765. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2766. configs.insert(configs.end(), cm::cbegin(allConfigs), cm::cend(allConfigs));
  2767. }
  2768. bool cmGlobalNinjaMultiGenerator::InspectConfigTypeVariables()
  2769. {
  2770. cmList configsList{ this->Makefiles.front()->GetDefinition(
  2771. "CMAKE_CONFIGURATION_TYPES") };
  2772. if (configsList.empty()) {
  2773. configsList.emplace_back();
  2774. }
  2775. std::set<std::string> configs(configsList.cbegin(), configsList.cend());
  2776. this->DefaultFileConfig =
  2777. this->Makefiles.front()->GetSafeDefinition("CMAKE_DEFAULT_BUILD_TYPE");
  2778. if (this->DefaultFileConfig.empty()) {
  2779. this->DefaultFileConfig = configsList.front();
  2780. }
  2781. if (!configs.count(this->DefaultFileConfig)) {
  2782. std::ostringstream msg;
  2783. msg << "The configuration specified by "
  2784. << "CMAKE_DEFAULT_BUILD_TYPE (" << this->DefaultFileConfig
  2785. << ") is not present in CMAKE_CONFIGURATION_TYPES";
  2786. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2787. msg.str());
  2788. return false;
  2789. }
  2790. cmList crossConfigsList{ this->Makefiles.front()->GetSafeDefinition(
  2791. "CMAKE_CROSS_CONFIGS") };
  2792. auto crossConfigs = ListSubsetWithAll(configs, configs, crossConfigsList);
  2793. if (!crossConfigs) {
  2794. std::ostringstream msg;
  2795. msg << "CMAKE_CROSS_CONFIGS is not a subset of "
  2796. << "CMAKE_CONFIGURATION_TYPES";
  2797. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2798. msg.str());
  2799. return false;
  2800. }
  2801. this->CrossConfigs = *crossConfigs;
  2802. auto defaultConfigsString =
  2803. this->Makefiles.front()->GetSafeDefinition("CMAKE_DEFAULT_CONFIGS");
  2804. if (defaultConfigsString.empty()) {
  2805. defaultConfigsString = this->DefaultFileConfig;
  2806. }
  2807. if (!defaultConfigsString.empty() &&
  2808. defaultConfigsString != this->DefaultFileConfig &&
  2809. (this->DefaultFileConfig.empty() || this->CrossConfigs.empty())) {
  2810. std::ostringstream msg;
  2811. msg << "CMAKE_DEFAULT_CONFIGS cannot be used without "
  2812. << "CMAKE_DEFAULT_BUILD_TYPE or CMAKE_CROSS_CONFIGS";
  2813. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2814. msg.str());
  2815. return false;
  2816. }
  2817. cmList defaultConfigsList(defaultConfigsString);
  2818. if (!this->DefaultFileConfig.empty()) {
  2819. auto defaultConfigs =
  2820. ListSubsetWithAll(this->GetCrossConfigs(this->DefaultFileConfig),
  2821. this->CrossConfigs, defaultConfigsList);
  2822. if (!defaultConfigs) {
  2823. std::ostringstream msg;
  2824. msg << "CMAKE_DEFAULT_CONFIGS is not a subset of CMAKE_CROSS_CONFIGS";
  2825. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2826. msg.str());
  2827. return false;
  2828. }
  2829. this->DefaultConfigs = *defaultConfigs;
  2830. }
  2831. return true;
  2832. }
  2833. std::string cmGlobalNinjaMultiGenerator::GetDefaultBuildConfig() const
  2834. {
  2835. return "";
  2836. }
  2837. std::string cmGlobalNinjaMultiGenerator::OrderDependsTargetForTarget(
  2838. cmGeneratorTarget const* target, const std::string& config) const
  2839. {
  2840. return cmStrCat("cmake_object_order_depends_target_", target->GetName(), '_',
  2841. cmSystemTools::UpperCase(config));
  2842. }