cmLocalGenerator.cxx 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671
  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 "cmLocalGenerator.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <initializer_list>
  10. #include <iterator>
  11. #include <sstream>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <vector>
  15. #include <cm/memory>
  16. #include <cm/optional>
  17. #include <cm/string_view>
  18. #include <cmext/algorithm>
  19. #include <cmext/string_view>
  20. #include "cmsys/RegularExpression.hxx"
  21. #include "cmAlgorithms.h"
  22. #include "cmComputeLinkInformation.h"
  23. #include "cmCustomCommand.h"
  24. #include "cmCustomCommandGenerator.h"
  25. #include "cmCustomCommandLines.h"
  26. #include "cmCustomCommandTypes.h"
  27. #include "cmGeneratedFileStream.h"
  28. #include "cmGeneratorExpression.h"
  29. #include "cmGeneratorExpressionEvaluationFile.h"
  30. #include "cmGeneratorTarget.h"
  31. #include "cmGlobalGenerator.h"
  32. #include "cmInstallGenerator.h"
  33. #include "cmInstallScriptGenerator.h"
  34. #include "cmInstallTargetGenerator.h"
  35. #include "cmLinkLineComputer.h"
  36. #include "cmLinkLineDeviceComputer.h"
  37. #include "cmMakefile.h"
  38. #include "cmRange.h"
  39. #include "cmRulePlaceholderExpander.h"
  40. #include "cmSourceFile.h"
  41. #include "cmSourceFileLocation.h"
  42. #include "cmSourceFileLocationKind.h"
  43. #include "cmStandardLevelResolver.h"
  44. #include "cmState.h"
  45. #include "cmStateDirectory.h"
  46. #include "cmStateTypes.h"
  47. #include "cmStringAlgorithms.h"
  48. #include "cmSystemTools.h"
  49. #include "cmTarget.h"
  50. #include "cmTestGenerator.h"
  51. #include "cmValue.h"
  52. #include "cmVersion.h"
  53. #include "cmake.h"
  54. #if !defined(CMAKE_BOOTSTRAP)
  55. # define CM_LG_ENCODE_OBJECT_NAMES
  56. # include "cmCryptoHash.h"
  57. #endif
  58. #if defined(__HAIKU__)
  59. # include <FindDirectory.h>
  60. # include <StorageDefs.h>
  61. #endif
  62. // List of variables that are replaced when
  63. // rules are expanced. These variables are
  64. // replaced in the form <var> with GetSafeDefinition(var).
  65. // ${LANG} is replaced in the variable first with all enabled
  66. // languages.
  67. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  68. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  69. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  70. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  71. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  72. "CMAKE_${LANG}_LINK_FLAGS",
  73. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  74. "CMAKE_${LANG}_ARCHIVE",
  75. "CMAKE_AR",
  76. "CMAKE_CURRENT_SOURCE_DIR",
  77. "CMAKE_CURRENT_BINARY_DIR",
  78. "CMAKE_RANLIB",
  79. "CMAKE_LINKER",
  80. "CMAKE_MT",
  81. "CMAKE_CUDA_HOST_COMPILER",
  82. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  83. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  84. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  85. : cmOutputConverter(makefile->GetStateSnapshot())
  86. , DirectoryBacktrace(makefile->GetBacktrace())
  87. {
  88. this->GlobalGenerator = gg;
  89. this->Makefile = makefile;
  90. this->AliasTargets = makefile->GetAliasTargets();
  91. this->EmitUniversalBinaryFlags = true;
  92. this->BackwardsCompatibility = 0;
  93. this->BackwardsCompatibilityFinal = false;
  94. this->ComputeObjectMaxPath();
  95. // Canonicalize entries of the CPATH environment variable the same
  96. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  97. {
  98. std::vector<std::string> cpath;
  99. cmSystemTools::GetPath(cpath, "CPATH");
  100. for (std::string const& cp : cpath) {
  101. if (cmSystemTools::FileIsFullPath(cp)) {
  102. this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
  103. }
  104. }
  105. }
  106. std::vector<std::string> enabledLanguages =
  107. this->GetState()->GetEnabledLanguages();
  108. if (cmValue sysrootCompile =
  109. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  110. this->CompilerSysroot = *sysrootCompile;
  111. } else {
  112. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  113. }
  114. if (cmValue sysrootLink =
  115. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  116. this->LinkerSysroot = *sysrootLink;
  117. } else {
  118. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  119. }
  120. if (cmValue appleArchSysroots =
  121. this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
  122. std::string const& appleArchs =
  123. this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  124. std::vector<std::string> archs;
  125. std::vector<std::string> sysroots;
  126. cmExpandList(appleArchs, archs);
  127. cmExpandList(*appleArchSysroots, sysroots, true);
  128. if (archs.size() == sysroots.size()) {
  129. for (size_t i = 0; i < archs.size(); ++i) {
  130. this->AppleArchSysroots[archs[i]] = sysroots[i];
  131. }
  132. } else {
  133. std::string const e =
  134. cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n ", *appleArchSysroots,
  135. "\n"
  136. "is not the same length as CMAKE_OSX_ARCHITECTURES:\n ",
  137. appleArchs);
  138. this->IssueMessage(MessageType::FATAL_ERROR, e);
  139. }
  140. }
  141. for (std::string const& lang : enabledLanguages) {
  142. if (lang == "NONE") {
  143. continue;
  144. }
  145. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  146. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  147. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  148. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  149. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  150. std::string const& compilerOptionTarget =
  151. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  152. std::string const& compilerExternalToolchain =
  153. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  154. std::string const& compilerOptionExternalToolchain =
  155. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  156. std::string const& compilerOptionSysroot =
  157. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  158. this->VariableMappings[compilerArg1] =
  159. this->Makefile->GetSafeDefinition(compilerArg1);
  160. this->VariableMappings[compilerTarget] =
  161. this->Makefile->GetSafeDefinition(compilerTarget);
  162. this->VariableMappings[compilerOptionTarget] =
  163. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  164. this->VariableMappings[compilerExternalToolchain] =
  165. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  166. this->VariableMappings[compilerOptionExternalToolchain] =
  167. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  168. this->VariableMappings[compilerOptionSysroot] =
  169. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  170. for (std::string replaceVar : ruleReplaceVars) {
  171. if (replaceVar.find("${LANG}") != std::string::npos) {
  172. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  173. }
  174. this->VariableMappings[replaceVar] =
  175. this->Makefile->GetSafeDefinition(replaceVar);
  176. }
  177. }
  178. }
  179. cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
  180. const
  181. {
  182. return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  183. this->CompilerSysroot,
  184. this->LinkerSysroot);
  185. }
  186. cmLocalGenerator::~cmLocalGenerator() = default;
  187. void cmLocalGenerator::IssueMessage(MessageType t,
  188. std::string const& text) const
  189. {
  190. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  191. }
  192. void cmLocalGenerator::ComputeObjectMaxPath()
  193. {
  194. // Choose a maximum object file name length.
  195. #if defined(_WIN32) || defined(__CYGWIN__)
  196. this->ObjectPathMax = 250;
  197. #else
  198. this->ObjectPathMax = 1000;
  199. #endif
  200. cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  201. if (cmNonempty(plen)) {
  202. unsigned int pmax;
  203. if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
  204. if (pmax >= 128) {
  205. this->ObjectPathMax = pmax;
  206. } else {
  207. std::ostringstream w;
  208. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  209. << ", which is less than the minimum of 128. "
  210. << "The value will be ignored.";
  211. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  212. }
  213. } else {
  214. std::ostringstream w;
  215. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
  216. << "\", which fails to parse as a positive integer. "
  217. << "The value will be ignored.";
  218. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  219. }
  220. }
  221. this->ObjectMaxPathViolations.clear();
  222. }
  223. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  224. const std::string& config,
  225. const std::string& lang,
  226. const cmGeneratorTarget* target)
  227. {
  228. if (!target) {
  229. return;
  230. }
  231. std::stable_sort(
  232. includeDirs.begin(), includeDirs.end(),
  233. [&target, &config, &lang](std::string const& a, std::string const& b) {
  234. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  235. target->IsSystemIncludeDirectory(b, config, lang);
  236. });
  237. }
  238. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  239. const std::string& config,
  240. const std::string& lang,
  241. const cmGeneratorTarget* target)
  242. {
  243. if (!target) {
  244. return;
  245. }
  246. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  247. [target, &config, &lang](BT<std::string> const& a,
  248. BT<std::string> const& b) {
  249. return !target->IsSystemIncludeDirectory(a.Value, config,
  250. lang) &&
  251. target->IsSystemIncludeDirectory(b.Value, config, lang);
  252. });
  253. }
  254. void cmLocalGenerator::TraceDependencies() const
  255. {
  256. // Generate the rule files for each target.
  257. const auto& targets = this->GetGeneratorTargets();
  258. for (const auto& target : targets) {
  259. if (!target->IsInBuildSystem()) {
  260. continue;
  261. }
  262. target->TraceDependencies();
  263. }
  264. }
  265. void cmLocalGenerator::GenerateTestFiles()
  266. {
  267. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  268. return;
  269. }
  270. // Compute the set of configurations.
  271. std::vector<std::string> configurationTypes =
  272. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  273. std::string config = this->Makefile->GetDefaultConfiguration();
  274. std::string file =
  275. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  276. "/CTestTestfile.cmake");
  277. cmGeneratedFileStream fout(file);
  278. fout.SetCopyIfDifferent(true);
  279. fout << "# CMake generated Testfile for \n"
  280. "# Source directory: "
  281. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  282. << "\n"
  283. "# Build directory: "
  284. << this->StateSnapshot.GetDirectory().GetCurrentBinary()
  285. << "\n"
  286. "# \n"
  287. "# This file includes the relevant testing commands "
  288. "required for \n"
  289. "# testing this directory and lists subdirectories to "
  290. "be tested as well.\n";
  291. std::string resourceSpecFile =
  292. this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
  293. if (!resourceSpecFile.empty()) {
  294. fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
  295. }
  296. cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  297. if (testIncludeFile) {
  298. fout << "include(\"" << *testIncludeFile << "\")\n";
  299. }
  300. cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  301. if (testIncludeFiles) {
  302. std::vector<std::string> includesList = cmExpandedList(*testIncludeFiles);
  303. for (std::string const& i : includesList) {
  304. fout << "include(\"" << i << "\")\n";
  305. }
  306. }
  307. // Ask each test generator to write its code.
  308. for (const auto& tester : this->Makefile->GetTestGenerators()) {
  309. tester->Compute(this);
  310. tester->Generate(fout, config, configurationTypes);
  311. }
  312. using vec_t = std::vector<cmStateSnapshot>;
  313. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  314. for (cmStateSnapshot const& i : children) {
  315. // TODO: Use add_subdirectory instead?
  316. std::string outP = i.GetDirectory().GetCurrentBinary();
  317. outP = this->MaybeRelativeToCurBinDir(outP);
  318. outP = cmOutputConverter::EscapeForCMake(outP);
  319. fout << "subdirs(" << outP << ")\n";
  320. }
  321. // Add directory labels property
  322. cmValue directoryLabels =
  323. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  324. cmValue labels = this->Makefile->GetProperty("LABELS");
  325. if (labels || directoryLabels) {
  326. fout << "set_directory_properties(PROPERTIES LABELS ";
  327. if (labels) {
  328. fout << cmOutputConverter::EscapeForCMake(*labels);
  329. }
  330. if (labels && directoryLabels) {
  331. fout << ";";
  332. }
  333. if (directoryLabels) {
  334. fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
  335. }
  336. fout << ")\n";
  337. }
  338. }
  339. void cmLocalGenerator::CreateEvaluationFileOutputs()
  340. {
  341. std::vector<std::string> const& configs =
  342. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  343. for (std::string const& c : configs) {
  344. this->CreateEvaluationFileOutputs(c);
  345. }
  346. }
  347. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  348. {
  349. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  350. geef->CreateOutputFile(this, config);
  351. }
  352. }
  353. void cmLocalGenerator::ProcessEvaluationFiles(
  354. std::vector<std::string>& generatedFiles)
  355. {
  356. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  357. geef->Generate(this);
  358. if (cmSystemTools::GetFatalErrorOccurred()) {
  359. return;
  360. }
  361. std::vector<std::string> files = geef->GetFiles();
  362. std::sort(files.begin(), files.end());
  363. std::vector<std::string> intersection;
  364. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  365. generatedFiles.end(),
  366. std::back_inserter(intersection));
  367. if (!intersection.empty()) {
  368. cmSystemTools::Error("Files to be generated by multiple different "
  369. "commands: " +
  370. cmWrap('"', intersection, '"', " "));
  371. return;
  372. }
  373. cm::append(generatedFiles, files);
  374. std::inplace_merge(generatedFiles.begin(),
  375. generatedFiles.end() - files.size(),
  376. generatedFiles.end());
  377. }
  378. }
  379. void cmLocalGenerator::GenerateInstallRules()
  380. {
  381. // Compute the install prefix.
  382. cmValue installPrefix =
  383. this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  384. std::string prefix = *installPrefix;
  385. #if defined(_WIN32) && !defined(__CYGWIN__)
  386. if (!installPrefix) {
  387. if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
  388. prefix = "C:";
  389. }
  390. cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  391. if (cmNonempty(project_name)) {
  392. prefix += "/Program Files/";
  393. prefix += *project_name;
  394. } else {
  395. prefix += "/InstalledCMakeProject";
  396. }
  397. }
  398. #elif defined(__HAIKU__)
  399. char dir[B_PATH_NAME_LENGTH];
  400. if (!installPrefix) {
  401. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  402. B_OK) {
  403. prefix = dir;
  404. } else {
  405. prefix = "/boot/system";
  406. }
  407. }
  408. #else
  409. if (!installPrefix) {
  410. prefix = "/usr/local";
  411. }
  412. #endif
  413. if (cmValue stagingPrefix =
  414. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  415. prefix = *stagingPrefix;
  416. }
  417. // Compute the set of configurations.
  418. std::vector<std::string> configurationTypes =
  419. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  420. std::string config = this->Makefile->GetDefaultConfiguration();
  421. // Choose a default install configuration.
  422. std::string default_config = config;
  423. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  424. "DEBUG", nullptr };
  425. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  426. for (std::string const& configurationType : configurationTypes) {
  427. if (cmSystemTools::UpperCase(configurationType) == *c) {
  428. default_config = configurationType;
  429. }
  430. }
  431. }
  432. if (default_config.empty() && !configurationTypes.empty()) {
  433. default_config = configurationTypes[0];
  434. }
  435. // Create the install script file.
  436. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  437. std::string homedir = this->GetState()->GetBinaryDirectory();
  438. int toplevel_install = 0;
  439. if (file == homedir) {
  440. toplevel_install = 1;
  441. }
  442. file += "/cmake_install.cmake";
  443. cmGeneratedFileStream fout(file);
  444. fout.SetCopyIfDifferent(true);
  445. // Write the header.
  446. /* clang-format off */
  447. fout << "# Install script for directory: "
  448. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  449. << "\n\n"
  450. "# Set the install prefix\n"
  451. "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
  452. " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
  453. "endif()\n"
  454. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  455. << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
  456. /* clang-format on */
  457. // Write support code for generating per-configuration install rules.
  458. /* clang-format off */
  459. fout <<
  460. "# Set the install configuration name.\n"
  461. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  462. " if(BUILD_TYPE)\n"
  463. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  464. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  465. " else()\n"
  466. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  467. " endif()\n"
  468. " message(STATUS \"Install configuration: "
  469. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  470. "endif()\n"
  471. "\n";
  472. /* clang-format on */
  473. // Write support code for dealing with component-specific installs.
  474. /* clang-format off */
  475. fout <<
  476. "# Set the component getting installed.\n"
  477. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  478. " if(COMPONENT)\n"
  479. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  480. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  481. " else()\n"
  482. " set(CMAKE_INSTALL_COMPONENT)\n"
  483. " endif()\n"
  484. "endif()\n"
  485. "\n";
  486. /* clang-format on */
  487. // Copy user-specified install options to the install code.
  488. if (cmValue so_no_exe =
  489. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  490. /* clang-format off */
  491. fout <<
  492. "# Install shared libraries without execute permission?\n"
  493. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  494. " set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
  495. "endif()\n"
  496. "\n";
  497. /* clang-format on */
  498. }
  499. // Copy cmake cross compile state to install code.
  500. if (cmValue crosscompiling =
  501. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  502. /* clang-format off */
  503. fout <<
  504. "# Is this installation the result of a crosscompile?\n"
  505. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  506. " set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
  507. "endif()\n"
  508. "\n";
  509. /* clang-format on */
  510. }
  511. // Write default directory permissions.
  512. if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
  513. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  514. /* clang-format off */
  515. fout <<
  516. "# Set default install directory permissions.\n"
  517. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  518. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  519. << *defaultDirPermissions << "\")\n"
  520. "endif()\n"
  521. "\n";
  522. /* clang-format on */
  523. }
  524. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
  525. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  526. // has same platform variable as when running cmake
  527. if (cmValue platform = this->Makefile->GetDefinition(
  528. "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
  529. /* clang-format off */
  530. fout <<
  531. "# Set default install directory permissions.\n"
  532. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
  533. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
  534. << *platform << "\")\n"
  535. "endif()\n"
  536. "\n";
  537. /* clang-format on */
  538. }
  539. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
  540. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  541. // has same tool selected as when running cmake
  542. if (cmValue command =
  543. this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
  544. /* clang-format off */
  545. fout <<
  546. "# Set default install directory permissions.\n"
  547. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
  548. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
  549. << *command << "\")\n"
  550. "endif()\n"
  551. "\n";
  552. /* clang-format on */
  553. }
  554. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
  555. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  556. // has same path to the tool as when running cmake
  557. if (cmValue command = this->Makefile->GetDefinition(
  558. "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
  559. /* clang-format off */
  560. fout <<
  561. "# Set default install directory permissions.\n"
  562. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
  563. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
  564. << *command << "\")\n"
  565. "endif()\n"
  566. "\n";
  567. /* clang-format on */
  568. }
  569. // Write out CMAKE_OBJDUMP so that installed code that uses
  570. // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
  571. // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
  572. // logic to fallback to CMAKE_OBJDUMP when `objdump` is
  573. // not on the path
  574. if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
  575. /* clang-format off */
  576. fout <<
  577. "# Set default install directory permissions.\n"
  578. "if(NOT DEFINED CMAKE_OBJDUMP)\n"
  579. " set(CMAKE_OBJDUMP \""
  580. << *command << "\")\n"
  581. "endif()\n"
  582. "\n";
  583. /* clang-format on */
  584. }
  585. this->AddGeneratorSpecificInstallSetup(fout);
  586. // Ask each install generator to write its code.
  587. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  588. auto const& installers = this->Makefile->GetInstallGenerators();
  589. bool haveSubdirectoryInstall = false;
  590. bool haveInstallAfterSubdirectory = false;
  591. if (status == cmPolicies::WARN) {
  592. for (const auto& installer : installers) {
  593. installer->CheckCMP0082(haveSubdirectoryInstall,
  594. haveInstallAfterSubdirectory);
  595. installer->Generate(fout, config, configurationTypes);
  596. }
  597. } else {
  598. for (const auto& installer : installers) {
  599. installer->Generate(fout, config, configurationTypes);
  600. }
  601. }
  602. // Write rules from old-style specification stored in targets.
  603. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  604. // Include install scripts from subdirectories.
  605. switch (status) {
  606. case cmPolicies::WARN:
  607. if (haveInstallAfterSubdirectory &&
  608. this->Makefile->PolicyOptionalWarningEnabled(
  609. "CMAKE_POLICY_WARNING_CMP0082")) {
  610. std::ostringstream e;
  611. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  612. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  613. }
  614. CM_FALLTHROUGH;
  615. case cmPolicies::OLD: {
  616. std::vector<cmStateSnapshot> children =
  617. this->Makefile->GetStateSnapshot().GetChildren();
  618. if (!children.empty()) {
  619. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  620. fout << " # Include the install script for each subdirectory.\n";
  621. for (cmStateSnapshot const& c : children) {
  622. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  623. std::string odir = c.GetDirectory().GetCurrentBinary();
  624. cmSystemTools::ConvertToUnixSlashes(odir);
  625. fout << " include(\"" << odir << "/cmake_install.cmake\")\n";
  626. }
  627. }
  628. fout << "\n";
  629. fout << "endif()\n\n";
  630. }
  631. } break;
  632. case cmPolicies::REQUIRED_IF_USED:
  633. case cmPolicies::REQUIRED_ALWAYS:
  634. case cmPolicies::NEW:
  635. // NEW behavior is handled in
  636. // cmInstallSubdirectoryGenerator::GenerateScript()
  637. break;
  638. }
  639. // Record the install manifest.
  640. if (toplevel_install) {
  641. /* clang-format off */
  642. fout <<
  643. "if(CMAKE_INSTALL_COMPONENT)\n"
  644. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  645. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  646. "else()\n"
  647. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  648. "endif()\n"
  649. "\n"
  650. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  651. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  652. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  653. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  654. /* clang-format on */
  655. }
  656. }
  657. void cmLocalGenerator::AddGeneratorTarget(
  658. std::unique_ptr<cmGeneratorTarget> gt)
  659. {
  660. cmGeneratorTarget* gt_ptr = gt.get();
  661. this->GeneratorTargets.push_back(std::move(gt));
  662. this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
  663. this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
  664. }
  665. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  666. {
  667. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  668. this->GlobalGenerator->IndexGeneratorTarget(gt);
  669. }
  670. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
  671. std::unique_ptr<cmGeneratorTarget> gt)
  672. {
  673. this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
  674. }
  675. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  676. const std::string& name) const
  677. {
  678. auto ti = this->GeneratorTargetSearchIndex.find(name);
  679. if (ti != this->GeneratorTargetSearchIndex.end()) {
  680. return ti->second;
  681. }
  682. return nullptr;
  683. }
  684. void cmLocalGenerator::ComputeTargetManifest()
  685. {
  686. // Collect the set of configuration types.
  687. std::vector<std::string> configNames =
  688. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  689. // Add our targets to the manifest for each configuration.
  690. const auto& targets = this->GetGeneratorTargets();
  691. for (const auto& target : targets) {
  692. if (!target->IsInBuildSystem()) {
  693. continue;
  694. }
  695. for (std::string const& c : configNames) {
  696. target->ComputeTargetManifest(c);
  697. }
  698. }
  699. }
  700. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  701. {
  702. // Collect the set of configuration types.
  703. std::vector<std::string> configNames =
  704. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  705. using LanguagePair = std::pair<std::string, std::string>;
  706. std::vector<LanguagePair> pairedLanguages{
  707. { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
  708. };
  709. std::set<LanguagePair> inferredEnabledLanguages;
  710. for (auto const& lang : pairedLanguages) {
  711. if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
  712. inferredEnabledLanguages.insert(lang);
  713. }
  714. }
  715. // Process compile features of all targets.
  716. const auto& targets = this->GetGeneratorTargets();
  717. for (const auto& target : targets) {
  718. for (std::string const& c : configNames) {
  719. if (!target->ComputeCompileFeatures(c)) {
  720. return false;
  721. }
  722. }
  723. // Now that C/C++ _STANDARD values have been computed
  724. // set the values to ObjC/ObjCXX _STANDARD variables
  725. if (target->CanCompileSources()) {
  726. for (std::string const& c : configNames) {
  727. target->ComputeCompileFeatures(c, inferredEnabledLanguages);
  728. }
  729. }
  730. }
  731. return true;
  732. }
  733. bool cmLocalGenerator::IsRootMakefile() const
  734. {
  735. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  736. }
  737. cmState* cmLocalGenerator::GetState() const
  738. {
  739. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  740. }
  741. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  742. {
  743. return this->Makefile->GetStateSnapshot();
  744. }
  745. std::string cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  746. const std::string& prop,
  747. const std::string& config)
  748. {
  749. cmValue value = this->Makefile->GetProperty(prop);
  750. if (target) {
  751. value = target->GetProperty(prop);
  752. }
  753. if (value) {
  754. return cmGeneratorExpression::Evaluate(*value, this, config, target);
  755. }
  756. return "";
  757. }
  758. std::string cmLocalGenerator::ConvertToIncludeReference(
  759. std::string const& path, OutputFormat format)
  760. {
  761. return this->ConvertToOutputForExisting(path, format);
  762. }
  763. std::string cmLocalGenerator::GetIncludeFlags(
  764. std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
  765. std::string const& lang, std::string const& config, bool forResponseFile)
  766. {
  767. if (lang.empty()) {
  768. return "";
  769. }
  770. std::vector<std::string> includes = includeDirs;
  771. MoveSystemIncludesToEnd(includes, config, lang, target);
  772. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  773. std::ostringstream includeFlags;
  774. std::string const& includeFlag =
  775. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  776. bool quotePaths = false;
  777. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  778. quotePaths = true;
  779. }
  780. std::string sep = " ";
  781. bool repeatFlag = true;
  782. // should the include flag be repeated like ie. -IA -IB
  783. if (cmValue incSep = this->Makefile->GetDefinition(
  784. cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
  785. // if there is a separator then the flag is not repeated but is only
  786. // given once i.e. -classpath a:b:c
  787. sep = *incSep;
  788. repeatFlag = false;
  789. }
  790. // Support special system include flag if it is available and the
  791. // normal flag is repeated for each directory.
  792. cmValue sysIncludeFlag = nullptr;
  793. cmValue sysIncludeFlagWarning = nullptr;
  794. if (repeatFlag) {
  795. sysIncludeFlag = this->Makefile->GetDefinition(
  796. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  797. sysIncludeFlagWarning = this->Makefile->GetDefinition(
  798. cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
  799. }
  800. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  801. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  802. cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
  803. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  804. bool flagUsed = false;
  805. bool sysIncludeFlagUsed = false;
  806. std::set<std::string> emitted;
  807. #ifdef __APPLE__
  808. emitted.insert("/System/Library/Frameworks");
  809. #endif
  810. for (std::string const& i : includes) {
  811. if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
  812. cmSystemTools::IsPathToFramework(i)) {
  813. std::string const frameworkDir =
  814. cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
  815. if (emitted.insert(frameworkDir).second) {
  816. if (sysFwSearchFlag && target &&
  817. target->IsSystemIncludeDirectory(i, config, lang)) {
  818. includeFlags << *sysFwSearchFlag;
  819. } else {
  820. includeFlags << *fwSearchFlag;
  821. }
  822. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  823. << " ";
  824. }
  825. continue;
  826. }
  827. if (!flagUsed || repeatFlag) {
  828. if (sysIncludeFlag && target &&
  829. target->IsSystemIncludeDirectory(i, config, lang)) {
  830. includeFlags << *sysIncludeFlag;
  831. sysIncludeFlagUsed = true;
  832. } else {
  833. includeFlags << includeFlag;
  834. }
  835. flagUsed = true;
  836. }
  837. std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
  838. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  839. includeFlags << "\"";
  840. }
  841. includeFlags << includePath;
  842. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  843. includeFlags << "\"";
  844. }
  845. includeFlags << sep;
  846. }
  847. if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
  848. includeFlags << *sysIncludeFlagWarning;
  849. }
  850. std::string flags = includeFlags.str();
  851. // remove trailing separators
  852. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  853. flags.back() = ' ';
  854. }
  855. return cmTrimWhitespace(flags);
  856. }
  857. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  858. cmGeneratorTarget* target,
  859. const std::string& lang,
  860. const std::string& config)
  861. {
  862. std::vector<BT<std::string>> tmpFlags;
  863. this->AddCompileOptions(tmpFlags, target, lang, config);
  864. this->AppendFlags(flags, tmpFlags);
  865. }
  866. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  867. cmGeneratorTarget* target,
  868. const std::string& lang,
  869. const std::string& config)
  870. {
  871. std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
  872. if (cmValue langFlagRegexStr =
  873. this->Makefile->GetDefinition(langFlagRegexVar)) {
  874. // Filter flags acceptable to this language.
  875. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  876. std::vector<std::string> opts;
  877. cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
  878. // Re-escape these flags since COMPILE_FLAGS were already parsed
  879. // as a command line above.
  880. std::string compileOpts;
  881. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
  882. if (!compileOpts.empty()) {
  883. flags.emplace_back(std::move(compileOpts));
  884. }
  885. }
  886. std::vector<BT<std::string>> targetCompileOpts =
  887. target->GetCompileOptions(config, lang);
  888. // COMPILE_OPTIONS are escaped.
  889. this->AppendCompileOptions(flags, targetCompileOpts,
  890. langFlagRegexStr->c_str());
  891. } else {
  892. // Use all flags.
  893. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  894. // COMPILE_FLAGS are not escaped for historical reasons.
  895. std::string compileFlags;
  896. this->AppendFlags(compileFlags, *targetFlags);
  897. if (!compileFlags.empty()) {
  898. flags.emplace_back(std::move(compileFlags));
  899. }
  900. }
  901. std::vector<BT<std::string>> targetCompileOpts =
  902. target->GetCompileOptions(config, lang);
  903. // COMPILE_OPTIONS are escaped.
  904. this->AppendCompileOptions(flags, targetCompileOpts);
  905. }
  906. cmStandardLevelResolver standardResolver(this->Makefile);
  907. for (auto const& it : target->GetMaxLanguageStandards()) {
  908. cmValue standard = target->GetLanguageStandard(it.first, config);
  909. if (!standard) {
  910. continue;
  911. }
  912. if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
  913. std::ostringstream e;
  914. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  915. << "\" was evaluated when computing the link "
  916. "implementation, and the \""
  917. << it.first << "_STANDARD\" was \"" << it.second
  918. << "\" for that computation. Computing the "
  919. "COMPILE_FEATURES based on the link implementation resulted in a "
  920. "higher \""
  921. << it.first << "_STANDARD\" \"" << *standard
  922. << "\". "
  923. "This is not permitted. The COMPILE_FEATURES may not both depend "
  924. "on "
  925. "and be depended on by the link implementation.\n";
  926. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  927. return;
  928. }
  929. }
  930. // Add Warning as errors flags
  931. if (!this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
  932. const cmValue wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
  933. const cmValue wErrorOpts = this->Makefile->GetDefinition(
  934. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
  935. if (wError.IsOn() && wErrorOpts.IsSet()) {
  936. std::string wErrorFlags;
  937. this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
  938. if (!wErrorFlags.empty()) {
  939. flags.emplace_back(std::move(wErrorFlags));
  940. }
  941. }
  942. }
  943. // Add compile flag for the MSVC compiler only.
  944. cmMakefile* mf = this->GetMakefile();
  945. if (cmValue jmc =
  946. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  947. // Handle Just My Code debugging flags, /JMC.
  948. // If the target is a Managed C++ one, /JMC is not compatible.
  949. if (target->GetManagedType(config) !=
  950. cmGeneratorTarget::ManagedType::Managed) {
  951. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  952. // to ON
  953. if (cmValue jmcExprGen =
  954. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  955. std::string isJMCEnabled =
  956. cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
  957. if (cmIsOn(isJMCEnabled)) {
  958. std::vector<std::string> optVec = cmExpandedList(*jmc);
  959. std::string jmcFlags;
  960. this->AppendCompileOptions(jmcFlags, optVec);
  961. if (!jmcFlags.empty()) {
  962. flags.emplace_back(std::move(jmcFlags));
  963. }
  964. }
  965. }
  966. }
  967. }
  968. }
  969. cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
  970. const std::string& target, cmCustomCommandType type,
  971. std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
  972. {
  973. cmTarget* t = this->Makefile->GetCustomCommandTarget(
  974. target, objLibCommands, this->DirectoryBacktrace);
  975. if (!t) {
  976. return nullptr;
  977. }
  978. cc->SetBacktrace(this->DirectoryBacktrace);
  979. detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
  980. std::move(cc));
  981. return t;
  982. }
  983. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  984. std::unique_ptr<cmCustomCommand> cc, bool replace)
  985. {
  986. // Make sure there is at least one output.
  987. if (cc->GetOutputs().empty()) {
  988. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  989. return nullptr;
  990. }
  991. cc->SetBacktrace(this->DirectoryBacktrace);
  992. return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
  993. std::move(cc), replace);
  994. }
  995. cmTarget* cmLocalGenerator::AddUtilityCommand(
  996. const std::string& utilityName, bool excludeFromAll,
  997. std::unique_ptr<cmCustomCommand> cc)
  998. {
  999. cmTarget* target =
  1000. this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
  1001. target->SetIsGeneratorProvided(true);
  1002. if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
  1003. return target;
  1004. }
  1005. cc->SetBacktrace(this->DirectoryBacktrace);
  1006. detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
  1007. std::move(cc));
  1008. return target;
  1009. }
  1010. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1011. cmGeneratorTarget const* target, std::string const& lang,
  1012. std::string const& config, bool stripImplicitDirs,
  1013. bool appendAllImplicitDirs) const
  1014. {
  1015. std::vector<BT<std::string>> result;
  1016. // Do not repeat an include path.
  1017. std::set<std::string> emitted;
  1018. auto emitDir = [&result, &emitted](std::string const& dir) {
  1019. if (emitted.insert(dir).second) {
  1020. result.emplace_back(dir);
  1021. }
  1022. };
  1023. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  1024. if (emitted.insert(dir.Value).second) {
  1025. result.emplace_back(dir);
  1026. }
  1027. };
  1028. // When automatic include directories are requested for a build then
  1029. // include the source and binary directories at the beginning of the
  1030. // include path to approximate include file behavior for an
  1031. // in-source build. This does not account for the case of a source
  1032. // file in a subdirectory of the current source directory but we
  1033. // cannot fix this because not all native build tools support
  1034. // per-source-file include paths.
  1035. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  1036. // Current binary directory
  1037. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  1038. // Current source directory
  1039. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  1040. }
  1041. if (!target) {
  1042. return result;
  1043. }
  1044. // Standard include directories to be added unconditionally at the end.
  1045. // These are intended to simulate additional implicit include directories.
  1046. std::vector<std::string> userStandardDirs;
  1047. {
  1048. std::string const value = this->Makefile->GetSafeDefinition(
  1049. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  1050. cmExpandList(value, userStandardDirs);
  1051. for (std::string& usd : userStandardDirs) {
  1052. cmSystemTools::ConvertToUnixSlashes(usd);
  1053. }
  1054. }
  1055. // Implicit include directories
  1056. std::vector<std::string> implicitDirs;
  1057. std::set<std::string> implicitSet;
  1058. // Include directories to be excluded as if they were implicit.
  1059. std::set<std::string> implicitExclude;
  1060. {
  1061. // Raw list of implicit include directories
  1062. // Start with "standard" directories that we unconditionally add below.
  1063. std::vector<std::string> impDirVec = userStandardDirs;
  1064. // Load implicit include directories for this language.
  1065. // We ignore this for Fortran because:
  1066. // * There are no standard library headers to avoid overriding.
  1067. // * Compilers like gfortran do not search their own implicit include
  1068. // directories for modules ('.mod' files).
  1069. if (lang != "Fortran") {
  1070. size_t const impDirVecOldSize = impDirVec.size();
  1071. if (this->Makefile->GetDefExpandList(
  1072. cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES"),
  1073. impDirVec)) {
  1074. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  1075. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  1076. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  1077. }
  1078. }
  1079. }
  1080. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  1081. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  1082. // variables are now computed. On macOS the /usr/include directory is
  1083. // inside the platform SDK so the computed value does not contain it
  1084. // directly. In this case adding -I/usr/include can hide SDK headers so we
  1085. // must still exclude it.
  1086. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  1087. !cm::contains(impDirVec, "/usr/include") &&
  1088. std::find_if(impDirVec.begin(), impDirVec.end(),
  1089. [](std::string const& d) {
  1090. return cmHasLiteralSuffix(d, "/usr/include");
  1091. }) != impDirVec.end()) {
  1092. // Only exclude this hard coded path for backwards compatibility.
  1093. implicitExclude.emplace("/usr/include");
  1094. }
  1095. for (std::string const& i : impDirVec) {
  1096. if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
  1097. implicitDirs.emplace_back(i);
  1098. }
  1099. }
  1100. }
  1101. bool const isCorCxx = (lang == "C" || lang == "CXX");
  1102. // Resolve symlinks in CPATH for comparison with resolved include paths.
  1103. // We do this here instead of when EnvCPATH is populated in case symlinks
  1104. // on disk have changed in the meantime.
  1105. std::set<std::string> resolvedEnvCPATH;
  1106. if (isCorCxx) {
  1107. for (std::string const& i : this->EnvCPATH) {
  1108. resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
  1109. }
  1110. }
  1111. // Checks if this is not an excluded (implicit) include directory.
  1112. auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
  1113. isCorCxx](std::string const& dir) -> bool {
  1114. std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
  1115. return
  1116. // Do not exclude directories that are not in any excluded set.
  1117. !(cm::contains(implicitSet, real_dir) ||
  1118. cm::contains(implicitExclude, dir))
  1119. // Do not exclude entries of the CPATH environment variable even though
  1120. // they are implicitly searched by the compiler. They are meant to be
  1121. // user-specified directories that can be re-ordered or converted to
  1122. // -isystem without breaking real compiler builtin headers.
  1123. || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
  1124. };
  1125. // Get the target-specific include directories.
  1126. std::vector<BT<std::string>> userDirs =
  1127. target->GetIncludeDirectories(config, lang);
  1128. // Support putting all the in-project include directories first if
  1129. // it is requested by the project.
  1130. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  1131. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  1132. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  1133. for (BT<std::string> const& udr : userDirs) {
  1134. // Emit this directory only if it is a subdirectory of the
  1135. // top-level source or binary tree.
  1136. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  1137. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  1138. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  1139. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  1140. if (notExcluded(udr.Value)) {
  1141. emitBT(udr);
  1142. }
  1143. }
  1144. }
  1145. }
  1146. // Emit remaining non implicit user directories.
  1147. for (BT<std::string> const& udr : userDirs) {
  1148. if (notExcluded(udr.Value)) {
  1149. emitBT(udr);
  1150. }
  1151. }
  1152. // Sort result
  1153. MoveSystemIncludesToEnd(result, config, lang, target);
  1154. // Append standard include directories for this language.
  1155. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  1156. for (std::string& usd : userStandardDirs) {
  1157. emitDir(usd);
  1158. userDirs.emplace_back(std::move(usd));
  1159. }
  1160. // Append compiler implicit include directories
  1161. if (!stripImplicitDirs) {
  1162. // Append implicit directories that were requested by the user only
  1163. for (BT<std::string> const& udr : userDirs) {
  1164. if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  1165. emitBT(udr);
  1166. }
  1167. }
  1168. // Append remaining implicit directories (on demand)
  1169. if (appendAllImplicitDirs) {
  1170. for (std::string& imd : implicitDirs) {
  1171. emitDir(imd);
  1172. }
  1173. }
  1174. }
  1175. return result;
  1176. }
  1177. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1178. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1179. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1180. bool appendAllImplicitDirs) const
  1181. {
  1182. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1183. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1184. dirs.reserve(dirs.size() + tmp.size());
  1185. for (BT<std::string>& v : tmp) {
  1186. dirs.emplace_back(std::move(v.Value));
  1187. }
  1188. }
  1189. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1190. cmGeneratorTarget const* target, std::string const& lang,
  1191. std::string const& config) const
  1192. {
  1193. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1194. }
  1195. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1196. cmGeneratorTarget const* target,
  1197. const std::string& lang,
  1198. const std::string& config) const
  1199. {
  1200. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1201. }
  1202. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1203. std::string const& config,
  1204. std::string const& linkLanguage,
  1205. cmGeneratorTarget* target)
  1206. {
  1207. std::vector<BT<std::string>> tmpFlags =
  1208. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1209. this->AppendFlags(flags, tmpFlags);
  1210. }
  1211. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1212. std::string const& config, std::string const& linkLanguage,
  1213. cmGeneratorTarget* target)
  1214. {
  1215. const std::string configUpper = cmSystemTools::UpperCase(config);
  1216. std::vector<BT<std::string>> flags;
  1217. if (linkLanguage != "Swift") {
  1218. std::string staticLibFlags;
  1219. this->AppendFlags(
  1220. staticLibFlags,
  1221. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1222. if (!configUpper.empty()) {
  1223. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
  1224. this->AppendFlags(staticLibFlags,
  1225. this->Makefile->GetSafeDefinition(name));
  1226. }
  1227. if (!staticLibFlags.empty()) {
  1228. flags.emplace_back(std::move(staticLibFlags));
  1229. }
  1230. }
  1231. std::string staticLibFlags;
  1232. this->AppendFlags(staticLibFlags,
  1233. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1234. if (!configUpper.empty()) {
  1235. std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
  1236. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1237. }
  1238. if (!staticLibFlags.empty()) {
  1239. flags.emplace_back(std::move(staticLibFlags));
  1240. }
  1241. std::vector<BT<std::string>> staticLibOpts =
  1242. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1243. // STATIC_LIBRARY_OPTIONS are escaped.
  1244. this->AppendCompileOptions(flags, staticLibOpts);
  1245. return flags;
  1246. }
  1247. void cmLocalGenerator::GetDeviceLinkFlags(
  1248. cmLinkLineDeviceComputer& linkLineComputer, const std::string& config,
  1249. std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
  1250. std::string& linkPath, cmGeneratorTarget* target)
  1251. {
  1252. cmGeneratorTarget::DeviceLinkSetter setter(*target);
  1253. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1254. auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
  1255. auto ipoEnabled = target->IsIPOEnabled(linklang, config);
  1256. if (!ipoEnabled) {
  1257. ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
  1258. }
  1259. if (ipoEnabled) {
  1260. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  1261. "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
  1262. linkFlags += *cudaIPOFlags;
  1263. }
  1264. }
  1265. if (pcli) {
  1266. // Compute the required device link libraries when
  1267. // resolving gpu lang device symbols
  1268. this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
  1269. linkPath);
  1270. }
  1271. this->AddVisibilityPresetFlags(linkFlags, target, "CUDA");
  1272. std::vector<std::string> linkOpts;
  1273. target->GetLinkOptions(linkOpts, config, "CUDA");
  1274. // LINK_OPTIONS are escaped.
  1275. this->AppendCompileOptions(linkFlags, linkOpts);
  1276. }
  1277. void cmLocalGenerator::GetTargetFlags(
  1278. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1279. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1280. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1281. {
  1282. std::vector<BT<std::string>> linkFlagsList;
  1283. std::vector<BT<std::string>> linkPathList;
  1284. std::vector<BT<std::string>> linkLibsList;
  1285. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1286. linkFlagsList, frameworkPath, linkPathList, target);
  1287. this->AppendFlags(linkFlags, linkFlagsList);
  1288. this->AppendFlags(linkPath, linkPathList);
  1289. this->AppendFlags(linkLibs, linkLibsList);
  1290. }
  1291. void cmLocalGenerator::GetTargetFlags(
  1292. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1293. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1294. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1295. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1296. {
  1297. const std::string configUpper = cmSystemTools::UpperCase(config);
  1298. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1299. const char* libraryLinkVariable =
  1300. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1301. const std::string linkLanguage =
  1302. linkLineComputer->GetLinkerLanguage(target, config);
  1303. switch (target->GetType()) {
  1304. case cmStateEnums::STATIC_LIBRARY:
  1305. linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
  1306. break;
  1307. case cmStateEnums::MODULE_LIBRARY:
  1308. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1309. CM_FALLTHROUGH;
  1310. case cmStateEnums::SHARED_LIBRARY: {
  1311. std::string sharedLibFlags;
  1312. if (linkLanguage != "Swift") {
  1313. sharedLibFlags = cmStrCat(
  1314. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1315. if (!configUpper.empty()) {
  1316. std::string build = cmStrCat(libraryLinkVariable, '_', configUpper);
  1317. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1318. sharedLibFlags += " ";
  1319. }
  1320. }
  1321. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1322. if (targetLinkFlags) {
  1323. sharedLibFlags += *targetLinkFlags;
  1324. sharedLibFlags += " ";
  1325. }
  1326. if (!configUpper.empty()) {
  1327. targetLinkFlags =
  1328. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1329. if (targetLinkFlags) {
  1330. sharedLibFlags += *targetLinkFlags;
  1331. sharedLibFlags += " ";
  1332. }
  1333. }
  1334. if (!sharedLibFlags.empty()) {
  1335. linkFlags.emplace_back(std::move(sharedLibFlags));
  1336. }
  1337. std::vector<BT<std::string>> linkOpts =
  1338. target->GetLinkOptions(config, linkLanguage);
  1339. // LINK_OPTIONS are escaped.
  1340. this->AppendCompileOptions(linkFlags, linkOpts);
  1341. if (pcli) {
  1342. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1343. frameworkPath, linkPath);
  1344. }
  1345. } break;
  1346. case cmStateEnums::EXECUTABLE: {
  1347. std::string exeFlags;
  1348. if (linkLanguage != "Swift") {
  1349. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1350. exeFlags += " ";
  1351. if (!configUpper.empty()) {
  1352. exeFlags += this->Makefile->GetSafeDefinition(
  1353. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", configUpper));
  1354. exeFlags += " ";
  1355. }
  1356. if (linkLanguage.empty()) {
  1357. cmSystemTools::Error(
  1358. "CMake can not determine linker language for target: " +
  1359. target->GetName());
  1360. return;
  1361. }
  1362. if (target->IsWin32Executable(config)) {
  1363. exeFlags += this->Makefile->GetSafeDefinition(
  1364. cmStrCat("CMAKE_", linkLanguage, "_CREATE_WIN32_EXE"));
  1365. exeFlags += " ";
  1366. } else {
  1367. exeFlags += this->Makefile->GetSafeDefinition(
  1368. cmStrCat("CMAKE_", linkLanguage, "_CREATE_CONSOLE_EXE"));
  1369. exeFlags += " ";
  1370. }
  1371. if (target->IsExecutableWithExports()) {
  1372. exeFlags += this->Makefile->GetSafeDefinition(
  1373. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1374. exeFlags += " ";
  1375. }
  1376. }
  1377. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
  1378. if (pcli) {
  1379. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1380. frameworkPath, linkPath);
  1381. }
  1382. if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
  1383. std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
  1384. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1385. exeFlags += " ";
  1386. }
  1387. std::string cmp0065Flags =
  1388. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1389. if (!cmp0065Flags.empty()) {
  1390. exeFlags += cmp0065Flags;
  1391. exeFlags += " ";
  1392. }
  1393. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1394. if (targetLinkFlags) {
  1395. exeFlags += *targetLinkFlags;
  1396. exeFlags += " ";
  1397. }
  1398. if (!configUpper.empty()) {
  1399. targetLinkFlags =
  1400. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1401. if (targetLinkFlags) {
  1402. exeFlags += *targetLinkFlags;
  1403. exeFlags += " ";
  1404. }
  1405. }
  1406. if (!exeFlags.empty()) {
  1407. linkFlags.emplace_back(std::move(exeFlags));
  1408. }
  1409. std::vector<BT<std::string>> linkOpts =
  1410. target->GetLinkOptions(config, linkLanguage);
  1411. // LINK_OPTIONS are escaped.
  1412. this->AppendCompileOptions(linkFlags, linkOpts);
  1413. } break;
  1414. default:
  1415. break;
  1416. }
  1417. std::string extraLinkFlags;
  1418. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1419. linkLanguage);
  1420. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1421. this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
  1422. config);
  1423. if (!extraLinkFlags.empty()) {
  1424. linkFlags.emplace_back(std::move(extraLinkFlags));
  1425. }
  1426. }
  1427. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1428. std::string const& config,
  1429. std::string const& lang,
  1430. std::string& flags,
  1431. std::string const& arch)
  1432. {
  1433. std::vector<BT<std::string>> tmpFlags =
  1434. this->GetTargetCompileFlags(target, config, lang, arch);
  1435. this->AppendFlags(flags, tmpFlags);
  1436. }
  1437. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1438. cmGeneratorTarget* target, std::string const& config,
  1439. std::string const& lang, std::string const& arch)
  1440. {
  1441. std::vector<BT<std::string>> flags;
  1442. std::string compileFlags;
  1443. cmMakefile* mf = this->GetMakefile();
  1444. // Add language-specific flags.
  1445. this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
  1446. config);
  1447. if (target->IsIPOEnabled(lang, config)) {
  1448. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1449. }
  1450. this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
  1451. if (lang == "Fortran") {
  1452. this->AppendFlags(compileFlags,
  1453. this->GetTargetFortranFlags(target, config));
  1454. }
  1455. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1456. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1457. this->AddColorDiagnosticsFlags(compileFlags, lang);
  1458. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1459. this->AppendFlags(compileFlags,
  1460. this->GetFrameworkFlags(lang, config, target));
  1461. if (!compileFlags.empty()) {
  1462. flags.emplace_back(std::move(compileFlags));
  1463. }
  1464. this->AddCompileOptions(flags, target, lang, config);
  1465. return flags;
  1466. }
  1467. static std::string GetFrameworkFlags(const std::string& lang,
  1468. const std::string& config,
  1469. cmGeneratorTarget* target)
  1470. {
  1471. cmLocalGenerator* lg = target->GetLocalGenerator();
  1472. cmMakefile* mf = lg->GetMakefile();
  1473. if (!mf->IsOn("APPLE")) {
  1474. return std::string();
  1475. }
  1476. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1477. cmValue fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1478. if (!cmNonempty(fwSearchFlag)) {
  1479. return std::string();
  1480. }
  1481. std::set<std::string> emitted;
  1482. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1483. emitted.insert("/System/Library/Frameworks");
  1484. #endif
  1485. std::vector<std::string> includes;
  1486. lg->GetIncludeDirectories(includes, target, "C", config);
  1487. // check all include directories for frameworks as this
  1488. // will already have added a -F for the framework
  1489. for (std::string const& include : includes) {
  1490. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1491. std::string frameworkDir = cmStrCat(include, "/../");
  1492. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1493. emitted.insert(frameworkDir);
  1494. }
  1495. }
  1496. std::string flags;
  1497. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1498. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1499. for (std::string const& framework : frameworks) {
  1500. if (emitted.insert(framework).second) {
  1501. flags += *fwSearchFlag;
  1502. flags +=
  1503. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1504. flags += " ";
  1505. }
  1506. }
  1507. }
  1508. return flags;
  1509. }
  1510. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1511. std::string const& config,
  1512. cmGeneratorTarget* target)
  1513. {
  1514. return ::GetFrameworkFlags(l, config, target);
  1515. }
  1516. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1517. std::string const& config,
  1518. std::string const& lang,
  1519. std::set<std::string>& defines) const
  1520. {
  1521. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1522. for (BT<std::string> const& v : tmp) {
  1523. defines.emplace(v.Value);
  1524. }
  1525. }
  1526. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1527. cmGeneratorTarget const* target, std::string const& config,
  1528. std::string const& lang) const
  1529. {
  1530. std::set<BT<std::string>> defines;
  1531. // Add the export symbol definition for shared library objects.
  1532. if (const std::string* exportMacro = target->GetExportMacro()) {
  1533. this->AppendDefines(defines, *exportMacro);
  1534. }
  1535. // Add preprocessor definitions for this target and configuration.
  1536. std::vector<BT<std::string>> targetDefines =
  1537. target->GetCompileDefinitions(config, lang);
  1538. this->AppendDefines(defines, targetDefines);
  1539. return defines;
  1540. }
  1541. std::string cmLocalGenerator::GetTargetFortranFlags(
  1542. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1543. {
  1544. // Implemented by specific generators that override this.
  1545. return std::string();
  1546. }
  1547. /**
  1548. * Output the linking rules on a command line. For executables,
  1549. * targetLibrary should be a NULL pointer. For libraries, it should point
  1550. * to the name of the library. This will not link a library against itself.
  1551. */
  1552. void cmLocalGenerator::OutputLinkLibraries(
  1553. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1554. std::string& linkLibraries, std::string& frameworkPath,
  1555. std::string& linkPath)
  1556. {
  1557. std::vector<BT<std::string>> linkLibrariesList;
  1558. std::vector<BT<std::string>> linkPathList;
  1559. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1560. frameworkPath, linkPathList);
  1561. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1562. pcli->AppendValues(linkPath, linkPathList);
  1563. }
  1564. void cmLocalGenerator::OutputLinkLibraries(
  1565. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1566. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1567. std::vector<BT<std::string>>& linkPath)
  1568. {
  1569. cmComputeLinkInformation& cli = *pcli;
  1570. std::string linkLanguage = cli.GetLinkLanguage();
  1571. std::string libPathFlag;
  1572. if (cmValue value = this->Makefile->GetDefinition(
  1573. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1574. libPathFlag = *value;
  1575. } else {
  1576. libPathFlag =
  1577. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1578. }
  1579. std::string libPathTerminator;
  1580. if (cmValue value = this->Makefile->GetDefinition(
  1581. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1582. libPathTerminator = *value;
  1583. } else {
  1584. libPathTerminator =
  1585. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1586. }
  1587. // Add standard libraries for this language.
  1588. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1589. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1590. // Append the framework search path flags.
  1591. std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
  1592. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1593. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1594. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1595. linkPath);
  1596. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1597. }
  1598. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1599. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1600. {
  1601. std::string linkFlags;
  1602. // Flags to link an executable to shared libraries.
  1603. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1604. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1605. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1606. bool add_shlib_flags = false;
  1607. switch (tgt.GetPolicyStatusCMP0065()) {
  1608. case cmPolicies::WARN:
  1609. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1610. this->Makefile->PolicyOptionalWarningEnabled(
  1611. "CMAKE_POLICY_WARNING_CMP0065")) {
  1612. std::ostringstream w;
  1613. /* clang-format off */
  1614. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1615. "For compatibility with older versions of CMake, "
  1616. "additional flags may be added to export symbols on all "
  1617. "executables regardless of their ENABLE_EXPORTS property.";
  1618. /* clang-format on */
  1619. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1620. }
  1621. CM_FALLTHROUGH;
  1622. case cmPolicies::OLD:
  1623. // OLD behavior is to always add the flags, except on AIX where
  1624. // we compute symbol exports if ENABLE_EXPORTS is on.
  1625. add_shlib_flags =
  1626. !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1627. break;
  1628. case cmPolicies::REQUIRED_IF_USED:
  1629. case cmPolicies::REQUIRED_ALWAYS:
  1630. this->IssueMessage(
  1631. MessageType::FATAL_ERROR,
  1632. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1633. CM_FALLTHROUGH;
  1634. case cmPolicies::NEW:
  1635. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1636. // except on AIX where we compute symbol exports.
  1637. add_shlib_flags =
  1638. !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1639. break;
  1640. }
  1641. if (add_shlib_flags) {
  1642. linkFlags = this->Makefile->GetSafeDefinition(
  1643. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1644. }
  1645. }
  1646. return linkFlags;
  1647. }
  1648. bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
  1649. const std::vector<std::string>& archs, cmValue sysroot)
  1650. {
  1651. if (!sysroot) {
  1652. return false;
  1653. }
  1654. return std::all_of(archs.begin(), archs.end(),
  1655. [this, sysroot](std::string const& arch) -> bool {
  1656. std::string const& archSysroot =
  1657. this->AppleArchSysroots[arch];
  1658. return cmIsOff(archSysroot) || *sysroot == archSysroot;
  1659. });
  1660. }
  1661. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1662. cmGeneratorTarget const* target,
  1663. const std::string& lang,
  1664. const std::string& config,
  1665. const std::string& filterArch)
  1666. {
  1667. // Only add Apple specific flags on Apple platforms
  1668. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1669. std::vector<std::string> archs;
  1670. target->GetAppleArchs(config, archs);
  1671. if (!archs.empty() &&
  1672. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
  1673. lang == "ASM")) {
  1674. for (std::string const& arch : archs) {
  1675. if (filterArch.empty() || filterArch == arch) {
  1676. flags += " -arch ";
  1677. flags += arch;
  1678. }
  1679. }
  1680. }
  1681. cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1682. if (sysroot && *sysroot == "/") {
  1683. sysroot = nullptr;
  1684. }
  1685. std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
  1686. cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1687. if (cmNonempty(sysrootFlag)) {
  1688. if (!this->AppleArchSysroots.empty() &&
  1689. !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
  1690. for (std::string const& arch : archs) {
  1691. std::string const& archSysroot = this->AppleArchSysroots[arch];
  1692. if (cmIsOff(archSysroot)) {
  1693. continue;
  1694. }
  1695. if (filterArch.empty() || filterArch == arch) {
  1696. flags += " -Xarch_" + arch + " ";
  1697. // Combine sysroot flag and path to work with -Xarch
  1698. std::string arch_sysroot = *sysrootFlag + archSysroot;
  1699. flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
  1700. }
  1701. }
  1702. } else if (cmNonempty(sysroot)) {
  1703. flags += " ";
  1704. flags += *sysrootFlag;
  1705. flags += " ";
  1706. flags += this->ConvertToOutputFormat(*sysroot, SHELL);
  1707. }
  1708. }
  1709. cmValue deploymentTarget =
  1710. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1711. std::string deploymentTargetFlagVar =
  1712. "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1713. cmValue deploymentTargetFlag =
  1714. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1715. if (cmNonempty(deploymentTargetFlag) && cmNonempty(deploymentTarget)) {
  1716. flags += " ";
  1717. flags += *deploymentTargetFlag;
  1718. flags += *deploymentTarget;
  1719. }
  1720. }
  1721. }
  1722. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1723. cmGeneratorTarget const* target,
  1724. cmBuildStep compileOrLink,
  1725. const std::string& lang,
  1726. const std::string& config)
  1727. {
  1728. // Add language-specific flags.
  1729. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1730. config);
  1731. // Add the language standard flag for compiling, and sometimes linking.
  1732. if (compileOrLink == cmBuildStep::Compile ||
  1733. (compileOrLink == cmBuildStep::Link &&
  1734. // Some toolchains require use of the language standard flag
  1735. // when linking in order to use the matching standard library.
  1736. // FIXME: If CMake gains an abstraction for standard library
  1737. // selection, this will have to be reconciled with it.
  1738. this->Makefile->IsOn(
  1739. cmStrCat("CMAKE_", lang, "_LINK_WITH_STANDARD_COMPILE_OPTION")))) {
  1740. cmStandardLevelResolver standardResolver(this->Makefile);
  1741. std::string const& optionFlagDef =
  1742. standardResolver.GetCompileOptionDef(target, lang, config);
  1743. if (!optionFlagDef.empty()) {
  1744. cmValue opt =
  1745. target->Target->GetMakefile()->GetDefinition(optionFlagDef);
  1746. if (opt) {
  1747. std::vector<std::string> optVec = cmExpandedList(*opt);
  1748. for (std::string const& i : optVec) {
  1749. this->AppendFlagEscape(flags, i);
  1750. }
  1751. }
  1752. }
  1753. }
  1754. std::string compiler = this->Makefile->GetSafeDefinition(
  1755. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1756. std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
  1757. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1758. if (lang == "Swift") {
  1759. if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1760. if (cmSystemTools::VersionCompare(
  1761. cmSystemTools::OP_GREATER_EQUAL,
  1762. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1763. "4.2")) {
  1764. this->AppendFlags(flags, "-swift-version " + *v);
  1765. }
  1766. }
  1767. } else if (lang == "CUDA") {
  1768. target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
  1769. target->AddCUDAToolkitFlags(flags);
  1770. } else if (lang == "ISPC") {
  1771. target->AddISPCTargetFlags(flags);
  1772. } else if (lang == "RC" &&
  1773. this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
  1774. .find("llvm-rc") != std::string::npos) {
  1775. compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
  1776. if (!compiler.empty()) {
  1777. compilerSimulateId =
  1778. this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
  1779. } else {
  1780. compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
  1781. compilerSimulateId =
  1782. this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
  1783. }
  1784. } else if (lang == "HIP") {
  1785. target->AddHIPArchitectureFlags(flags);
  1786. }
  1787. // Add VFS Overlay for Clang compilers
  1788. if (compiler == "Clang") {
  1789. if (cmValue vfsOverlay =
  1790. this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
  1791. if (compilerSimulateId == "MSVC") {
  1792. this->AppendCompileOptions(
  1793. flags,
  1794. std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
  1795. *vfsOverlay });
  1796. } else {
  1797. this->AppendCompileOptions(
  1798. flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
  1799. }
  1800. }
  1801. }
  1802. // Add MSVC runtime library flags. This is activated by the presence
  1803. // of a default selection whether or not it is overridden by a property.
  1804. cmValue msvcRuntimeLibraryDefault =
  1805. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1806. if (cmNonempty(msvcRuntimeLibraryDefault)) {
  1807. cmValue msvcRuntimeLibraryValue =
  1808. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1809. if (!msvcRuntimeLibraryValue) {
  1810. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1811. }
  1812. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1813. *msvcRuntimeLibraryValue, this, config, target);
  1814. if (!msvcRuntimeLibrary.empty()) {
  1815. if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1816. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1817. msvcRuntimeLibrary)) {
  1818. this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
  1819. } else if ((this->Makefile->GetSafeDefinition(
  1820. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1821. this->Makefile->GetSafeDefinition(
  1822. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1823. !cmSystemTools::GetErrorOccurredFlag()) {
  1824. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1825. this->IssueMessage(MessageType::FATAL_ERROR,
  1826. "MSVC_RUNTIME_LIBRARY value '" +
  1827. msvcRuntimeLibrary + "' not known for this " +
  1828. lang + " compiler.");
  1829. }
  1830. }
  1831. }
  1832. // Add Watcom runtime library flags. This is activated by the presence
  1833. // of a default selection whether or not it is overridden by a property.
  1834. cmValue watcomRuntimeLibraryDefault =
  1835. this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
  1836. if (cmNonempty(watcomRuntimeLibraryDefault)) {
  1837. cmValue watcomRuntimeLibraryValue =
  1838. target->GetProperty("WATCOM_RUNTIME_LIBRARY");
  1839. if (!watcomRuntimeLibraryValue) {
  1840. watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
  1841. }
  1842. std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1843. *watcomRuntimeLibraryValue, this, config, target);
  1844. if (!watcomRuntimeLibrary.empty()) {
  1845. if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1846. "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
  1847. watcomRuntimeLibrary)) {
  1848. this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
  1849. } else if ((this->Makefile->GetSafeDefinition(
  1850. "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
  1851. this->Makefile->GetSafeDefinition(
  1852. "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
  1853. !cmSystemTools::GetErrorOccurredFlag()) {
  1854. // The compiler uses the Watcom ABI so it needs a known runtime
  1855. // library.
  1856. this->IssueMessage(MessageType::FATAL_ERROR,
  1857. "WATCOM_RUNTIME_LIBRARY value '" +
  1858. watcomRuntimeLibrary + "' not known for this " +
  1859. lang + " compiler.");
  1860. }
  1861. }
  1862. }
  1863. // Add MSVC debug information format flags if CMP0141 is NEW.
  1864. if (cm::optional<std::string> msvcDebugInformationFormat =
  1865. this->GetMSVCDebugFormatName(config, target)) {
  1866. if (!msvcDebugInformationFormat->empty()) {
  1867. if (cmValue msvcDebugInformationFormatOptions =
  1868. this->Makefile->GetDefinition(
  1869. cmStrCat("CMAKE_", lang,
  1870. "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
  1871. *msvcDebugInformationFormat))) {
  1872. this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
  1873. } else if ((this->Makefile->GetSafeDefinition(
  1874. cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
  1875. this->Makefile->GetSafeDefinition(
  1876. cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
  1877. !cmSystemTools::GetErrorOccurredFlag()) {
  1878. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1879. this->IssueMessage(MessageType::FATAL_ERROR,
  1880. cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
  1881. *msvcDebugInformationFormat,
  1882. "' not known for this ", lang,
  1883. " compiler."));
  1884. }
  1885. }
  1886. }
  1887. }
  1888. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1889. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1890. const std::string& config)
  1891. {
  1892. this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
  1893. if (target->IsIPOEnabled(lang, config)) {
  1894. this->AppendFeatureOptions(flags, lang, "IPO");
  1895. }
  1896. }
  1897. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1898. const std::string& name) const
  1899. {
  1900. auto imported = this->ImportedGeneratorTargets.find(name);
  1901. if (imported != this->ImportedGeneratorTargets.end()) {
  1902. return imported->second;
  1903. }
  1904. // find local alias to imported target
  1905. auto aliased = this->AliasTargets.find(name);
  1906. if (aliased != this->AliasTargets.end()) {
  1907. imported = this->ImportedGeneratorTargets.find(aliased->second);
  1908. if (imported != this->ImportedGeneratorTargets.end()) {
  1909. return imported->second;
  1910. }
  1911. }
  1912. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1913. return t;
  1914. }
  1915. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1916. }
  1917. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1918. const std::string& config,
  1919. std::string& dep)
  1920. {
  1921. // Older CMake code may specify the dependency using the target
  1922. // output file rather than the target name. Such code would have
  1923. // been written before there was support for target properties that
  1924. // modify the name so stripping down to just the file name should
  1925. // produce the target name in this case.
  1926. std::string name = cmSystemTools::GetFilenameName(inName);
  1927. // If the input name is the empty string, there is no real
  1928. // dependency. Short-circuit the other checks:
  1929. if (name.empty()) {
  1930. return false;
  1931. }
  1932. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1933. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1934. }
  1935. // Look for a CMake target with the given name.
  1936. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1937. // make sure it is not just a coincidence that the target name
  1938. // found is part of the inName
  1939. if (cmSystemTools::FileIsFullPath(inName)) {
  1940. std::string tLocation;
  1941. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1942. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1943. tLocation = target->GetLocation(config);
  1944. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1945. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1946. }
  1947. std::string depLocation =
  1948. cmSystemTools::GetFilenamePath(std::string(inName));
  1949. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1950. if (depLocation != tLocation) {
  1951. // it is a full path to a depend that has the same name
  1952. // as a target but is in a different location so do not use
  1953. // the target as the depend
  1954. dep = inName;
  1955. return true;
  1956. }
  1957. }
  1958. switch (target->GetType()) {
  1959. case cmStateEnums::EXECUTABLE:
  1960. case cmStateEnums::STATIC_LIBRARY:
  1961. case cmStateEnums::SHARED_LIBRARY:
  1962. case cmStateEnums::MODULE_LIBRARY:
  1963. case cmStateEnums::UNKNOWN_LIBRARY:
  1964. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  1965. /*realname=*/true);
  1966. return true;
  1967. case cmStateEnums::OBJECT_LIBRARY:
  1968. // An object library has no single file on which to depend.
  1969. // This was listed to get the target-level dependency.
  1970. case cmStateEnums::INTERFACE_LIBRARY:
  1971. // An interface library has no file on which to depend.
  1972. // This was listed to get the target-level dependency.
  1973. case cmStateEnums::UTILITY:
  1974. case cmStateEnums::GLOBAL_TARGET:
  1975. // A utility target has no file on which to depend. This was listed
  1976. // only to get the target-level dependency.
  1977. return false;
  1978. }
  1979. }
  1980. // The name was not that of a CMake target. It must name a file.
  1981. if (cmSystemTools::FileIsFullPath(inName)) {
  1982. // This is a full path. Return it as given.
  1983. dep = inName;
  1984. return true;
  1985. }
  1986. // Check for a source file in this directory that matches the
  1987. // dependency.
  1988. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1989. dep = sf->ResolveFullPath();
  1990. return true;
  1991. }
  1992. // Treat the name as relative to the source directory in which it
  1993. // was given.
  1994. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  1995. // If the in-source path does not exist, assume it instead lives in the
  1996. // binary directory.
  1997. if (!cmSystemTools::FileExists(dep)) {
  1998. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  1999. }
  2000. dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
  2001. return true;
  2002. }
  2003. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  2004. const std::string& lang, bool shared)
  2005. {
  2006. std::string flagsVar;
  2007. // Add flags for dealing with shared libraries for this language.
  2008. if (shared) {
  2009. this->AppendFlags(flags,
  2010. this->Makefile->GetSafeDefinition(
  2011. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  2012. }
  2013. }
  2014. static void AddVisibilityCompileOption(std::string& flags,
  2015. cmGeneratorTarget const* target,
  2016. cmLocalGenerator* lg,
  2017. const std::string& lang,
  2018. std::string* warnCMP0063)
  2019. {
  2020. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2021. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2022. if (!opt) {
  2023. return;
  2024. }
  2025. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2026. cmValue prop = target->GetProperty(flagDefine);
  2027. if (!prop) {
  2028. return;
  2029. }
  2030. if (warnCMP0063) {
  2031. *warnCMP0063 += " " + flagDefine + "\n";
  2032. return;
  2033. }
  2034. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2035. (*prop != "internal")) {
  2036. std::ostringstream e;
  2037. e << "Target " << target->GetName() << " uses unsupported value \""
  2038. << *prop << "\" for " << flagDefine << "."
  2039. << " The supported values are: default, hidden, protected, and "
  2040. "internal.";
  2041. cmSystemTools::Error(e.str());
  2042. return;
  2043. }
  2044. std::string option = *opt + *prop;
  2045. lg->AppendFlags(flags, option);
  2046. }
  2047. static void AddInlineVisibilityCompileOption(std::string& flags,
  2048. cmGeneratorTarget const* target,
  2049. cmLocalGenerator* lg,
  2050. std::string* warnCMP0063,
  2051. const std::string& lang)
  2052. {
  2053. std::string compileOption =
  2054. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2055. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2056. if (!opt) {
  2057. return;
  2058. }
  2059. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2060. if (!prop) {
  2061. return;
  2062. }
  2063. if (warnCMP0063) {
  2064. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2065. return;
  2066. }
  2067. lg->AppendFlags(flags, *opt);
  2068. }
  2069. void cmLocalGenerator::AddVisibilityPresetFlags(
  2070. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2071. {
  2072. if (lang.empty()) {
  2073. return;
  2074. }
  2075. std::string warnCMP0063;
  2076. std::string* pWarnCMP0063 = nullptr;
  2077. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2078. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2079. !target->IsExecutableWithExports()) {
  2080. switch (target->GetPolicyStatusCMP0063()) {
  2081. case cmPolicies::OLD:
  2082. return;
  2083. case cmPolicies::WARN:
  2084. pWarnCMP0063 = &warnCMP0063;
  2085. break;
  2086. default:
  2087. break;
  2088. }
  2089. }
  2090. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2091. if (lang == "CXX" || lang == "OBJCXX") {
  2092. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2093. }
  2094. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2095. std::ostringstream w;
  2096. /* clang-format off */
  2097. w <<
  2098. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2099. "Target \"" << target->GetName() << "\" of "
  2100. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2101. "has the following visibility properties set for " << lang << ":\n" <<
  2102. warnCMP0063 <<
  2103. "For compatibility CMake is not honoring them for this target.";
  2104. /* clang-format on */
  2105. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2106. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2107. }
  2108. }
  2109. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2110. cmGeneratorTarget const* target,
  2111. std::string const& lang,
  2112. const std::string& config)
  2113. {
  2114. int targetType = target->GetType();
  2115. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2116. (targetType == cmStateEnums::MODULE_LIBRARY));
  2117. if (this->GetShouldUseOldFlags(shared, lang)) {
  2118. this->AddSharedFlags(flags, lang, shared);
  2119. } else {
  2120. if (target->GetLinkInterfaceDependentBoolProperty(
  2121. "POSITION_INDEPENDENT_CODE", config)) {
  2122. this->AddPositionIndependentFlags(flags, lang, targetType);
  2123. }
  2124. if (shared) {
  2125. this->AppendFeatureOptions(flags, lang, "DLL");
  2126. }
  2127. }
  2128. }
  2129. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2130. const std::string& lang) const
  2131. {
  2132. std::string originalFlags =
  2133. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2134. if (shared) {
  2135. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2136. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2137. if (flags != originalFlags) {
  2138. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2139. case cmPolicies::WARN: {
  2140. std::ostringstream e;
  2141. e << "Variable " << flagsVar
  2142. << " has been modified. CMake "
  2143. "will ignore the POSITION_INDEPENDENT_CODE target property "
  2144. "for "
  2145. "shared libraries and will use the "
  2146. << flagsVar
  2147. << " variable "
  2148. "instead. This may cause errors if the original content of "
  2149. << flagsVar << " was removed.\n"
  2150. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2151. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2152. CM_FALLTHROUGH;
  2153. }
  2154. case cmPolicies::OLD:
  2155. return true;
  2156. case cmPolicies::REQUIRED_IF_USED:
  2157. case cmPolicies::REQUIRED_ALWAYS:
  2158. case cmPolicies::NEW:
  2159. return false;
  2160. }
  2161. }
  2162. }
  2163. return false;
  2164. }
  2165. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2166. std::string const& lang,
  2167. int targetType)
  2168. {
  2169. std::string picFlags;
  2170. if (targetType == cmStateEnums::EXECUTABLE) {
  2171. picFlags = this->Makefile->GetSafeDefinition(
  2172. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2173. }
  2174. if (picFlags.empty()) {
  2175. picFlags = this->Makefile->GetSafeDefinition(
  2176. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2177. }
  2178. if (!picFlags.empty()) {
  2179. std::vector<std::string> options = cmExpandedList(picFlags);
  2180. for (std::string const& o : options) {
  2181. this->AppendFlagEscape(flags, o);
  2182. }
  2183. }
  2184. }
  2185. void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
  2186. const std::string& lang)
  2187. {
  2188. cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
  2189. if (diag.IsSet()) {
  2190. std::string colorFlagName;
  2191. if (diag.IsOn()) {
  2192. colorFlagName =
  2193. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
  2194. } else {
  2195. colorFlagName =
  2196. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
  2197. }
  2198. std::vector<std::string> options;
  2199. this->Makefile->GetDefExpandList(colorFlagName, options);
  2200. for (std::string const& option : options) {
  2201. this->AppendFlagEscape(flags, option);
  2202. }
  2203. }
  2204. }
  2205. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2206. const std::string& var,
  2207. const std::string& config)
  2208. {
  2209. // Add the flags from the variable itself.
  2210. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2211. // Add the flags from the build-type specific variable.
  2212. if (!config.empty()) {
  2213. const std::string flagsVar =
  2214. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2215. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2216. }
  2217. }
  2218. void cmLocalGenerator::AppendFlags(std::string& flags,
  2219. const std::string& newFlags) const
  2220. {
  2221. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2222. if (!newFlags.empty() && !allSpaces) {
  2223. if (!flags.empty()) {
  2224. flags += " ";
  2225. }
  2226. flags += newFlags;
  2227. }
  2228. }
  2229. void cmLocalGenerator::AppendFlags(
  2230. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2231. {
  2232. for (BT<std::string> const& flag : newFlags) {
  2233. this->AppendFlags(flags, flag.Value);
  2234. }
  2235. }
  2236. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2237. const std::string& rawFlag) const
  2238. {
  2239. this->AppendFlags(
  2240. flags,
  2241. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2242. }
  2243. void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
  2244. {
  2245. std::vector<std::string> enabledLanguages =
  2246. this->GetState()->GetEnabledLanguages();
  2247. if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
  2248. enabledLanguages.end()) {
  2249. return;
  2250. }
  2251. cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
  2252. assert(ispcHeaderSuffixProp);
  2253. std::vector<std::string> ispcArchSuffixes =
  2254. detail::ComputeISPCObjectSuffixes(target);
  2255. const bool extra_objects = (ispcArchSuffixes.size() > 1);
  2256. std::vector<std::string> configsList =
  2257. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2258. for (std::string const& config : configsList) {
  2259. std::string rootObjectDir = target->GetObjectDirectory(config);
  2260. std::string headerDir = rootObjectDir;
  2261. if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
  2262. headerDir = cmSystemTools::CollapseFullPath(
  2263. cmStrCat(this->GetBinaryDirectory(), '/', *prop));
  2264. }
  2265. std::vector<cmSourceFile*> sources;
  2266. target->GetSourceFiles(sources, config);
  2267. // build up the list of ispc headers and extra objects that this target is
  2268. // generating
  2269. for (cmSourceFile const* sf : sources) {
  2270. // Generate this object file's rule file.
  2271. const std::string& lang = sf->GetLanguage();
  2272. if (lang == "ISPC") {
  2273. std::string const& objectName = target->GetObjectName(sf);
  2274. // Drop both ".obj" and the source file extension
  2275. std::string ispcSource =
  2276. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  2277. ispcSource =
  2278. cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  2279. auto headerPath =
  2280. cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
  2281. target->AddISPCGeneratedHeader(headerPath, config);
  2282. if (extra_objects) {
  2283. std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
  2284. objectName, rootObjectDir, ispcArchSuffixes);
  2285. target->AddISPCGeneratedObject(std::move(objs), config);
  2286. }
  2287. }
  2288. }
  2289. }
  2290. }
  2291. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2292. {
  2293. std::vector<std::string> configsList =
  2294. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2295. for (std::string const& config : configsList) {
  2296. // FIXME: Refactor collection of sources to not evaluate object
  2297. // libraries.
  2298. std::vector<cmSourceFile*> sources;
  2299. target->GetSourceFiles(sources, config);
  2300. const std::string configUpper = cmSystemTools::UpperCase(config);
  2301. static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
  2302. "OBJCXX" } };
  2303. std::set<std::string> pchLangSet;
  2304. if (this->GetGlobalGenerator()->IsXcode()) {
  2305. for (const std::string& lang : langs) {
  2306. const std::string pchHeader = target->GetPchHeader(config, lang, "");
  2307. if (!pchHeader.empty()) {
  2308. pchLangSet.emplace(lang);
  2309. }
  2310. }
  2311. }
  2312. for (const std::string& lang : langs) {
  2313. auto langSources = std::count_if(
  2314. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2315. return lang == sf->GetLanguage() &&
  2316. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2317. });
  2318. if (langSources == 0) {
  2319. continue;
  2320. }
  2321. std::vector<std::string> architectures;
  2322. if (!this->GetGlobalGenerator()->IsXcode()) {
  2323. target->GetAppleArchs(config, architectures);
  2324. }
  2325. if (architectures.empty()) {
  2326. architectures.emplace_back();
  2327. } else {
  2328. std::string useMultiArchPch;
  2329. for (const std::string& arch : architectures) {
  2330. const std::string pchHeader =
  2331. target->GetPchHeader(config, lang, arch);
  2332. if (!pchHeader.empty()) {
  2333. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2334. ";-include", pchHeader);
  2335. }
  2336. }
  2337. if (!useMultiArchPch.empty()) {
  2338. target->Target->AppendProperty(
  2339. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
  2340. cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
  2341. }
  2342. }
  2343. for (const std::string& arch : architectures) {
  2344. const std::string pchSource = target->GetPchSource(config, lang, arch);
  2345. const std::string pchHeader = target->GetPchHeader(config, lang, arch);
  2346. if (pchSource.empty() || pchHeader.empty()) {
  2347. if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
  2348. for (auto* sf : sources) {
  2349. const auto sourceLanguage = sf->GetLanguage();
  2350. if (!sourceLanguage.empty() &&
  2351. pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
  2352. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2353. }
  2354. }
  2355. }
  2356. continue;
  2357. }
  2358. cmValue pchExtension =
  2359. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  2360. if (pchExtension.IsEmpty()) {
  2361. continue;
  2362. }
  2363. cmValue ReuseFrom =
  2364. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2365. auto* pch_sf = this->Makefile->GetOrCreateSource(
  2366. pchSource, false, cmSourceFileLocationKind::Known);
  2367. if (!this->GetGlobalGenerator()->IsXcode()) {
  2368. if (!ReuseFrom) {
  2369. target->AddSource(pchSource, true);
  2370. }
  2371. const std::string pchFile = target->GetPchFile(config, lang, arch);
  2372. // Exclude the pch files from linking
  2373. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2374. if (!ReuseFrom) {
  2375. pch_sf->AppendProperty(
  2376. "OBJECT_OUTPUTS",
  2377. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
  2378. } else {
  2379. auto* reuseTarget =
  2380. this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
  2381. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2382. const std::string compilerId =
  2383. this->Makefile->GetSafeDefinition(
  2384. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2385. const std::string compilerVersion =
  2386. this->Makefile->GetSafeDefinition(
  2387. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2388. const std::string langFlags =
  2389. this->Makefile->GetSafeDefinition(
  2390. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2391. bool editAndContinueDebugInfo = false;
  2392. bool programDatabaseDebugInfo = false;
  2393. cm::optional<std::string> msvcDebugInformationFormat =
  2394. this->GetMSVCDebugFormatName(config, target);
  2395. if (msvcDebugInformationFormat &&
  2396. !msvcDebugInformationFormat->empty()) {
  2397. editAndContinueDebugInfo =
  2398. *msvcDebugInformationFormat == "EditAndContinue";
  2399. programDatabaseDebugInfo =
  2400. *msvcDebugInformationFormat == "ProgramDatabase";
  2401. } else {
  2402. editAndContinueDebugInfo =
  2403. langFlags.find("/ZI") != std::string::npos ||
  2404. langFlags.find("-ZI") != std::string::npos;
  2405. programDatabaseDebugInfo =
  2406. langFlags.find("/Zi") != std::string::npos ||
  2407. langFlags.find("-Zi") != std::string::npos;
  2408. }
  2409. // MSVC 2008 is producing both .pdb and .idb files with /Zi.
  2410. bool msvc2008OrLess =
  2411. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  2412. compilerVersion, "16.0") &&
  2413. compilerId == "MSVC";
  2414. // but not when used via toolset -Tv90
  2415. if (this->Makefile->GetSafeDefinition(
  2416. "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
  2417. msvc2008OrLess = false;
  2418. }
  2419. if (editAndContinueDebugInfo || msvc2008OrLess) {
  2420. this->CopyPchCompilePdb(config, target, *ReuseFrom,
  2421. reuseTarget, { ".pdb", ".idb" });
  2422. } else if (programDatabaseDebugInfo) {
  2423. this->CopyPchCompilePdb(config, target, *ReuseFrom,
  2424. reuseTarget, { ".pdb" });
  2425. }
  2426. }
  2427. // Link to the pch object file
  2428. std::string pchSourceObj =
  2429. reuseTarget->GetPchFileObject(config, lang, arch);
  2430. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2431. std::string linkerProperty = "LINK_FLAGS_";
  2432. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2433. linkerProperty = "STATIC_LIBRARY_FLAGS_";
  2434. }
  2435. target->Target->AppendProperty(
  2436. cmStrCat(linkerProperty, configUpper),
  2437. cmStrCat(" ",
  2438. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2439. cm::nullopt, true);
  2440. } else if (reuseTarget->GetType() ==
  2441. cmStateEnums::OBJECT_LIBRARY) {
  2442. // FIXME: This can propagate more than one level, unlike
  2443. // the rest of the object files in an object library.
  2444. // Find another way to do this.
  2445. target->Target->AppendProperty(
  2446. "INTERFACE_LINK_LIBRARIES",
  2447. cmStrCat("$<$<CONFIG:", config,
  2448. ">:$<LINK_ONLY:", pchSourceObj, ">>"));
  2449. // We updated the link interface, so ensure it is recomputed.
  2450. target->ClearLinkInterfaceCache();
  2451. }
  2452. }
  2453. } else {
  2454. pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
  2455. }
  2456. // Add pchHeader to source files, which will
  2457. // be grouped as "Precompile Header File"
  2458. auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
  2459. pchHeader, false, cmSourceFileLocationKind::Known);
  2460. std::string err;
  2461. pchHeader_sf->ResolveFullPath(&err);
  2462. if (!err.empty()) {
  2463. std::ostringstream msg;
  2464. msg << "Unable to resolve full path of PCH-header '" << pchHeader
  2465. << "' assigned to target " << target->GetName()
  2466. << ", although its path is supposed to be known!";
  2467. this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
  2468. }
  2469. target->AddSource(pchHeader);
  2470. }
  2471. }
  2472. }
  2473. }
  2474. }
  2475. void cmLocalGenerator::CopyPchCompilePdb(
  2476. const std::string& config, cmGeneratorTarget* target,
  2477. const std::string& ReuseFrom, cmGeneratorTarget* reuseTarget,
  2478. const std::vector<std::string>& extensions)
  2479. {
  2480. const std::string pdb_prefix =
  2481. this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
  2482. const std::string target_compile_pdb_dir =
  2483. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2484. target->GetName(), ".dir/");
  2485. const std::string copy_script = cmStrCat(
  2486. target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
  2487. cmGeneratedFileStream file(copy_script);
  2488. file << "# CMake generated file\n";
  2489. file << "# The compiler generated pdb file needs to be written to disk\n"
  2490. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2491. << "# the pdb file is ready to be copied.\n\n";
  2492. for (auto const& extension : extensions) {
  2493. const std::string from_file =
  2494. cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2495. "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
  2496. const std::string to_dir =
  2497. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2498. target->GetName(), ".dir/${PDB_PREFIX}");
  2499. const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
  2500. std::string dest_file = to_file;
  2501. std::string const& prefix = target->GetSafeProperty("PREFIX");
  2502. if (!prefix.empty()) {
  2503. dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
  2504. }
  2505. file << "foreach(retry RANGE 1 30)\n";
  2506. file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
  2507. << dest_file << "\" OR NOT \"" << dest_file << " \" IS_NEWER_THAN \""
  2508. << from_file << "\"))\n";
  2509. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2510. file << " \"" << from_file << "\""
  2511. << " \"" << to_dir << "\" RESULT_VARIABLE result "
  2512. << " ERROR_QUIET)\n";
  2513. file << " if (NOT result EQUAL 0)\n"
  2514. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2515. << " -E sleep 1)\n"
  2516. << " else()\n";
  2517. if (!prefix.empty()) {
  2518. file << " file(REMOVE \"" << dest_file << "\")\n";
  2519. file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
  2520. }
  2521. file << " break()\n"
  2522. << " endif()\n";
  2523. file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
  2524. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2525. << " -E sleep 1)\n"
  2526. << " endif()\n";
  2527. file << "endforeach()\n";
  2528. }
  2529. auto configGenex = [&](cm::string_view expr) -> std::string {
  2530. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2531. return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
  2532. }
  2533. return std::string(expr);
  2534. };
  2535. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2536. { configGenex(cmSystemTools::GetCMakeCommand()),
  2537. configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
  2538. configGenex(copy_script) });
  2539. const char* no_message = "";
  2540. std::vector<std::string> outputs;
  2541. outputs.push_back(configGenex(
  2542. cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
  2543. auto cc = cm::make_unique<cmCustomCommand>();
  2544. cc->SetCommandLines(commandLines);
  2545. cc->SetComment(no_message);
  2546. cc->SetCMP0116Status(cmPolicies::NEW);
  2547. cc->SetStdPipesUTF8(true);
  2548. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2549. cc->SetByproducts(outputs);
  2550. this->AddCustomCommandToTarget(
  2551. target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
  2552. cmObjectLibraryCommands::Accept);
  2553. } else {
  2554. cc->SetOutputs(outputs);
  2555. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
  2556. if (copy_rule) {
  2557. target->AddSource(copy_rule->ResolveFullPath());
  2558. }
  2559. }
  2560. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2561. target_compile_pdb_dir);
  2562. }
  2563. cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
  2564. std::string const& config, cmGeneratorTarget const* target)
  2565. {
  2566. // MSVC debug information format selection is activated by the presence
  2567. // of a default whether or not it is overridden by a property.
  2568. cm::optional<std::string> msvcDebugInformationFormat;
  2569. cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
  2570. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
  2571. if (cmNonempty(msvcDebugInformationFormatDefault)) {
  2572. cmValue msvcDebugInformationFormatValue =
  2573. target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
  2574. if (!msvcDebugInformationFormatValue) {
  2575. msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
  2576. }
  2577. msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
  2578. *msvcDebugInformationFormatValue, this, config, target);
  2579. }
  2580. return msvcDebugInformationFormat;
  2581. }
  2582. namespace {
  2583. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2584. std::string const& filename)
  2585. {
  2586. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2587. sf->SetProperty("UNITY_SOURCE_FILE", filename);
  2588. }
  2589. }
  2590. cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
  2591. cmGeneratorTarget* target, std::vector<std::string> const& configs,
  2592. cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
  2593. cmValue beforeInclude, cmValue afterInclude, std::string filename) const
  2594. {
  2595. cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
  2596. cmGeneratedFileStream file(
  2597. filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
  2598. file.SetCopyIfDifferent(true);
  2599. file << "/* generated by CMake */\n\n";
  2600. bool perConfig = false;
  2601. for (UnityBatchedSource const& ubs : sources) {
  2602. cm::optional<std::string> cond;
  2603. if (ubs.Configs.size() != configs.size()) {
  2604. perConfig = true;
  2605. cond = std::string();
  2606. cm::string_view sep;
  2607. for (size_t ci : ubs.Configs) {
  2608. cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
  2609. cmSystemTools::UpperCase(configs[ci]), ")");
  2610. sep = " || "_s;
  2611. }
  2612. }
  2613. RegisterUnitySources(target, ubs.Source, filename);
  2614. WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
  2615. beforeInclude, afterInclude, uniqueIdName);
  2616. }
  2617. return UnitySource(std::move(filename), perConfig);
  2618. }
  2619. void cmLocalGenerator::WriteUnitySourceInclude(
  2620. std::ostream& unity_file, cm::optional<std::string> const& cond,
  2621. std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
  2622. cmValue uniqueIdName) const
  2623. {
  2624. if (cond) {
  2625. unity_file << "#if " << *cond << "\n";
  2626. }
  2627. if (cmNonempty(uniqueIdName)) {
  2628. std::string pathToHash;
  2629. auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
  2630. return (cmSystemTools::ComparePath(a, b) ||
  2631. cmSystemTools::IsSubDirectory(a, b));
  2632. };
  2633. const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
  2634. if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
  2635. pathToHash = "BLD_" +
  2636. cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
  2637. } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
  2638. pathToHash = "SRC_" +
  2639. cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
  2640. } else {
  2641. pathToHash = "ABS_" + sf_full_path;
  2642. }
  2643. unity_file << "/* " << pathToHash << " */\n"
  2644. << "#undef " << *uniqueIdName << "\n"
  2645. << "#define " << *uniqueIdName << " unity_"
  2646. #ifndef CMAKE_BOOTSTRAP
  2647. << cmSystemTools::ComputeStringMD5(pathToHash) << "\n"
  2648. #endif
  2649. ;
  2650. }
  2651. if (beforeInclude) {
  2652. unity_file << *beforeInclude << "\n";
  2653. }
  2654. unity_file << "#include \"" << sf_full_path << "\"\n";
  2655. if (afterInclude) {
  2656. unity_file << *afterInclude << "\n";
  2657. }
  2658. if (cond) {
  2659. unity_file << "#endif\n";
  2660. }
  2661. unity_file << "\n";
  2662. }
  2663. std::vector<cmLocalGenerator::UnitySource>
  2664. cmLocalGenerator::AddUnityFilesModeAuto(
  2665. cmGeneratorTarget* target, std::string const& lang,
  2666. std::vector<std::string> const& configs,
  2667. std::vector<UnityBatchedSource> const& filtered_sources,
  2668. cmValue beforeInclude, cmValue afterInclude,
  2669. std::string const& filename_base, size_t batchSize)
  2670. {
  2671. if (batchSize == 0) {
  2672. batchSize = filtered_sources.size();
  2673. }
  2674. std::vector<UnitySource> unity_files;
  2675. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2676. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2677. chunk = std::min(itemsLeft, batchSize);
  2678. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2679. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2680. auto const begin = filtered_sources.begin() + batch * batchSize;
  2681. auto const end = begin + chunk;
  2682. unity_files.emplace_back(this->WriteUnitySource(
  2683. target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
  2684. std::move(filename)));
  2685. }
  2686. return unity_files;
  2687. }
  2688. std::vector<cmLocalGenerator::UnitySource>
  2689. cmLocalGenerator::AddUnityFilesModeGroup(
  2690. cmGeneratorTarget* target, std::string const& lang,
  2691. std::vector<std::string> const& configs,
  2692. std::vector<UnityBatchedSource> const& filtered_sources,
  2693. cmValue beforeInclude, cmValue afterInclude,
  2694. std::string const& filename_base)
  2695. {
  2696. std::vector<UnitySource> unity_files;
  2697. // sources organized by group name. Drop any source
  2698. // without a group
  2699. std::unordered_map<std::string, std::vector<UnityBatchedSource>>
  2700. explicit_mapping;
  2701. for (UnityBatchedSource const& ubs : filtered_sources) {
  2702. if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
  2703. auto i = explicit_mapping.find(*value);
  2704. if (i == explicit_mapping.end()) {
  2705. std::vector<UnityBatchedSource> sources{ ubs };
  2706. explicit_mapping.emplace(*value, std::move(sources));
  2707. } else {
  2708. i->second.emplace_back(ubs);
  2709. }
  2710. }
  2711. }
  2712. for (auto const& item : explicit_mapping) {
  2713. auto const& name = item.first;
  2714. std::string filename = cmStrCat(filename_base, "unity_", name,
  2715. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2716. unity_files.emplace_back(this->WriteUnitySource(
  2717. target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
  2718. std::move(filename)));
  2719. }
  2720. return unity_files;
  2721. }
  2722. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2723. {
  2724. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2725. return;
  2726. }
  2727. std::vector<UnityBatchedSource> unitySources;
  2728. std::vector<std::string> configs =
  2729. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2730. std::map<cmSourceFile const*, size_t> index;
  2731. for (size_t ci = 0; ci < configs.size(); ++ci) {
  2732. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2733. std::vector<cmSourceFile*> sources;
  2734. target->GetSourceFiles(sources, configs[ci]);
  2735. for (cmSourceFile* sf : sources) {
  2736. auto mi = index.find(sf);
  2737. if (mi == index.end()) {
  2738. unitySources.emplace_back(sf);
  2739. std::map<cmSourceFile const*, size_t>::value_type entry(
  2740. sf, unitySources.size() - 1);
  2741. mi = index.insert(entry).first;
  2742. }
  2743. unitySources[mi->second].Configs.emplace_back(ci);
  2744. }
  2745. }
  2746. std::string filename_base =
  2747. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2748. target->GetName(), ".dir/Unity/");
  2749. cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2750. const size_t unityBatchSize = batchSizeString
  2751. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2752. : 0;
  2753. cmValue beforeInclude =
  2754. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2755. cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2756. cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2757. for (std::string lang : { "C", "CXX" }) {
  2758. std::vector<UnityBatchedSource> filtered_sources;
  2759. std::copy_if(unitySources.begin(), unitySources.end(),
  2760. std::back_inserter(filtered_sources),
  2761. [&](UnityBatchedSource const& ubs) -> bool {
  2762. cmSourceFile* sf = ubs.Source;
  2763. return sf->GetLanguage() == lang &&
  2764. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2765. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2766. !sf->GetProperty("COMPILE_OPTIONS") &&
  2767. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2768. !sf->GetProperty("COMPILE_FLAGS") &&
  2769. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2770. });
  2771. std::vector<UnitySource> unity_files;
  2772. if (!unityMode || *unityMode == "BATCH") {
  2773. unity_files = AddUnityFilesModeAuto(
  2774. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2775. filename_base, unityBatchSize);
  2776. } else if (unityMode && *unityMode == "GROUP") {
  2777. unity_files =
  2778. AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
  2779. beforeInclude, afterInclude, filename_base);
  2780. } else {
  2781. // unity mode is set to an unsupported value
  2782. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2783. " assigned to target " + target->GetName() +
  2784. ". Acceptable values are BATCH and GROUP.");
  2785. this->IssueMessage(MessageType::FATAL_ERROR, e);
  2786. }
  2787. for (UnitySource const& file : unity_files) {
  2788. auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
  2789. target->AddSource(file.Path, true);
  2790. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2791. unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
  2792. if (file.PerConfig) {
  2793. unity->SetProperty("COMPILE_DEFINITIONS",
  2794. "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
  2795. }
  2796. }
  2797. }
  2798. }
  2799. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2800. cmGeneratorTarget* target,
  2801. const std::string& config,
  2802. const std::string& lang)
  2803. {
  2804. if (!target->IsIPOEnabled(lang, config)) {
  2805. return;
  2806. }
  2807. switch (target->GetType()) {
  2808. case cmStateEnums::EXECUTABLE:
  2809. case cmStateEnums::SHARED_LIBRARY:
  2810. case cmStateEnums::MODULE_LIBRARY:
  2811. break;
  2812. default:
  2813. return;
  2814. }
  2815. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2816. cmValue rawFlagsList = this->Makefile->GetDefinition(name);
  2817. if (!rawFlagsList) {
  2818. return;
  2819. }
  2820. std::vector<std::string> flagsList = cmExpandedList(*rawFlagsList);
  2821. for (std::string const& o : flagsList) {
  2822. this->AppendFlagEscape(flags, o);
  2823. }
  2824. }
  2825. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2826. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2827. const std::string& lang)
  2828. {
  2829. // For now, only EXECUTABLE is concerned
  2830. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2831. return;
  2832. }
  2833. const char* PICValue = target->GetLinkPIEProperty(config);
  2834. if (PICValue == nullptr) {
  2835. // POSITION_INDEPENDENT_CODE is not set
  2836. return;
  2837. }
  2838. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2839. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2840. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2841. return;
  2842. }
  2843. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2844. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2845. if (pieFlags.empty()) {
  2846. return;
  2847. }
  2848. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2849. for (const auto& flag : flagsList) {
  2850. this->AppendFlagEscape(flags, flag);
  2851. }
  2852. }
  2853. void cmLocalGenerator::AppendModuleDefinitionFlag(
  2854. std::string& flags, cmGeneratorTarget const* target,
  2855. cmLinkLineComputer* linkLineComputer, std::string const& config)
  2856. {
  2857. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  2858. target->GetModuleDefinitionInfo(config);
  2859. if (!mdi || mdi->DefFile.empty()) {
  2860. return;
  2861. }
  2862. cmValue defFileFlag =
  2863. this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  2864. if (!defFileFlag) {
  2865. return;
  2866. }
  2867. // Append the flag and value. Use ConvertToLinkReference to help
  2868. // vs6's "cl -link" pass it to the linker.
  2869. std::string flag =
  2870. cmStrCat(*defFileFlag,
  2871. this->ConvertToOutputFormat(
  2872. linkLineComputer->ConvertToLinkReference(mdi->DefFile),
  2873. cmOutputConverter::SHELL));
  2874. this->AppendFlags(flags, flag);
  2875. }
  2876. bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
  2877. const cmGeneratorTarget* target,
  2878. const std::string& lang)
  2879. {
  2880. auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  2881. (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
  2882. target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
  2883. target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
  2884. if (useLWYU) {
  2885. const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
  2886. cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
  2887. useLWYU = !lwyuFlag.empty();
  2888. if (useLWYU) {
  2889. std::vector<BT<std::string>> lwyuOpts;
  2890. lwyuOpts.emplace_back(lwyuFlag);
  2891. this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
  2892. }
  2893. }
  2894. return useLWYU;
  2895. }
  2896. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2897. std::string const& options_list,
  2898. const char* regex) const
  2899. {
  2900. // Short-circuit if there are no options.
  2901. if (options_list.empty()) {
  2902. return;
  2903. }
  2904. // Expand the list of options.
  2905. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2906. this->AppendCompileOptions(options, options_vec, regex);
  2907. }
  2908. void cmLocalGenerator::AppendCompileOptions(
  2909. std::string& options, const std::vector<std::string>& options_vec,
  2910. const char* regex) const
  2911. {
  2912. if (regex != nullptr) {
  2913. // Filter flags upon specified reges.
  2914. cmsys::RegularExpression r(regex);
  2915. for (std::string const& opt : options_vec) {
  2916. if (r.find(opt)) {
  2917. this->AppendFlagEscape(options, opt);
  2918. }
  2919. }
  2920. } else {
  2921. for (std::string const& opt : options_vec) {
  2922. this->AppendFlagEscape(options, opt);
  2923. }
  2924. }
  2925. }
  2926. void cmLocalGenerator::AppendCompileOptions(
  2927. std::vector<BT<std::string>>& options,
  2928. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2929. {
  2930. if (regex != nullptr) {
  2931. // Filter flags upon specified regular expressions.
  2932. cmsys::RegularExpression r(regex);
  2933. for (BT<std::string> const& opt : options_vec) {
  2934. if (r.find(opt.Value)) {
  2935. std::string flag;
  2936. this->AppendFlagEscape(flag, opt.Value);
  2937. options.emplace_back(std::move(flag), opt.Backtrace);
  2938. }
  2939. }
  2940. } else {
  2941. for (BT<std::string> const& opt : options_vec) {
  2942. std::string flag;
  2943. this->AppendFlagEscape(flag, opt.Value);
  2944. options.emplace_back(std::move(flag), opt.Backtrace);
  2945. }
  2946. }
  2947. }
  2948. void cmLocalGenerator::AppendIncludeDirectories(
  2949. std::vector<std::string>& includes, const std::string& includes_list,
  2950. const cmSourceFile& sourceFile) const
  2951. {
  2952. // Short-circuit if there are no includes.
  2953. if (includes_list.empty()) {
  2954. return;
  2955. }
  2956. // Expand the list of includes.
  2957. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2958. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2959. }
  2960. void cmLocalGenerator::AppendIncludeDirectories(
  2961. std::vector<std::string>& includes,
  2962. const std::vector<std::string>& includes_vec,
  2963. const cmSourceFile& sourceFile) const
  2964. {
  2965. std::unordered_set<std::string> uniqueIncludes;
  2966. for (const std::string& include : includes_vec) {
  2967. if (!cmSystemTools::FileIsFullPath(include)) {
  2968. std::ostringstream e;
  2969. e << "Found relative path while evaluating include directories of "
  2970. "\""
  2971. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2972. << "\"\n";
  2973. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2974. return;
  2975. }
  2976. std::string inc = include;
  2977. if (!cmIsOff(inc)) {
  2978. cmSystemTools::ConvertToUnixSlashes(inc);
  2979. }
  2980. if (uniqueIncludes.insert(inc).second) {
  2981. includes.push_back(std::move(inc));
  2982. }
  2983. }
  2984. }
  2985. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2986. std::string const& defines_list) const
  2987. {
  2988. std::set<BT<std::string>> tmp;
  2989. this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
  2990. for (BT<std::string> const& i : tmp) {
  2991. defines.emplace(i.Value);
  2992. }
  2993. }
  2994. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2995. std::string const& defines_list) const
  2996. {
  2997. // Short-circuit if there are no definitions.
  2998. if (defines_list.empty()) {
  2999. return;
  3000. }
  3001. // Expand the list of definitions.
  3002. this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
  3003. }
  3004. void cmLocalGenerator::AppendDefines(
  3005. std::set<BT<std::string>>& defines,
  3006. const std::vector<BT<std::string>>& defines_vec) const
  3007. {
  3008. for (BT<std::string> const& d : defines_vec) {
  3009. // Skip unsupported definitions.
  3010. if (!this->CheckDefinition(d.Value)) {
  3011. continue;
  3012. }
  3013. // remove any leading -D
  3014. if (cmHasLiteralPrefix(d.Value, "-D")) {
  3015. defines.emplace(d.Value.substr(2), d.Backtrace);
  3016. } else {
  3017. defines.insert(d);
  3018. }
  3019. }
  3020. }
  3021. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  3022. std::string& definesString,
  3023. const std::string& lang)
  3024. {
  3025. // Lookup the define flag for the current language.
  3026. std::string dflag = "-D";
  3027. if (!lang.empty()) {
  3028. cmValue df =
  3029. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  3030. if (cmNonempty(df)) {
  3031. dflag = *df;
  3032. }
  3033. }
  3034. const char* itemSeparator = definesString.empty() ? "" : " ";
  3035. for (std::string const& define : defines) {
  3036. // Append the definition with proper escaping.
  3037. std::string def = dflag;
  3038. if (this->GetState()->UseWatcomWMake()) {
  3039. // The Watcom compiler does its own command line parsing instead
  3040. // of using the windows shell rules. Definitions are one of
  3041. // -DNAME
  3042. // -DNAME=<cpp-token>
  3043. // -DNAME="c-string with spaces and other characters(?@#$)"
  3044. //
  3045. // Watcom will properly parse each of these cases from the
  3046. // command line without any escapes. However we still have to
  3047. // get the '$' and '#' characters through WMake as '$$' and
  3048. // '$#'.
  3049. for (char c : define) {
  3050. if (c == '$' || c == '#') {
  3051. def += '$';
  3052. }
  3053. def += c;
  3054. }
  3055. } else {
  3056. // Make the definition appear properly on the command line. Use
  3057. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  3058. std::string::size_type eq = define.find('=');
  3059. def += define.substr(0, eq);
  3060. if (eq != std::string::npos) {
  3061. def += "=";
  3062. def += this->EscapeForShell(define.substr(eq + 1), true);
  3063. }
  3064. }
  3065. definesString += itemSeparator;
  3066. itemSeparator = " ";
  3067. definesString += def;
  3068. }
  3069. }
  3070. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  3071. const std::string& lang,
  3072. const char* feature)
  3073. {
  3074. cmValue optionList = this->Makefile->GetDefinition(
  3075. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  3076. if (optionList) {
  3077. std::vector<std::string> options = cmExpandedList(*optionList);
  3078. for (std::string const& o : options) {
  3079. this->AppendFlagEscape(flags, o);
  3080. }
  3081. }
  3082. }
  3083. cmValue cmLocalGenerator::GetFeature(const std::string& feature,
  3084. const std::string& config)
  3085. {
  3086. std::string featureName = feature;
  3087. // TODO: Define accumulation policy for features (prepend, append,
  3088. // replace). Currently we always replace.
  3089. if (!config.empty()) {
  3090. featureName += "_";
  3091. featureName += cmSystemTools::UpperCase(config);
  3092. }
  3093. cmStateSnapshot snp = this->StateSnapshot;
  3094. while (snp.IsValid()) {
  3095. if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
  3096. return value;
  3097. }
  3098. snp = snp.GetBuildsystemDirectoryParent();
  3099. }
  3100. return nullptr;
  3101. }
  3102. std::string cmLocalGenerator::GetProjectName() const
  3103. {
  3104. return this->StateSnapshot.GetProjectName();
  3105. }
  3106. std::string cmLocalGenerator::ConstructComment(
  3107. cmCustomCommandGenerator const& ccg, const char* default_comment) const
  3108. {
  3109. // Check for a comment provided with the command.
  3110. if (cm::optional<std::string> comment = ccg.GetComment()) {
  3111. return *comment;
  3112. }
  3113. // Construct a reasonable default comment if possible.
  3114. if (!ccg.GetOutputs().empty()) {
  3115. std::string comment;
  3116. comment = "Generating ";
  3117. const char* sep = "";
  3118. for (std::string const& o : ccg.GetOutputs()) {
  3119. comment += sep;
  3120. comment += this->MaybeRelativeToCurBinDir(o);
  3121. sep = ", ";
  3122. }
  3123. return comment;
  3124. }
  3125. // Otherwise use the provided default.
  3126. return default_comment;
  3127. }
  3128. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  3129. {
  3130. public:
  3131. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  3132. std::string const& dest, bool implib)
  3133. : cmInstallTargetGenerator(
  3134. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  3135. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  3136. false)
  3137. {
  3138. this->Compute(lg);
  3139. }
  3140. };
  3141. void cmLocalGenerator::GenerateTargetInstallRules(
  3142. std::ostream& os, const std::string& config,
  3143. std::vector<std::string> const& configurationTypes)
  3144. {
  3145. // Convert the old-style install specification from each target to
  3146. // an install generator and run it.
  3147. const auto& tgts = this->GetGeneratorTargets();
  3148. for (const auto& l : tgts) {
  3149. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3150. continue;
  3151. }
  3152. // Include the user-specified pre-install script for this target.
  3153. if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3154. cmInstallScriptGenerator g(*preinstall, false, "", false, false);
  3155. g.Generate(os, config, configurationTypes);
  3156. }
  3157. // Install this target if a destination is given.
  3158. if (!l->Target->GetInstallPath().empty()) {
  3159. // Compute the full install destination. Note that converting
  3160. // to unix slashes also removes any trailing slash.
  3161. // We also skip over the leading slash given by the user.
  3162. std::string destination = l->Target->GetInstallPath().substr(1);
  3163. cmSystemTools::ConvertToUnixSlashes(destination);
  3164. if (destination.empty()) {
  3165. destination = ".";
  3166. }
  3167. // Generate the proper install generator for this target type.
  3168. switch (l->GetType()) {
  3169. case cmStateEnums::EXECUTABLE:
  3170. case cmStateEnums::STATIC_LIBRARY:
  3171. case cmStateEnums::MODULE_LIBRARY: {
  3172. // Use a target install generator.
  3173. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3174. false);
  3175. g.Generate(os, config, configurationTypes);
  3176. } break;
  3177. case cmStateEnums::SHARED_LIBRARY: {
  3178. #if defined(_WIN32) || defined(__CYGWIN__)
  3179. // Special code to handle DLL. Install the import library
  3180. // to the normal destination and the DLL to the runtime
  3181. // destination.
  3182. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3183. true);
  3184. g1.Generate(os, config, configurationTypes);
  3185. // We also skip over the leading slash given by the user.
  3186. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3187. cmSystemTools::ConvertToUnixSlashes(destination);
  3188. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3189. false);
  3190. g2.Generate(os, config, configurationTypes);
  3191. #else
  3192. // Use a target install generator.
  3193. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3194. false);
  3195. g.Generate(os, config, configurationTypes);
  3196. #endif
  3197. } break;
  3198. default:
  3199. break;
  3200. }
  3201. }
  3202. // Include the user-specified post-install script for this target.
  3203. if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3204. cmInstallScriptGenerator g(*postinstall, false, "", false, false);
  3205. g.Generate(os, config, configurationTypes);
  3206. }
  3207. }
  3208. }
  3209. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  3210. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3211. std::string::size_type max_len)
  3212. {
  3213. // Check if the path can be shortened using an md5 sum replacement for
  3214. // a portion of the path.
  3215. std::string::size_type md5Len = 32;
  3216. std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
  3217. std::string::size_type pos = objName.find('/', numExtraChars);
  3218. if (pos == std::string::npos) {
  3219. pos = objName.rfind('/', numExtraChars);
  3220. if (pos == std::string::npos || pos <= md5Len) {
  3221. return false;
  3222. }
  3223. }
  3224. // Replace the beginning of the path portion of the object name with
  3225. // its own md5 sum.
  3226. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3227. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3228. cm::string_view(objName).substr(pos));
  3229. objName = md5name;
  3230. // The object name is now shorter, check if it is short enough.
  3231. return pos >= numExtraChars;
  3232. }
  3233. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3234. std::string::size_type dir_len,
  3235. std::string::size_type max_total_len)
  3236. {
  3237. // Enforce the maximum file name length if possible.
  3238. std::string::size_type max_obj_len = max_total_len;
  3239. if (dir_len < max_total_len) {
  3240. max_obj_len = max_total_len - dir_len;
  3241. if (objName.size() > max_obj_len) {
  3242. // The current object file name is too long. Try to shorten it.
  3243. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3244. }
  3245. // The object file name is short enough.
  3246. return true;
  3247. }
  3248. // The build directory in which the object will be stored is
  3249. // already too deep.
  3250. return false;
  3251. }
  3252. #endif
  3253. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3254. const std::string& sin, std::string const& dir_max)
  3255. {
  3256. // Look for an existing mapped name for this object file.
  3257. auto it = this->UniqueObjectNamesMap.find(sin);
  3258. // If no entry exists create one.
  3259. if (it == this->UniqueObjectNamesMap.end()) {
  3260. // Start with the original name.
  3261. std::string ssin = sin;
  3262. // Avoid full paths by removing leading slashes.
  3263. ssin.erase(0, ssin.find_first_not_of('/'));
  3264. // Avoid full paths by removing colons.
  3265. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3266. // Avoid relative paths that go up the tree.
  3267. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3268. // Avoid spaces.
  3269. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3270. // Mangle the name if necessary.
  3271. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3272. bool done;
  3273. int cc = 0;
  3274. char rpstr[100];
  3275. snprintf(rpstr, sizeof(rpstr), "_p_");
  3276. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3277. std::string sssin = sin;
  3278. do {
  3279. done = true;
  3280. for (it = this->UniqueObjectNamesMap.begin();
  3281. it != this->UniqueObjectNamesMap.end(); ++it) {
  3282. if (it->second == ssin) {
  3283. done = false;
  3284. }
  3285. }
  3286. if (done) {
  3287. break;
  3288. }
  3289. sssin = ssin;
  3290. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3291. snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
  3292. } while (!done);
  3293. }
  3294. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  3295. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3296. this->ObjectPathMax)) {
  3297. // Warn if this is the first time the path has been seen.
  3298. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3299. std::ostringstream m;
  3300. /* clang-format off */
  3301. m << "The object file directory\n"
  3302. << " " << dir_max << "\n"
  3303. << "has " << dir_max.size() << " characters. "
  3304. << "The maximum full path to an object file is "
  3305. << this->ObjectPathMax << " characters "
  3306. << "(see CMAKE_OBJECT_PATH_MAX). "
  3307. << "Object file\n"
  3308. << " " << ssin << "\n"
  3309. << "cannot be safely placed under this directory. "
  3310. << "The build may not work correctly.";
  3311. /* clang-format on */
  3312. this->IssueMessage(MessageType::WARNING, m.str());
  3313. }
  3314. }
  3315. #else
  3316. (void)dir_max;
  3317. #endif
  3318. // Insert the newly mapped object file name.
  3319. std::map<std::string, std::string>::value_type e(sin, ssin);
  3320. it = this->UniqueObjectNamesMap.insert(e).first;
  3321. }
  3322. // Return the map entry.
  3323. return it->second;
  3324. }
  3325. void cmLocalGenerator::ComputeObjectFilenames(
  3326. std::map<cmSourceFile const*, std::string>& /*unused*/,
  3327. cmGeneratorTarget const* /*unused*/)
  3328. {
  3329. }
  3330. bool cmLocalGenerator::IsWindowsShell() const
  3331. {
  3332. return this->GetState()->UseWindowsShell();
  3333. }
  3334. bool cmLocalGenerator::IsWatcomWMake() const
  3335. {
  3336. return this->GetState()->UseWatcomWMake();
  3337. }
  3338. bool cmLocalGenerator::IsMinGWMake() const
  3339. {
  3340. return this->GetState()->UseMinGWMake();
  3341. }
  3342. bool cmLocalGenerator::IsNMake() const
  3343. {
  3344. return this->GetState()->UseNMake();
  3345. }
  3346. bool cmLocalGenerator::IsNinjaMulti() const
  3347. {
  3348. return this->GetState()->UseNinjaMulti();
  3349. }
  3350. namespace {
  3351. std::string relativeIfUnder(std::string const& top, std::string const& cur,
  3352. std::string const& path)
  3353. {
  3354. // Use a path relative to 'cur' if it can be expressed without
  3355. // a `../` sequence that leaves 'top'.
  3356. if (cmSystemTools::IsSubDirectory(path, cur) ||
  3357. (cmSystemTools::IsSubDirectory(cur, top) &&
  3358. cmSystemTools::IsSubDirectory(path, top))) {
  3359. return cmSystemTools::ForceToRelativePath(cur, path);
  3360. }
  3361. return path;
  3362. }
  3363. }
  3364. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3365. const cmSourceFile& source, std::string const& dir_max,
  3366. bool* hasSourceExtension, char const* customOutputExtension)
  3367. {
  3368. // Construct the object file name using the full path to the source
  3369. // file which is its only unique identification.
  3370. std::string const& fullPath = source.GetFullPath();
  3371. // Try referencing the source relative to the source tree.
  3372. std::string relFromSource = relativeIfUnder(
  3373. this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
  3374. assert(!relFromSource.empty());
  3375. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3376. bool subSource = relSource && relFromSource[0] != '.';
  3377. // Try referencing the source relative to the binary tree.
  3378. std::string relFromBinary = relativeIfUnder(
  3379. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
  3380. assert(!relFromBinary.empty());
  3381. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3382. bool subBinary = relBinary && relFromBinary[0] != '.';
  3383. // Select a nice-looking reference to the source file to construct
  3384. // the object file name.
  3385. std::string objectName;
  3386. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3387. // NOLINTNEXTLINE(bugprone-branch-clone)
  3388. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3389. objectName = relFromSource;
  3390. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3391. relFromBinary.length() < relFromSource.length()) {
  3392. objectName = relFromBinary;
  3393. } else {
  3394. objectName = relFromSource;
  3395. }
  3396. // if it is still a full path check for the try compile case
  3397. // try compile never have in source sources, and should not
  3398. // have conflicting source file names in the same target
  3399. if (cmSystemTools::FileIsFullPath(objectName)) {
  3400. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  3401. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  3402. }
  3403. }
  3404. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  3405. // we don't end up having:
  3406. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  3407. cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  3408. cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
  3409. const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
  3410. if (unitySourceFile || pchExtension || isPchObject) {
  3411. if (pchExtension) {
  3412. customOutputExtension = pchExtension->c_str();
  3413. }
  3414. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  3415. if (var.find(objectName)) {
  3416. objectName.erase(var.start(), var.end() - var.start());
  3417. }
  3418. }
  3419. // Replace the original source file extension with the object file
  3420. // extension.
  3421. bool keptSourceExtension = true;
  3422. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  3423. // Decide whether this language wants to replace the source
  3424. // extension with the object extension. For CMake 2.4
  3425. // compatibility do this by default.
  3426. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  3427. if (!replaceExt) {
  3428. std::string lang = source.GetLanguage();
  3429. if (!lang.empty()) {
  3430. replaceExt = this->Makefile->IsOn(
  3431. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  3432. }
  3433. }
  3434. // Remove the source extension if it is to be replaced.
  3435. if (replaceExt || customOutputExtension) {
  3436. keptSourceExtension = false;
  3437. std::string::size_type dot_pos = objectName.rfind('.');
  3438. if (dot_pos != std::string::npos) {
  3439. objectName = objectName.substr(0, dot_pos);
  3440. }
  3441. }
  3442. // Store the new extension.
  3443. if (customOutputExtension) {
  3444. objectName += customOutputExtension;
  3445. } else {
  3446. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  3447. }
  3448. }
  3449. if (hasSourceExtension) {
  3450. *hasSourceExtension = keptSourceExtension;
  3451. }
  3452. // Convert to a safe name.
  3453. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  3454. }
  3455. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  3456. {
  3457. return source.GetLanguage();
  3458. }
  3459. cmake* cmLocalGenerator::GetCMakeInstance() const
  3460. {
  3461. return this->GlobalGenerator->GetCMakeInstance();
  3462. }
  3463. std::string const& cmLocalGenerator::GetSourceDirectory() const
  3464. {
  3465. return this->GetCMakeInstance()->GetHomeDirectory();
  3466. }
  3467. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  3468. {
  3469. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3470. }
  3471. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  3472. {
  3473. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  3474. }
  3475. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  3476. {
  3477. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  3478. }
  3479. std::string cmLocalGenerator::GetTargetDirectory(
  3480. const cmGeneratorTarget* /*unused*/) const
  3481. {
  3482. cmSystemTools::Error("GetTargetDirectory"
  3483. " called on cmLocalGenerator");
  3484. return "";
  3485. }
  3486. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3487. {
  3488. // The computed version may change until the project is fully
  3489. // configured.
  3490. if (!this->BackwardsCompatibilityFinal) {
  3491. unsigned int major = 0;
  3492. unsigned int minor = 0;
  3493. unsigned int patch = 0;
  3494. if (cmValue value =
  3495. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3496. switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
  3497. case 2:
  3498. patch = 0;
  3499. break;
  3500. case 1:
  3501. minor = 0;
  3502. patch = 0;
  3503. break;
  3504. default:
  3505. break;
  3506. }
  3507. }
  3508. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3509. this->BackwardsCompatibilityFinal = true;
  3510. }
  3511. return this->BackwardsCompatibility;
  3512. }
  3513. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3514. {
  3515. // Check the policy to decide whether to pay attention to this
  3516. // variable.
  3517. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3518. case cmPolicies::WARN:
  3519. // WARN is just OLD without warning because user code does not
  3520. // always affect whether this check is done.
  3521. CM_FALLTHROUGH;
  3522. case cmPolicies::OLD:
  3523. // Old behavior is to check the variable.
  3524. break;
  3525. case cmPolicies::NEW:
  3526. // New behavior is to ignore the variable.
  3527. case cmPolicies::REQUIRED_IF_USED:
  3528. case cmPolicies::REQUIRED_ALWAYS:
  3529. // This will never be the case because the only way to require
  3530. // the setting is to require the user to specify version policy
  3531. // 2.6 or higher. Once we add that requirement then this whole
  3532. // method can be removed anyway.
  3533. return false;
  3534. }
  3535. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3536. // equal to or lower than the given version.
  3537. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3538. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3539. }
  3540. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3541. cmPolicies::PolicyID id) const
  3542. {
  3543. return this->Makefile->GetPolicyStatus(id);
  3544. }
  3545. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3546. {
  3547. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3548. std::string::size_type pos = define.find_first_of("(=");
  3549. if (pos != std::string::npos) {
  3550. if (define[pos] == '(') {
  3551. std::ostringstream e;
  3552. /* clang-format off */
  3553. e << "WARNING: Function-style preprocessor definitions may not be "
  3554. << "passed on the compiler command line because many compilers "
  3555. << "do not support it.\n"
  3556. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3557. << "Consider defining the macro in a (configured) header file.\n";
  3558. /* clang-format on */
  3559. cmSystemTools::Message(e.str());
  3560. return false;
  3561. }
  3562. }
  3563. // Many compilers do not support # in the value so we disable it.
  3564. if (define.find_first_of('#') != std::string::npos) {
  3565. std::ostringstream e;
  3566. /* clang-format off */
  3567. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3568. << "passed on the compiler command line because many compilers "
  3569. << "do not support it.\n"
  3570. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3571. << "Consider defining the macro in a (configured) header file.\n";
  3572. /* clang-format on */
  3573. cmSystemTools::Message(e.str());
  3574. return false;
  3575. }
  3576. // Assume it is supported.
  3577. return true;
  3578. }
  3579. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3580. const std::string& prop)
  3581. {
  3582. if (cmValue val = target->GetProperty(prop)) {
  3583. mf->AddDefinition(prop, *val);
  3584. }
  3585. }
  3586. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3587. const std::string& targetName,
  3588. const std::string& fname)
  3589. {
  3590. // Find the Info.plist template.
  3591. cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3592. std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
  3593. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3594. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3595. if (!inMod.empty()) {
  3596. inFile = inMod;
  3597. }
  3598. }
  3599. if (!cmSystemTools::FileExists(inFile, true)) {
  3600. std::ostringstream e;
  3601. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3602. << "\" could not be found.";
  3603. cmSystemTools::Error(e.str());
  3604. return;
  3605. }
  3606. // Convert target properties to variables in an isolated makefile
  3607. // scope to configure the file. If properties are set they will
  3608. // override user make variables. If not the configuration will fall
  3609. // back to the directory-level values set by the user.
  3610. cmMakefile* mf = this->Makefile;
  3611. cmMakefile::ScopePushPop varScope(mf);
  3612. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3613. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3614. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3615. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3616. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3617. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3618. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3619. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3620. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3621. mf->ConfigureFile(inFile, fname, false, false, false);
  3622. }
  3623. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3624. cmGeneratorTarget* target, const std::string& targetName,
  3625. const std::string& fname)
  3626. {
  3627. // Find the Info.plist template.
  3628. cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3629. std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
  3630. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3631. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3632. if (!inMod.empty()) {
  3633. inFile = inMod;
  3634. }
  3635. }
  3636. if (!cmSystemTools::FileExists(inFile, true)) {
  3637. std::ostringstream e;
  3638. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3639. << "\" could not be found.";
  3640. cmSystemTools::Error(e.str());
  3641. return;
  3642. }
  3643. // Convert target properties to variables in an isolated makefile
  3644. // scope to configure the file. If properties are set they will
  3645. // override user make variables. If not the configuration will fall
  3646. // back to the directory-level values set by the user.
  3647. cmMakefile* mf = this->Makefile;
  3648. cmMakefile::ScopePushPop varScope(mf);
  3649. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3650. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3651. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3652. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3653. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3654. mf->ConfigureFile(inFile, fname, false, false, false);
  3655. }
  3656. namespace {
  3657. cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
  3658. {
  3659. return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
  3660. : "BYPRODUCTS"_s);
  3661. }
  3662. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3663. cmLocalGenerator::OutputRole role,
  3664. cmCommandOrigin origin,
  3665. const cmListFileBacktrace& lfbt)
  3666. {
  3667. if (cmGeneratorExpression::Find(output) != std::string::npos) {
  3668. lg.GetCMakeInstance()->IssueMessage(
  3669. MessageType::FATAL_ERROR,
  3670. "Generator expressions in custom command outputs are not implemented!",
  3671. lfbt);
  3672. return;
  3673. }
  3674. // Make sure the file will not be generated into the source
  3675. // directory during an out of source build.
  3676. if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
  3677. lg.GetCMakeInstance()->IssueMessage(
  3678. MessageType::FATAL_ERROR,
  3679. cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
  3680. "\nin a source directory as an output of custom command."),
  3681. lfbt);
  3682. return;
  3683. }
  3684. // Make sure the output file name has no invalid characters.
  3685. std::string::size_type pos = output.find_first_of("#<>");
  3686. if (pos != std::string::npos) {
  3687. lg.GetCMakeInstance()->IssueMessage(
  3688. MessageType::FATAL_ERROR,
  3689. cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
  3690. "\" is not allowed."),
  3691. lfbt);
  3692. return;
  3693. }
  3694. // Outputs without generator expressions from the project are already
  3695. // created and marked as generated. Do not mark them again, because
  3696. // other commands might have overwritten the property.
  3697. if (origin == cmCommandOrigin::Generator) {
  3698. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3699. }
  3700. }
  3701. std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
  3702. cmListFileBacktrace const& bt,
  3703. std::string const& output)
  3704. {
  3705. // If the output path has no generator expressions, use it directly.
  3706. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3707. return output;
  3708. }
  3709. // The output path contains a generator expression, but we must choose
  3710. // a single source file path to which to attach the custom command.
  3711. // Use some heuristics to provide a nice-looking name when possible.
  3712. // If the only genex is $<CONFIG>, replace that gracefully.
  3713. {
  3714. std::string simple = output;
  3715. cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
  3716. if (cmGeneratorExpression::Find(simple) == std::string::npos) {
  3717. return simple;
  3718. }
  3719. }
  3720. // If the genex evaluates to the same value in all configurations, use that.
  3721. {
  3722. std::vector<std::string> allConfigOutputs =
  3723. lg.ExpandCustomCommandOutputGenex(output, bt);
  3724. if (allConfigOutputs.size() == 1) {
  3725. return allConfigOutputs.front();
  3726. }
  3727. }
  3728. // Fall back to a deterministic unique name.
  3729. cmCryptoHash h(cmCryptoHash::AlgoSHA256);
  3730. return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
  3731. h.HashString(output).substr(0, 16));
  3732. }
  3733. cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3734. std::unique_ptr<cmCustomCommand> cc,
  3735. bool replace)
  3736. {
  3737. cmMakefile* mf = lg.GetMakefile();
  3738. const auto& lfbt = cc->GetBacktrace();
  3739. const auto& outputs = cc->GetOutputs();
  3740. const auto& byproducts = cc->GetByproducts();
  3741. const auto& commandLines = cc->GetCommandLines();
  3742. // Choose a source file on which to store the custom command.
  3743. cmSourceFile* file = nullptr;
  3744. if (!commandLines.empty() && cc->HasMainDependency()) {
  3745. const auto& main_dependency = cc->GetMainDependency();
  3746. // The main dependency was specified. Use it unless a different
  3747. // custom command already used it.
  3748. file = mf->GetSource(main_dependency);
  3749. if (file && file->GetCustomCommand() && !replace) {
  3750. // The main dependency already has a custom command.
  3751. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  3752. // The existing custom command is identical. Silently ignore
  3753. // the duplicate.
  3754. return file;
  3755. }
  3756. // The existing custom command is different. We need to
  3757. // generate a rule file for this new command.
  3758. file = nullptr;
  3759. } else if (!file) {
  3760. file = mf->CreateSource(main_dependency);
  3761. }
  3762. }
  3763. // Generate a rule file if the main dependency is not available.
  3764. if (!file) {
  3765. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  3766. // Construct a rule file associated with the first output produced.
  3767. std::string outName = gg->GenerateRuleFile(
  3768. ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
  3769. // Check if the rule file already exists.
  3770. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  3771. if (file && file->GetCustomCommand() && !replace) {
  3772. // The rule file already exists.
  3773. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  3774. lg.GetCMakeInstance()->IssueMessage(
  3775. MessageType::FATAL_ERROR,
  3776. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  3777. "\nwhich already has a custom rule."),
  3778. lfbt);
  3779. }
  3780. return file;
  3781. }
  3782. // Create a cmSourceFile for the rule file.
  3783. if (!file) {
  3784. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  3785. }
  3786. file->SetProperty("__CMAKE_RULE", "1");
  3787. }
  3788. // Attach the custom command to the file.
  3789. if (file) {
  3790. cc->SetEscapeAllowMakeVars(true);
  3791. lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
  3792. lfbt, origin);
  3793. lg.AddSourceOutputs(file, byproducts,
  3794. cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
  3795. file->SetCustomCommand(std::move(cc));
  3796. }
  3797. return file;
  3798. }
  3799. bool AnyOutputMatches(const std::string& name,
  3800. const std::vector<std::string>& outputs)
  3801. {
  3802. return std::any_of(outputs.begin(), outputs.end(),
  3803. [&name](std::string const& output) -> bool {
  3804. std::string::size_type pos = output.rfind(name);
  3805. // If the output matches exactly
  3806. return (pos != std::string::npos &&
  3807. pos == output.size() - name.size() &&
  3808. (pos == 0 || output[pos - 1] == '/'));
  3809. });
  3810. }
  3811. bool AnyTargetCommandOutputMatches(
  3812. const std::string& name, const std::vector<cmCustomCommand>& commands)
  3813. {
  3814. return std::any_of(commands.begin(), commands.end(),
  3815. [&name](cmCustomCommand const& command) -> bool {
  3816. return AnyOutputMatches(name, command.GetByproducts());
  3817. });
  3818. }
  3819. }
  3820. namespace detail {
  3821. void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
  3822. cmTarget* target, cmCustomCommandType type,
  3823. std::unique_ptr<cmCustomCommand> cc)
  3824. {
  3825. // Add the command to the appropriate build step for the target.
  3826. cc->SetEscapeAllowMakeVars(true);
  3827. cc->SetTarget(target->GetName());
  3828. lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
  3829. origin);
  3830. switch (type) {
  3831. case cmCustomCommandType::PRE_BUILD:
  3832. target->AddPreBuildCommand(std::move(*cc));
  3833. break;
  3834. case cmCustomCommandType::PRE_LINK:
  3835. target->AddPreLinkCommand(std::move(*cc));
  3836. break;
  3837. case cmCustomCommandType::POST_BUILD:
  3838. target->AddPostBuildCommand(std::move(*cc));
  3839. break;
  3840. }
  3841. cc.reset();
  3842. }
  3843. cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
  3844. cmCommandOrigin origin,
  3845. std::unique_ptr<cmCustomCommand> cc,
  3846. bool replace)
  3847. {
  3848. return AddCustomCommand(lg, origin, std::move(cc), replace);
  3849. }
  3850. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  3851. const cmListFileBacktrace& lfbt,
  3852. const std::string& output,
  3853. const std::vector<std::string>& depends,
  3854. const cmImplicitDependsList& implicit_depends,
  3855. const cmCustomCommandLines& commandLines)
  3856. {
  3857. // Lookup an existing command.
  3858. cmSourceFile* sf = nullptr;
  3859. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3860. sf = lg.GetSourceFileWithOutput(output);
  3861. } else {
  3862. // This output path has a generator expression. Evaluate it to
  3863. // find the output for any configurations.
  3864. for (std::string const& out :
  3865. lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
  3866. sf = lg.GetSourceFileWithOutput(out);
  3867. if (sf) {
  3868. break;
  3869. }
  3870. }
  3871. }
  3872. if (sf) {
  3873. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  3874. cc->AppendCommands(commandLines);
  3875. cc->AppendDepends(depends);
  3876. cc->AppendImplicitDepends(implicit_depends);
  3877. return;
  3878. }
  3879. }
  3880. // No existing command found.
  3881. lg.GetCMakeInstance()->IssueMessage(
  3882. MessageType::FATAL_ERROR,
  3883. cmStrCat("Attempt to APPEND to custom command with output\n ", output,
  3884. "\nwhich is not already a custom command output."),
  3885. lfbt);
  3886. }
  3887. void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3888. cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
  3889. {
  3890. // They might be moved away
  3891. auto byproducts = cc->GetByproducts();
  3892. auto lfbt = cc->GetBacktrace();
  3893. // Use an empty comment to avoid generation of default comment.
  3894. if (!cc->GetComment()) {
  3895. cc->SetComment("");
  3896. }
  3897. // Create the generated symbolic output name of the utility target.
  3898. std::string output =
  3899. lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
  3900. cc->SetOutputs(output);
  3901. cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
  3902. /*replace=*/false);
  3903. if (rule) {
  3904. lg.AddTargetByproducts(target, byproducts, lfbt, origin);
  3905. }
  3906. target->AddSource(output);
  3907. }
  3908. std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
  3909. {
  3910. const std::string& targetProperty =
  3911. target->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  3912. std::vector<std::string> ispcTargets;
  3913. if (!cmIsOff(targetProperty)) {
  3914. cmExpandList(targetProperty, ispcTargets);
  3915. for (auto& ispcTarget : ispcTargets) {
  3916. // transform targets into the suffixes
  3917. auto pos = ispcTarget.find('-');
  3918. auto target_suffix = ispcTarget.substr(0, pos);
  3919. if (target_suffix ==
  3920. "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
  3921. target_suffix = "avx";
  3922. }
  3923. ispcTarget = target_suffix;
  3924. }
  3925. }
  3926. return ispcTargets;
  3927. }
  3928. std::vector<std::string> ComputeISPCExtraObjects(
  3929. std::string const& objectName, std::string const& buildDirectory,
  3930. std::vector<std::string> const& ispcSuffixes)
  3931. {
  3932. auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
  3933. std::vector<std::string> computedObjects;
  3934. computedObjects.reserve(ispcSuffixes.size());
  3935. auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
  3936. // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
  3937. // drops any directories in objectName
  3938. auto objNameNoExt = objectName;
  3939. std::string::size_type dot_pos = objectName.rfind('.');
  3940. if (dot_pos != std::string::npos) {
  3941. objNameNoExt.resize(dot_pos);
  3942. }
  3943. for (const auto& ispcTarget : ispcSuffixes) {
  3944. computedObjects.emplace_back(
  3945. cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
  3946. }
  3947. return computedObjects;
  3948. }
  3949. }
  3950. cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
  3951. const std::string& name) const
  3952. {
  3953. // Linear search? Also see GetSourceFileWithOutput for detail.
  3954. if (!cmSystemTools::FileIsFullPath(name)) {
  3955. cmSourcesWithOutput sources;
  3956. sources.Target = this->LinearGetTargetWithOutput(name);
  3957. sources.Source = this->LinearGetSourceFileWithOutput(
  3958. name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
  3959. return sources;
  3960. }
  3961. // Otherwise we use an efficient lookup map.
  3962. auto o = this->OutputToSource.find(name);
  3963. if (o != this->OutputToSource.end()) {
  3964. return o->second.Sources;
  3965. }
  3966. return {};
  3967. }
  3968. cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
  3969. const std::string& name, cmSourceOutputKind kind) const
  3970. {
  3971. // If the queried path is not absolute we use the backward compatible
  3972. // linear-time search for an output with a matching suffix.
  3973. if (!cmSystemTools::FileIsFullPath(name)) {
  3974. bool byproduct = false;
  3975. return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
  3976. }
  3977. // Otherwise we use an efficient lookup map.
  3978. auto o = this->OutputToSource.find(name);
  3979. if (o != this->OutputToSource.end() &&
  3980. (!o->second.Sources.SourceIsByproduct ||
  3981. kind == cmSourceOutputKind::OutputOrByproduct)) {
  3982. // Source file could also be null pointer for example if we found the
  3983. // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
  3984. // command of a target, or a not yet created custom command.
  3985. return o->second.Sources.Source;
  3986. }
  3987. return nullptr;
  3988. }
  3989. std::string cmLocalGenerator::CreateUtilityOutput(
  3990. std::string const& targetName, std::vector<std::string> const&,
  3991. cmListFileBacktrace const&)
  3992. {
  3993. std::string force =
  3994. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
  3995. // The output is not actually created so mark it symbolic.
  3996. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  3997. sf->SetProperty("SYMBOLIC", "1");
  3998. } else {
  3999. cmSystemTools::Error("Could not get source file entry for " + force);
  4000. }
  4001. return force;
  4002. }
  4003. std::vector<cmCustomCommandGenerator>
  4004. cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
  4005. std::string const& config)
  4006. {
  4007. std::vector<cmCustomCommandGenerator> ccgs;
  4008. ccgs.emplace_back(cc, config, this);
  4009. return ccgs;
  4010. }
  4011. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
  4012. cmCompiledGeneratorExpression const& cge, std::string const& config)
  4013. {
  4014. std::vector<std::string> paths = cmExpandedList(cge.Evaluate(this, config));
  4015. for (std::string& p : paths) {
  4016. p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
  4017. }
  4018. return paths;
  4019. }
  4020. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
  4021. std::string const& o, cmListFileBacktrace const& bt)
  4022. {
  4023. std::vector<std::string> allConfigOutputs;
  4024. cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
  4025. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
  4026. std::vector<std::string> configs =
  4027. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4028. for (std::string const& config : configs) {
  4029. std::vector<std::string> configOutputs =
  4030. this->ExpandCustomCommandOutputPaths(*cge, config);
  4031. allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
  4032. std::move(configOutputs.begin(), configOutputs.end(),
  4033. std::back_inserter(allConfigOutputs));
  4034. }
  4035. auto endUnique =
  4036. cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
  4037. allConfigOutputs.erase(endUnique, allConfigOutputs.end());
  4038. return allConfigOutputs;
  4039. }
  4040. void cmLocalGenerator::AddTargetByproducts(
  4041. cmTarget* target, const std::vector<std::string>& byproducts,
  4042. cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4043. {
  4044. for (std::string const& o : byproducts) {
  4045. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4046. this->UpdateOutputToSourceMap(o, target, bt, origin);
  4047. continue;
  4048. }
  4049. // This byproduct path has a generator expression. Evaluate it to
  4050. // register the byproducts for all configurations.
  4051. for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
  4052. this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
  4053. }
  4054. }
  4055. }
  4056. void cmLocalGenerator::AddSourceOutputs(
  4057. cmSourceFile* source, const std::vector<std::string>& outputs,
  4058. OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4059. {
  4060. for (std::string const& o : outputs) {
  4061. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4062. this->UpdateOutputToSourceMap(o, source, role, bt, origin);
  4063. continue;
  4064. }
  4065. // This output path has a generator expression. Evaluate it to
  4066. // register the outputs for all configurations.
  4067. for (std::string const& out :
  4068. this->ExpandCustomCommandOutputGenex(o, bt)) {
  4069. this->UpdateOutputToSourceMap(out, source, role, bt,
  4070. cmCommandOrigin::Generator);
  4071. }
  4072. }
  4073. }
  4074. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
  4075. cmTarget* target,
  4076. cmListFileBacktrace const& bt,
  4077. cmCommandOrigin origin)
  4078. {
  4079. SourceEntry entry;
  4080. entry.Sources.Target = target;
  4081. auto pr = this->OutputToSource.emplace(byproduct, entry);
  4082. if (pr.second) {
  4083. CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
  4084. } else {
  4085. SourceEntry& current = pr.first->second;
  4086. // Has the target already been set?
  4087. if (!current.Sources.Target) {
  4088. current.Sources.Target = target;
  4089. } else {
  4090. // Multiple custom commands/targets produce the same output (source file
  4091. // or target). See also comment in other UpdateOutputToSourceMap
  4092. // overload.
  4093. //
  4094. // TODO: Warn the user about this case.
  4095. }
  4096. }
  4097. }
  4098. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
  4099. cmSourceFile* source,
  4100. OutputRole role,
  4101. cmListFileBacktrace const& bt,
  4102. cmCommandOrigin origin)
  4103. {
  4104. SourceEntry entry;
  4105. entry.Sources.Source = source;
  4106. entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
  4107. auto pr = this->OutputToSource.emplace(output, entry);
  4108. if (pr.second) {
  4109. CreateGeneratedSource(*this, output, role, origin, bt);
  4110. } else {
  4111. SourceEntry& current = pr.first->second;
  4112. // Outputs take precedence over byproducts
  4113. if (!current.Sources.Source ||
  4114. (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
  4115. current.Sources.Source = source;
  4116. current.Sources.SourceIsByproduct = false;
  4117. } else {
  4118. // Multiple custom commands produce the same output but may
  4119. // be attached to a different source file (MAIN_DEPENDENCY).
  4120. // LinearGetSourceFileWithOutput would return the first one,
  4121. // so keep the mapping for the first one.
  4122. //
  4123. // TODO: Warn the user about this case. However, the VS 8 generator
  4124. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  4125. // individual targets.
  4126. }
  4127. }
  4128. }
  4129. cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
  4130. const std::string& name) const
  4131. {
  4132. // We go through the ordered vector of targets to get reproducible results
  4133. // should multiple names match.
  4134. for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
  4135. // Does the output of any command match the source file name?
  4136. if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
  4137. return t;
  4138. }
  4139. if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
  4140. return t;
  4141. }
  4142. if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
  4143. return t;
  4144. }
  4145. }
  4146. return nullptr;
  4147. }
  4148. cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
  4149. const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
  4150. {
  4151. // Outputs take precedence over byproducts.
  4152. byproduct = false;
  4153. cmSourceFile* fallback = nullptr;
  4154. // Look through all the source files that have custom commands and see if the
  4155. // custom command has the passed source file as an output.
  4156. for (const auto& src : this->Makefile->GetSourceFiles()) {
  4157. // Does this source file have a custom command?
  4158. if (src->GetCustomCommand()) {
  4159. // Does the output of the custom command match the source file name?
  4160. if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
  4161. // Return the first matching output.
  4162. return src.get();
  4163. }
  4164. if (kind == cmSourceOutputKind::OutputOrByproduct) {
  4165. if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
  4166. // Do not return the source yet as there might be a matching output.
  4167. fallback = src.get();
  4168. }
  4169. }
  4170. }
  4171. }
  4172. // Did we find a byproduct?
  4173. byproduct = fallback != nullptr;
  4174. return fallback;
  4175. }