cmLocalGenerator.cxx 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659
  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. cmValue cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  746. const std::string& prop)
  747. {
  748. if (target) {
  749. return target->GetProperty(prop);
  750. }
  751. return this->Makefile->GetProperty(prop);
  752. }
  753. std::string cmLocalGenerator::ConvertToIncludeReference(
  754. std::string const& path, OutputFormat format)
  755. {
  756. return this->ConvertToOutputForExisting(path, format);
  757. }
  758. std::string cmLocalGenerator::GetIncludeFlags(
  759. std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
  760. std::string const& lang, std::string const& config, bool forResponseFile)
  761. {
  762. if (lang.empty()) {
  763. return "";
  764. }
  765. std::vector<std::string> includes = includeDirs;
  766. MoveSystemIncludesToEnd(includes, config, lang, target);
  767. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  768. std::ostringstream includeFlags;
  769. std::string const& includeFlag =
  770. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  771. bool quotePaths = false;
  772. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  773. quotePaths = true;
  774. }
  775. std::string sep = " ";
  776. bool repeatFlag = true;
  777. // should the include flag be repeated like ie. -IA -IB
  778. if (cmValue incSep = this->Makefile->GetDefinition(
  779. cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
  780. // if there is a separator then the flag is not repeated but is only
  781. // given once i.e. -classpath a:b:c
  782. sep = incSep;
  783. repeatFlag = false;
  784. }
  785. // Support special system include flag if it is available and the
  786. // normal flag is repeated for each directory.
  787. cmValue sysIncludeFlag = nullptr;
  788. cmValue sysIncludeFlagWarning = nullptr;
  789. if (repeatFlag) {
  790. sysIncludeFlag = this->Makefile->GetDefinition(
  791. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  792. sysIncludeFlagWarning = this->Makefile->GetDefinition(
  793. cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
  794. }
  795. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  796. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  797. cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
  798. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  799. bool flagUsed = false;
  800. bool sysIncludeFlagUsed = false;
  801. std::set<std::string> emitted;
  802. #ifdef __APPLE__
  803. emitted.insert("/System/Library/Frameworks");
  804. #endif
  805. for (std::string const& i : includes) {
  806. if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
  807. cmSystemTools::IsPathToFramework(i)) {
  808. std::string const frameworkDir =
  809. cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
  810. if (emitted.insert(frameworkDir).second) {
  811. if (sysFwSearchFlag && target &&
  812. target->IsSystemIncludeDirectory(i, config, lang)) {
  813. includeFlags << *sysFwSearchFlag;
  814. } else {
  815. includeFlags << *fwSearchFlag;
  816. }
  817. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  818. << " ";
  819. }
  820. continue;
  821. }
  822. if (!flagUsed || repeatFlag) {
  823. if (sysIncludeFlag && target &&
  824. target->IsSystemIncludeDirectory(i, config, lang)) {
  825. includeFlags << *sysIncludeFlag;
  826. sysIncludeFlagUsed = true;
  827. } else {
  828. includeFlags << includeFlag;
  829. }
  830. flagUsed = true;
  831. }
  832. std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
  833. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  834. includeFlags << "\"";
  835. }
  836. includeFlags << includePath;
  837. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  838. includeFlags << "\"";
  839. }
  840. includeFlags << sep;
  841. }
  842. if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
  843. includeFlags << *sysIncludeFlagWarning;
  844. }
  845. std::string flags = includeFlags.str();
  846. // remove trailing separators
  847. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  848. flags.back() = ' ';
  849. }
  850. return cmTrimWhitespace(flags);
  851. }
  852. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  853. cmGeneratorTarget* target,
  854. const std::string& lang,
  855. const std::string& config)
  856. {
  857. std::vector<BT<std::string>> tmpFlags;
  858. this->AddCompileOptions(tmpFlags, target, lang, config);
  859. this->AppendFlags(flags, tmpFlags);
  860. }
  861. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  862. cmGeneratorTarget* target,
  863. const std::string& lang,
  864. const std::string& config)
  865. {
  866. std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
  867. if (cmValue langFlagRegexStr =
  868. this->Makefile->GetDefinition(langFlagRegexVar)) {
  869. // Filter flags acceptable to this language.
  870. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  871. std::vector<std::string> opts;
  872. cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
  873. // Re-escape these flags since COMPILE_FLAGS were already parsed
  874. // as a command line above.
  875. std::string compileOpts;
  876. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
  877. if (!compileOpts.empty()) {
  878. flags.emplace_back(std::move(compileOpts));
  879. }
  880. }
  881. std::vector<BT<std::string>> targetCompileOpts =
  882. target->GetCompileOptions(config, lang);
  883. // COMPILE_OPTIONS are escaped.
  884. this->AppendCompileOptions(flags, targetCompileOpts,
  885. langFlagRegexStr->c_str());
  886. } else {
  887. // Use all flags.
  888. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  889. // COMPILE_FLAGS are not escaped for historical reasons.
  890. std::string compileFlags;
  891. this->AppendFlags(compileFlags, *targetFlags);
  892. if (!compileFlags.empty()) {
  893. flags.emplace_back(std::move(compileFlags));
  894. }
  895. }
  896. std::vector<BT<std::string>> targetCompileOpts =
  897. target->GetCompileOptions(config, lang);
  898. // COMPILE_OPTIONS are escaped.
  899. this->AppendCompileOptions(flags, targetCompileOpts);
  900. }
  901. cmStandardLevelResolver standardResolver(this->Makefile);
  902. for (auto const& it : target->GetMaxLanguageStandards()) {
  903. cmValue standard = target->GetLanguageStandard(it.first, config);
  904. if (!standard) {
  905. continue;
  906. }
  907. if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
  908. std::ostringstream e;
  909. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  910. << "\" was evaluated when computing the link "
  911. "implementation, and the \""
  912. << it.first << "_STANDARD\" was \"" << it.second
  913. << "\" for that computation. Computing the "
  914. "COMPILE_FEATURES based on the link implementation resulted in a "
  915. "higher \""
  916. << it.first << "_STANDARD\" \"" << *standard
  917. << "\". "
  918. "This is not permitted. The COMPILE_FEATURES may not both depend "
  919. "on "
  920. "and be depended on by the link implementation.\n";
  921. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  922. return;
  923. }
  924. }
  925. std::string compReqFlag;
  926. this->AddCompilerRequirementFlag(compReqFlag, target, lang, config);
  927. if (!compReqFlag.empty()) {
  928. flags.emplace_back(std::move(compReqFlag));
  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. // iterate link deps and see if any of them need IPO
  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. std::string compiler = this->Makefile->GetSafeDefinition(
  1732. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1733. std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
  1734. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1735. if (lang == "Swift") {
  1736. if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1737. if (cmSystemTools::VersionCompare(
  1738. cmSystemTools::OP_GREATER_EQUAL,
  1739. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1740. "4.2")) {
  1741. this->AppendFlags(flags, "-swift-version " + *v);
  1742. }
  1743. }
  1744. } else if (lang == "CUDA") {
  1745. target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
  1746. target->AddCUDAToolkitFlags(flags);
  1747. } else if (lang == "ISPC") {
  1748. target->AddISPCTargetFlags(flags);
  1749. } else if (lang == "RC" &&
  1750. this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
  1751. .find("llvm-rc") != std::string::npos) {
  1752. compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
  1753. if (!compiler.empty()) {
  1754. compilerSimulateId =
  1755. this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
  1756. } else {
  1757. compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
  1758. compilerSimulateId =
  1759. this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
  1760. }
  1761. } else if (lang == "HIP") {
  1762. target->AddHIPArchitectureFlags(flags);
  1763. }
  1764. // Add VFS Overlay for Clang compilers
  1765. if (compiler == "Clang") {
  1766. if (cmValue vfsOverlay =
  1767. this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
  1768. if (compilerSimulateId == "MSVC") {
  1769. this->AppendCompileOptions(
  1770. flags,
  1771. std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
  1772. *vfsOverlay });
  1773. } else {
  1774. this->AppendCompileOptions(
  1775. flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
  1776. }
  1777. }
  1778. }
  1779. // Add MSVC runtime library flags. This is activated by the presence
  1780. // of a default selection whether or not it is overridden by a property.
  1781. cmValue msvcRuntimeLibraryDefault =
  1782. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1783. if (cmNonempty(msvcRuntimeLibraryDefault)) {
  1784. cmValue msvcRuntimeLibraryValue =
  1785. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1786. if (!msvcRuntimeLibraryValue) {
  1787. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1788. }
  1789. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1790. *msvcRuntimeLibraryValue, this, config, target);
  1791. if (!msvcRuntimeLibrary.empty()) {
  1792. if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1793. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1794. msvcRuntimeLibrary)) {
  1795. this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
  1796. } else if ((this->Makefile->GetSafeDefinition(
  1797. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1798. this->Makefile->GetSafeDefinition(
  1799. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1800. !cmSystemTools::GetErrorOccurredFlag()) {
  1801. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1802. this->IssueMessage(MessageType::FATAL_ERROR,
  1803. "MSVC_RUNTIME_LIBRARY value '" +
  1804. msvcRuntimeLibrary + "' not known for this " +
  1805. lang + " compiler.");
  1806. }
  1807. }
  1808. }
  1809. // Add Watcom runtime library flags. This is activated by the presence
  1810. // of a default selection whether or not it is overridden by a property.
  1811. cmValue watcomRuntimeLibraryDefault =
  1812. this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
  1813. if (cmNonempty(watcomRuntimeLibraryDefault)) {
  1814. cmValue watcomRuntimeLibraryValue =
  1815. target->GetProperty("WATCOM_RUNTIME_LIBRARY");
  1816. if (!watcomRuntimeLibraryValue) {
  1817. watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
  1818. }
  1819. std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1820. *watcomRuntimeLibraryValue, this, config, target);
  1821. if (!watcomRuntimeLibrary.empty()) {
  1822. if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1823. "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
  1824. watcomRuntimeLibrary)) {
  1825. this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
  1826. } else if ((this->Makefile->GetSafeDefinition(
  1827. "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
  1828. this->Makefile->GetSafeDefinition(
  1829. "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
  1830. !cmSystemTools::GetErrorOccurredFlag()) {
  1831. // The compiler uses the Watcom ABI so it needs a known runtime
  1832. // library.
  1833. this->IssueMessage(MessageType::FATAL_ERROR,
  1834. "WATCOM_RUNTIME_LIBRARY value '" +
  1835. watcomRuntimeLibrary + "' not known for this " +
  1836. lang + " compiler.");
  1837. }
  1838. }
  1839. }
  1840. // Add MSVC debug information format flags if CMP0141 is NEW.
  1841. if (cm::optional<std::string> msvcDebugInformationFormat =
  1842. this->GetMSVCDebugFormatName(config, target)) {
  1843. if (!msvcDebugInformationFormat->empty()) {
  1844. if (cmValue msvcDebugInformationFormatOptions =
  1845. this->Makefile->GetDefinition(
  1846. cmStrCat("CMAKE_", lang,
  1847. "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
  1848. *msvcDebugInformationFormat))) {
  1849. this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
  1850. } else if ((this->Makefile->GetSafeDefinition(
  1851. cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
  1852. this->Makefile->GetSafeDefinition(
  1853. cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
  1854. !cmSystemTools::GetErrorOccurredFlag()) {
  1855. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1856. this->IssueMessage(MessageType::FATAL_ERROR,
  1857. cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
  1858. *msvcDebugInformationFormat,
  1859. "' not known for this ", lang,
  1860. " compiler."));
  1861. }
  1862. }
  1863. }
  1864. }
  1865. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1866. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1867. const std::string& config)
  1868. {
  1869. if (this->Makefile->IsOn("CMAKE_" + lang +
  1870. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1871. // This toolchain requires use of the language standard flag
  1872. // when linking in order to use the matching standard library.
  1873. // FIXME: If CMake gains an abstraction for standard library
  1874. // selection, this will have to be reconciled with it.
  1875. this->AddCompilerRequirementFlag(flags, target, lang, config);
  1876. }
  1877. this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
  1878. if (target->IsIPOEnabled(lang, config)) {
  1879. this->AppendFeatureOptions(flags, lang, "IPO");
  1880. }
  1881. }
  1882. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1883. const std::string& name) const
  1884. {
  1885. auto imported = this->ImportedGeneratorTargets.find(name);
  1886. if (imported != this->ImportedGeneratorTargets.end()) {
  1887. return imported->second;
  1888. }
  1889. // find local alias to imported target
  1890. auto aliased = this->AliasTargets.find(name);
  1891. if (aliased != this->AliasTargets.end()) {
  1892. imported = this->ImportedGeneratorTargets.find(aliased->second);
  1893. if (imported != this->ImportedGeneratorTargets.end()) {
  1894. return imported->second;
  1895. }
  1896. }
  1897. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1898. return t;
  1899. }
  1900. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1901. }
  1902. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1903. const std::string& config,
  1904. std::string& dep)
  1905. {
  1906. // Older CMake code may specify the dependency using the target
  1907. // output file rather than the target name. Such code would have
  1908. // been written before there was support for target properties that
  1909. // modify the name so stripping down to just the file name should
  1910. // produce the target name in this case.
  1911. std::string name = cmSystemTools::GetFilenameName(inName);
  1912. // If the input name is the empty string, there is no real
  1913. // dependency. Short-circuit the other checks:
  1914. if (name.empty()) {
  1915. return false;
  1916. }
  1917. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1918. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1919. }
  1920. // Look for a CMake target with the given name.
  1921. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1922. // make sure it is not just a coincidence that the target name
  1923. // found is part of the inName
  1924. if (cmSystemTools::FileIsFullPath(inName)) {
  1925. std::string tLocation;
  1926. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1927. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1928. tLocation = target->GetLocation(config);
  1929. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1930. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1931. }
  1932. std::string depLocation =
  1933. cmSystemTools::GetFilenamePath(std::string(inName));
  1934. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1935. if (depLocation != tLocation) {
  1936. // it is a full path to a depend that has the same name
  1937. // as a target but is in a different location so do not use
  1938. // the target as the depend
  1939. dep = inName;
  1940. return true;
  1941. }
  1942. }
  1943. switch (target->GetType()) {
  1944. case cmStateEnums::EXECUTABLE:
  1945. case cmStateEnums::STATIC_LIBRARY:
  1946. case cmStateEnums::SHARED_LIBRARY:
  1947. case cmStateEnums::MODULE_LIBRARY:
  1948. case cmStateEnums::UNKNOWN_LIBRARY:
  1949. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  1950. /*realname=*/true);
  1951. return true;
  1952. case cmStateEnums::OBJECT_LIBRARY:
  1953. // An object library has no single file on which to depend.
  1954. // This was listed to get the target-level dependency.
  1955. case cmStateEnums::INTERFACE_LIBRARY:
  1956. // An interface library has no file on which to depend.
  1957. // This was listed to get the target-level dependency.
  1958. case cmStateEnums::UTILITY:
  1959. case cmStateEnums::GLOBAL_TARGET:
  1960. // A utility target has no file on which to depend. This was listed
  1961. // only to get the target-level dependency.
  1962. return false;
  1963. }
  1964. }
  1965. // The name was not that of a CMake target. It must name a file.
  1966. if (cmSystemTools::FileIsFullPath(inName)) {
  1967. // This is a full path. Return it as given.
  1968. dep = inName;
  1969. return true;
  1970. }
  1971. // Check for a source file in this directory that matches the
  1972. // dependency.
  1973. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1974. dep = sf->ResolveFullPath();
  1975. return true;
  1976. }
  1977. // Treat the name as relative to the source directory in which it
  1978. // was given.
  1979. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  1980. // If the in-source path does not exist, assume it instead lives in the
  1981. // binary directory.
  1982. if (!cmSystemTools::FileExists(dep)) {
  1983. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  1984. }
  1985. dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
  1986. return true;
  1987. }
  1988. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1989. const std::string& lang, bool shared)
  1990. {
  1991. std::string flagsVar;
  1992. // Add flags for dealing with shared libraries for this language.
  1993. if (shared) {
  1994. this->AppendFlags(flags,
  1995. this->Makefile->GetSafeDefinition(
  1996. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1997. }
  1998. }
  1999. void cmLocalGenerator::AddCompilerRequirementFlag(
  2000. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  2001. const std::string& config)
  2002. {
  2003. cmStandardLevelResolver standardResolver(this->Makefile);
  2004. std::string const& optionFlagDef =
  2005. standardResolver.GetCompileOptionDef(target, lang, config);
  2006. if (!optionFlagDef.empty()) {
  2007. cmValue opt = target->Target->GetMakefile()->GetDefinition(optionFlagDef);
  2008. if (opt) {
  2009. std::vector<std::string> optVec = cmExpandedList(*opt);
  2010. for (std::string const& i : optVec) {
  2011. this->AppendFlagEscape(flags, i);
  2012. }
  2013. }
  2014. }
  2015. }
  2016. static void AddVisibilityCompileOption(std::string& flags,
  2017. cmGeneratorTarget const* target,
  2018. cmLocalGenerator* lg,
  2019. const std::string& lang,
  2020. std::string* warnCMP0063)
  2021. {
  2022. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2023. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2024. if (!opt) {
  2025. return;
  2026. }
  2027. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2028. cmValue prop = target->GetProperty(flagDefine);
  2029. if (!prop) {
  2030. return;
  2031. }
  2032. if (warnCMP0063) {
  2033. *warnCMP0063 += " " + flagDefine + "\n";
  2034. return;
  2035. }
  2036. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2037. (*prop != "internal")) {
  2038. std::ostringstream e;
  2039. e << "Target " << target->GetName() << " uses unsupported value \""
  2040. << *prop << "\" for " << flagDefine << "."
  2041. << " The supported values are: default, hidden, protected, and "
  2042. "internal.";
  2043. cmSystemTools::Error(e.str());
  2044. return;
  2045. }
  2046. std::string option = *opt + *prop;
  2047. lg->AppendFlags(flags, option);
  2048. }
  2049. static void AddInlineVisibilityCompileOption(std::string& flags,
  2050. cmGeneratorTarget const* target,
  2051. cmLocalGenerator* lg,
  2052. std::string* warnCMP0063,
  2053. const std::string& lang)
  2054. {
  2055. std::string compileOption =
  2056. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2057. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2058. if (!opt) {
  2059. return;
  2060. }
  2061. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2062. if (!prop) {
  2063. return;
  2064. }
  2065. if (warnCMP0063) {
  2066. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2067. return;
  2068. }
  2069. lg->AppendFlags(flags, *opt);
  2070. }
  2071. void cmLocalGenerator::AddVisibilityPresetFlags(
  2072. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2073. {
  2074. if (lang.empty()) {
  2075. return;
  2076. }
  2077. std::string warnCMP0063;
  2078. std::string* pWarnCMP0063 = nullptr;
  2079. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2080. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2081. !target->IsExecutableWithExports()) {
  2082. switch (target->GetPolicyStatusCMP0063()) {
  2083. case cmPolicies::OLD:
  2084. return;
  2085. case cmPolicies::WARN:
  2086. pWarnCMP0063 = &warnCMP0063;
  2087. break;
  2088. default:
  2089. break;
  2090. }
  2091. }
  2092. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2093. if (lang == "CXX" || lang == "OBJCXX") {
  2094. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2095. }
  2096. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2097. std::ostringstream w;
  2098. /* clang-format off */
  2099. w <<
  2100. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2101. "Target \"" << target->GetName() << "\" of "
  2102. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2103. "has the following visibility properties set for " << lang << ":\n" <<
  2104. warnCMP0063 <<
  2105. "For compatibility CMake is not honoring them for this target.";
  2106. /* clang-format on */
  2107. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2108. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2109. }
  2110. }
  2111. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2112. cmGeneratorTarget const* target,
  2113. std::string const& lang,
  2114. const std::string& config)
  2115. {
  2116. int targetType = target->GetType();
  2117. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2118. (targetType == cmStateEnums::MODULE_LIBRARY));
  2119. if (this->GetShouldUseOldFlags(shared, lang)) {
  2120. this->AddSharedFlags(flags, lang, shared);
  2121. } else {
  2122. if (target->GetLinkInterfaceDependentBoolProperty(
  2123. "POSITION_INDEPENDENT_CODE", config)) {
  2124. this->AddPositionIndependentFlags(flags, lang, targetType);
  2125. }
  2126. if (shared) {
  2127. this->AppendFeatureOptions(flags, lang, "DLL");
  2128. }
  2129. }
  2130. }
  2131. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2132. const std::string& lang) const
  2133. {
  2134. std::string originalFlags =
  2135. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2136. if (shared) {
  2137. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2138. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2139. if (flags != originalFlags) {
  2140. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2141. case cmPolicies::WARN: {
  2142. std::ostringstream e;
  2143. e << "Variable " << flagsVar
  2144. << " has been modified. CMake "
  2145. "will ignore the POSITION_INDEPENDENT_CODE target property "
  2146. "for "
  2147. "shared libraries and will use the "
  2148. << flagsVar
  2149. << " variable "
  2150. "instead. This may cause errors if the original content of "
  2151. << flagsVar << " was removed.\n"
  2152. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2153. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2154. CM_FALLTHROUGH;
  2155. }
  2156. case cmPolicies::OLD:
  2157. return true;
  2158. case cmPolicies::REQUIRED_IF_USED:
  2159. case cmPolicies::REQUIRED_ALWAYS:
  2160. case cmPolicies::NEW:
  2161. return false;
  2162. }
  2163. }
  2164. }
  2165. return false;
  2166. }
  2167. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2168. std::string const& lang,
  2169. int targetType)
  2170. {
  2171. std::string picFlags;
  2172. if (targetType == cmStateEnums::EXECUTABLE) {
  2173. picFlags = this->Makefile->GetSafeDefinition(
  2174. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2175. }
  2176. if (picFlags.empty()) {
  2177. picFlags = this->Makefile->GetSafeDefinition(
  2178. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2179. }
  2180. if (!picFlags.empty()) {
  2181. std::vector<std::string> options = cmExpandedList(picFlags);
  2182. for (std::string const& o : options) {
  2183. this->AppendFlagEscape(flags, o);
  2184. }
  2185. }
  2186. }
  2187. void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
  2188. const std::string& lang)
  2189. {
  2190. cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
  2191. if (diag.IsSet()) {
  2192. std::string colorFlagName;
  2193. if (diag.IsOn()) {
  2194. colorFlagName =
  2195. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
  2196. } else {
  2197. colorFlagName =
  2198. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
  2199. }
  2200. std::vector<std::string> options;
  2201. this->Makefile->GetDefExpandList(colorFlagName, options);
  2202. for (std::string const& option : options) {
  2203. this->AppendFlagEscape(flags, option);
  2204. }
  2205. }
  2206. }
  2207. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2208. const std::string& var,
  2209. const std::string& config)
  2210. {
  2211. // Add the flags from the variable itself.
  2212. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2213. // Add the flags from the build-type specific variable.
  2214. if (!config.empty()) {
  2215. const std::string flagsVar =
  2216. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2217. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2218. }
  2219. }
  2220. void cmLocalGenerator::AppendFlags(std::string& flags,
  2221. const std::string& newFlags) const
  2222. {
  2223. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2224. if (!newFlags.empty() && !allSpaces) {
  2225. if (!flags.empty()) {
  2226. flags += " ";
  2227. }
  2228. flags += newFlags;
  2229. }
  2230. }
  2231. void cmLocalGenerator::AppendFlags(
  2232. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2233. {
  2234. for (BT<std::string> const& flag : newFlags) {
  2235. this->AppendFlags(flags, flag.Value);
  2236. }
  2237. }
  2238. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2239. const std::string& rawFlag) const
  2240. {
  2241. this->AppendFlags(
  2242. flags,
  2243. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2244. }
  2245. void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
  2246. {
  2247. std::vector<std::string> enabledLanguages =
  2248. this->GetState()->GetEnabledLanguages();
  2249. if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
  2250. enabledLanguages.end()) {
  2251. return;
  2252. }
  2253. cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
  2254. assert(ispcHeaderSuffixProp);
  2255. std::vector<std::string> ispcArchSuffixes =
  2256. detail::ComputeISPCObjectSuffixes(target);
  2257. const bool extra_objects = (ispcArchSuffixes.size() > 1);
  2258. std::vector<std::string> configsList =
  2259. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2260. for (std::string const& config : configsList) {
  2261. std::string rootObjectDir = target->GetObjectDirectory(config);
  2262. std::string headerDir = rootObjectDir;
  2263. if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
  2264. headerDir = cmSystemTools::CollapseFullPath(
  2265. cmStrCat(this->GetBinaryDirectory(), '/', *prop));
  2266. }
  2267. std::vector<cmSourceFile*> sources;
  2268. target->GetSourceFiles(sources, config);
  2269. // build up the list of ispc headers and extra objects that this target is
  2270. // generating
  2271. for (cmSourceFile const* sf : sources) {
  2272. // Generate this object file's rule file.
  2273. const std::string& lang = sf->GetLanguage();
  2274. if (lang == "ISPC") {
  2275. std::string const& objectName = target->GetObjectName(sf);
  2276. // Drop both ".obj" and the source file extension
  2277. std::string ispcSource =
  2278. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  2279. ispcSource =
  2280. cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  2281. auto headerPath =
  2282. cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
  2283. target->AddISPCGeneratedHeader(headerPath, config);
  2284. if (extra_objects) {
  2285. std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
  2286. objectName, rootObjectDir, ispcArchSuffixes);
  2287. target->AddISPCGeneratedObject(std::move(objs), config);
  2288. }
  2289. }
  2290. }
  2291. }
  2292. }
  2293. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2294. {
  2295. std::vector<std::string> configsList =
  2296. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2297. for (std::string const& config : configsList) {
  2298. // FIXME: Refactor collection of sources to not evaluate object
  2299. // libraries.
  2300. std::vector<cmSourceFile*> sources;
  2301. target->GetSourceFiles(sources, config);
  2302. const std::string configUpper = cmSystemTools::UpperCase(config);
  2303. static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
  2304. "OBJCXX" } };
  2305. std::set<std::string> pchLangSet;
  2306. if (this->GetGlobalGenerator()->IsXcode()) {
  2307. for (const std::string& lang : langs) {
  2308. const std::string pchHeader = target->GetPchHeader(config, lang, "");
  2309. if (!pchHeader.empty()) {
  2310. pchLangSet.emplace(lang);
  2311. }
  2312. }
  2313. }
  2314. for (const std::string& lang : langs) {
  2315. auto langSources = std::count_if(
  2316. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2317. return lang == sf->GetLanguage() &&
  2318. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2319. });
  2320. if (langSources == 0) {
  2321. continue;
  2322. }
  2323. std::vector<std::string> architectures;
  2324. if (!this->GetGlobalGenerator()->IsXcode()) {
  2325. target->GetAppleArchs(config, architectures);
  2326. }
  2327. if (architectures.empty()) {
  2328. architectures.emplace_back();
  2329. } else {
  2330. std::string useMultiArchPch;
  2331. for (const std::string& arch : architectures) {
  2332. const std::string pchHeader =
  2333. target->GetPchHeader(config, lang, arch);
  2334. if (!pchHeader.empty()) {
  2335. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2336. ";-include", pchHeader);
  2337. }
  2338. }
  2339. if (!useMultiArchPch.empty()) {
  2340. target->Target->AppendProperty(
  2341. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
  2342. cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
  2343. }
  2344. }
  2345. for (const std::string& arch : architectures) {
  2346. const std::string pchSource = target->GetPchSource(config, lang, arch);
  2347. const std::string pchHeader = target->GetPchHeader(config, lang, arch);
  2348. if (pchSource.empty() || pchHeader.empty()) {
  2349. if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
  2350. for (auto* sf : sources) {
  2351. const auto sourceLanguage = sf->GetLanguage();
  2352. if (!sourceLanguage.empty() &&
  2353. pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
  2354. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2355. }
  2356. }
  2357. }
  2358. continue;
  2359. }
  2360. cmValue pchExtension =
  2361. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  2362. if (pchExtension.IsEmpty()) {
  2363. continue;
  2364. }
  2365. cmValue ReuseFrom =
  2366. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2367. auto* pch_sf = this->Makefile->GetOrCreateSource(
  2368. pchSource, false, cmSourceFileLocationKind::Known);
  2369. if (!this->GetGlobalGenerator()->IsXcode()) {
  2370. if (!ReuseFrom) {
  2371. target->AddSource(pchSource, true);
  2372. }
  2373. const std::string pchFile = target->GetPchFile(config, lang, arch);
  2374. // Exclude the pch files from linking
  2375. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2376. if (!ReuseFrom) {
  2377. pch_sf->AppendProperty(
  2378. "OBJECT_OUTPUTS",
  2379. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
  2380. } else {
  2381. auto* reuseTarget =
  2382. this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
  2383. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2384. const std::string compilerId =
  2385. this->Makefile->GetSafeDefinition(
  2386. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2387. const std::string compilerVersion =
  2388. this->Makefile->GetSafeDefinition(
  2389. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2390. const std::string langFlags =
  2391. this->Makefile->GetSafeDefinition(
  2392. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2393. bool editAndContinueDebugInfo =
  2394. langFlags.find("/ZI") != std::string::npos ||
  2395. langFlags.find("-ZI") != std::string::npos;
  2396. bool programDatabaseDebugInfo =
  2397. langFlags.find("/Zi") != std::string::npos ||
  2398. langFlags.find("-Zi") != std::string::npos;
  2399. // MSVC 2008 is producing both .pdb and .idb files with /Zi.
  2400. bool msvc2008OrLess =
  2401. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  2402. compilerVersion, "16.0") &&
  2403. compilerId == "MSVC";
  2404. // but not when used via toolset -Tv90
  2405. if (this->Makefile->GetSafeDefinition(
  2406. "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
  2407. msvc2008OrLess = false;
  2408. }
  2409. if (editAndContinueDebugInfo || msvc2008OrLess) {
  2410. this->CopyPchCompilePdb(config, target, *ReuseFrom,
  2411. reuseTarget, { ".pdb", ".idb" });
  2412. } else if (programDatabaseDebugInfo) {
  2413. this->CopyPchCompilePdb(config, target, *ReuseFrom,
  2414. reuseTarget, { ".pdb" });
  2415. }
  2416. }
  2417. // Link to the pch object file
  2418. std::string pchSourceObj =
  2419. reuseTarget->GetPchFileObject(config, lang, arch);
  2420. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2421. std::string linkerProperty = "LINK_FLAGS_";
  2422. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2423. linkerProperty = "STATIC_LIBRARY_FLAGS_";
  2424. }
  2425. target->Target->AppendProperty(
  2426. cmStrCat(linkerProperty, configUpper),
  2427. cmStrCat(" ",
  2428. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2429. cm::nullopt, true);
  2430. } else if (reuseTarget->GetType() ==
  2431. cmStateEnums::OBJECT_LIBRARY) {
  2432. // FIXME: This can propagate more than one level, unlike
  2433. // the rest of the object files in an object library.
  2434. // Find another way to do this.
  2435. target->Target->AppendProperty(
  2436. "INTERFACE_LINK_LIBRARIES",
  2437. cmStrCat("$<$<CONFIG:", config,
  2438. ">:$<LINK_ONLY:", pchSourceObj, ">>"));
  2439. // We updated the link interface, so ensure it is recomputed.
  2440. target->ClearLinkInterfaceCache();
  2441. }
  2442. }
  2443. } else {
  2444. pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
  2445. }
  2446. // Add pchHeader to source files, which will
  2447. // be grouped as "Precompile Header File"
  2448. auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
  2449. pchHeader, false, cmSourceFileLocationKind::Known);
  2450. std::string err;
  2451. pchHeader_sf->ResolveFullPath(&err);
  2452. if (!err.empty()) {
  2453. std::ostringstream msg;
  2454. msg << "Unable to resolve full path of PCH-header '" << pchHeader
  2455. << "' assigned to target " << target->GetName()
  2456. << ", although its path is supposed to be known!";
  2457. this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
  2458. }
  2459. target->AddSource(pchHeader);
  2460. }
  2461. }
  2462. }
  2463. }
  2464. }
  2465. void cmLocalGenerator::CopyPchCompilePdb(
  2466. const std::string& config, cmGeneratorTarget* target,
  2467. const std::string& ReuseFrom, cmGeneratorTarget* reuseTarget,
  2468. const std::vector<std::string>& extensions)
  2469. {
  2470. const std::string pdb_prefix =
  2471. this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
  2472. const std::string target_compile_pdb_dir =
  2473. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2474. target->GetName(), ".dir/");
  2475. const std::string copy_script = cmStrCat(
  2476. target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
  2477. cmGeneratedFileStream file(copy_script);
  2478. file << "# CMake generated file\n";
  2479. file << "# The compiler generated pdb file needs to be written to disk\n"
  2480. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2481. << "# the pdb file is ready to be copied.\n\n";
  2482. for (auto const& extension : extensions) {
  2483. const std::string from_file =
  2484. cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2485. "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
  2486. const std::string to_dir =
  2487. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2488. target->GetName(), ".dir/${PDB_PREFIX}");
  2489. const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
  2490. std::string dest_file = to_file;
  2491. std::string const& prefix = target->GetSafeProperty("PREFIX");
  2492. if (!prefix.empty()) {
  2493. dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
  2494. }
  2495. file << "foreach(retry RANGE 1 30)\n";
  2496. file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
  2497. << dest_file << "\" OR NOT \"" << dest_file << " \" IS_NEWER_THAN \""
  2498. << from_file << "\"))\n";
  2499. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2500. file << " \"" << from_file << "\""
  2501. << " \"" << to_dir << "\" RESULT_VARIABLE result "
  2502. << " ERROR_QUIET)\n";
  2503. file << " if (NOT result EQUAL 0)\n"
  2504. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2505. << " -E sleep 1)\n"
  2506. << " else()\n";
  2507. if (!prefix.empty()) {
  2508. file << " file(REMOVE \"" << dest_file << "\")\n";
  2509. file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
  2510. }
  2511. file << " break()\n"
  2512. << " endif()\n";
  2513. file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
  2514. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2515. << " -E sleep 1)\n"
  2516. << " endif()\n";
  2517. file << "endforeach()\n";
  2518. }
  2519. auto configGenex = [&](cm::string_view expr) -> std::string {
  2520. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2521. return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
  2522. }
  2523. return std::string(expr);
  2524. };
  2525. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2526. { configGenex(cmSystemTools::GetCMakeCommand()),
  2527. configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
  2528. configGenex(copy_script) });
  2529. const char* no_message = "";
  2530. std::vector<std::string> outputs;
  2531. outputs.push_back(configGenex(
  2532. cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
  2533. auto cc = cm::make_unique<cmCustomCommand>();
  2534. cc->SetCommandLines(commandLines);
  2535. cc->SetComment(no_message);
  2536. cc->SetCMP0116Status(cmPolicies::NEW);
  2537. cc->SetStdPipesUTF8(true);
  2538. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2539. cc->SetByproducts(outputs);
  2540. this->AddCustomCommandToTarget(
  2541. target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
  2542. cmObjectLibraryCommands::Accept);
  2543. } else {
  2544. cc->SetOutputs(outputs);
  2545. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
  2546. if (copy_rule) {
  2547. target->AddSource(copy_rule->ResolveFullPath());
  2548. }
  2549. }
  2550. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2551. target_compile_pdb_dir);
  2552. }
  2553. cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
  2554. std::string const& config, cmGeneratorTarget const* target)
  2555. {
  2556. // MSVC debug information format selection is activated by the presence
  2557. // of a default whether or not it is overridden by a property.
  2558. cm::optional<std::string> msvcDebugInformationFormat;
  2559. cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
  2560. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
  2561. if (cmNonempty(msvcDebugInformationFormatDefault)) {
  2562. cmValue msvcDebugInformationFormatValue =
  2563. target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
  2564. if (!msvcDebugInformationFormatValue) {
  2565. msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
  2566. }
  2567. msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
  2568. *msvcDebugInformationFormatValue, this, config, target);
  2569. }
  2570. return msvcDebugInformationFormat;
  2571. }
  2572. namespace {
  2573. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2574. std::string const& filename)
  2575. {
  2576. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2577. sf->SetProperty("UNITY_SOURCE_FILE", filename);
  2578. }
  2579. }
  2580. cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
  2581. cmGeneratorTarget* target, std::vector<std::string> const& configs,
  2582. cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
  2583. cmValue beforeInclude, cmValue afterInclude, std::string filename) const
  2584. {
  2585. cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
  2586. cmGeneratedFileStream file(
  2587. filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
  2588. file.SetCopyIfDifferent(true);
  2589. file << "/* generated by CMake */\n\n";
  2590. bool perConfig = false;
  2591. for (UnityBatchedSource const& ubs : sources) {
  2592. cm::optional<std::string> cond;
  2593. if (ubs.Configs.size() != configs.size()) {
  2594. perConfig = true;
  2595. cond = std::string();
  2596. cm::string_view sep;
  2597. for (size_t ci : ubs.Configs) {
  2598. cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
  2599. cmSystemTools::UpperCase(configs[ci]), ")");
  2600. sep = " || "_s;
  2601. }
  2602. }
  2603. RegisterUnitySources(target, ubs.Source, filename);
  2604. WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
  2605. beforeInclude, afterInclude, uniqueIdName);
  2606. }
  2607. return UnitySource(std::move(filename), perConfig);
  2608. }
  2609. void cmLocalGenerator::WriteUnitySourceInclude(
  2610. std::ostream& unity_file, cm::optional<std::string> const& cond,
  2611. std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
  2612. cmValue uniqueIdName) const
  2613. {
  2614. if (cond) {
  2615. unity_file << "#if " << *cond << "\n";
  2616. }
  2617. if (cmNonempty(uniqueIdName)) {
  2618. std::string pathToHash;
  2619. auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
  2620. return (cmSystemTools::ComparePath(a, b) ||
  2621. cmSystemTools::IsSubDirectory(a, b));
  2622. };
  2623. const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
  2624. if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
  2625. pathToHash = "BLD_" +
  2626. cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
  2627. } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
  2628. pathToHash = "SRC_" +
  2629. cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
  2630. } else {
  2631. pathToHash = "ABS_" + sf_full_path;
  2632. }
  2633. unity_file << "/* " << pathToHash << " */\n"
  2634. << "#undef " << *uniqueIdName << "\n"
  2635. << "#define " << *uniqueIdName << " unity_"
  2636. #ifndef CMAKE_BOOTSTRAP
  2637. << cmSystemTools::ComputeStringMD5(pathToHash) << "\n"
  2638. #endif
  2639. ;
  2640. }
  2641. if (beforeInclude) {
  2642. unity_file << *beforeInclude << "\n";
  2643. }
  2644. unity_file << "#include \"" << sf_full_path << "\"\n";
  2645. if (afterInclude) {
  2646. unity_file << *afterInclude << "\n";
  2647. }
  2648. if (cond) {
  2649. unity_file << "#endif\n";
  2650. }
  2651. unity_file << "\n";
  2652. }
  2653. std::vector<cmLocalGenerator::UnitySource>
  2654. cmLocalGenerator::AddUnityFilesModeAuto(
  2655. cmGeneratorTarget* target, std::string const& lang,
  2656. std::vector<std::string> const& configs,
  2657. std::vector<UnityBatchedSource> const& filtered_sources,
  2658. cmValue beforeInclude, cmValue afterInclude,
  2659. std::string const& filename_base, size_t batchSize)
  2660. {
  2661. if (batchSize == 0) {
  2662. batchSize = filtered_sources.size();
  2663. }
  2664. std::vector<UnitySource> unity_files;
  2665. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2666. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2667. chunk = std::min(itemsLeft, batchSize);
  2668. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2669. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2670. auto const begin = filtered_sources.begin() + batch * batchSize;
  2671. auto const end = begin + chunk;
  2672. unity_files.emplace_back(this->WriteUnitySource(
  2673. target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
  2674. std::move(filename)));
  2675. }
  2676. return unity_files;
  2677. }
  2678. std::vector<cmLocalGenerator::UnitySource>
  2679. cmLocalGenerator::AddUnityFilesModeGroup(
  2680. cmGeneratorTarget* target, std::string const& lang,
  2681. std::vector<std::string> const& configs,
  2682. std::vector<UnityBatchedSource> const& filtered_sources,
  2683. cmValue beforeInclude, cmValue afterInclude,
  2684. std::string const& filename_base)
  2685. {
  2686. std::vector<UnitySource> unity_files;
  2687. // sources organized by group name. Drop any source
  2688. // without a group
  2689. std::unordered_map<std::string, std::vector<UnityBatchedSource>>
  2690. explicit_mapping;
  2691. for (UnityBatchedSource const& ubs : filtered_sources) {
  2692. if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
  2693. auto i = explicit_mapping.find(*value);
  2694. if (i == explicit_mapping.end()) {
  2695. std::vector<UnityBatchedSource> sources{ ubs };
  2696. explicit_mapping.emplace(*value, std::move(sources));
  2697. } else {
  2698. i->second.emplace_back(ubs);
  2699. }
  2700. }
  2701. }
  2702. for (auto const& item : explicit_mapping) {
  2703. auto const& name = item.first;
  2704. std::string filename = cmStrCat(filename_base, "unity_", name,
  2705. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2706. unity_files.emplace_back(this->WriteUnitySource(
  2707. target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
  2708. std::move(filename)));
  2709. }
  2710. return unity_files;
  2711. }
  2712. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2713. {
  2714. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2715. return;
  2716. }
  2717. std::vector<UnityBatchedSource> unitySources;
  2718. std::vector<std::string> configs =
  2719. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2720. std::map<cmSourceFile const*, size_t> index;
  2721. for (size_t ci = 0; ci < configs.size(); ++ci) {
  2722. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2723. std::vector<cmSourceFile*> sources;
  2724. target->GetSourceFiles(sources, configs[ci]);
  2725. for (cmSourceFile* sf : sources) {
  2726. auto mi = index.find(sf);
  2727. if (mi == index.end()) {
  2728. unitySources.emplace_back(sf);
  2729. std::map<cmSourceFile const*, size_t>::value_type entry(
  2730. sf, unitySources.size() - 1);
  2731. mi = index.insert(entry).first;
  2732. }
  2733. unitySources[mi->second].Configs.emplace_back(ci);
  2734. }
  2735. }
  2736. std::string filename_base =
  2737. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2738. target->GetName(), ".dir/Unity/");
  2739. cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2740. const size_t unityBatchSize = batchSizeString
  2741. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2742. : 0;
  2743. cmValue beforeInclude =
  2744. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2745. cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2746. cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2747. for (std::string lang : { "C", "CXX" }) {
  2748. std::vector<UnityBatchedSource> filtered_sources;
  2749. std::copy_if(unitySources.begin(), unitySources.end(),
  2750. std::back_inserter(filtered_sources),
  2751. [&](UnityBatchedSource const& ubs) -> bool {
  2752. cmSourceFile* sf = ubs.Source;
  2753. return sf->GetLanguage() == lang &&
  2754. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2755. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2756. !sf->GetProperty("COMPILE_OPTIONS") &&
  2757. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2758. !sf->GetProperty("COMPILE_FLAGS") &&
  2759. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2760. });
  2761. std::vector<UnitySource> unity_files;
  2762. if (!unityMode || *unityMode == "BATCH") {
  2763. unity_files = AddUnityFilesModeAuto(
  2764. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2765. filename_base, unityBatchSize);
  2766. } else if (unityMode && *unityMode == "GROUP") {
  2767. unity_files =
  2768. AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
  2769. beforeInclude, afterInclude, filename_base);
  2770. } else {
  2771. // unity mode is set to an unsupported value
  2772. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2773. " assigned to target " + target->GetName() +
  2774. ". Acceptable values are BATCH and GROUP.");
  2775. this->IssueMessage(MessageType::FATAL_ERROR, e);
  2776. }
  2777. for (UnitySource const& file : unity_files) {
  2778. auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
  2779. target->AddSource(file.Path, true);
  2780. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2781. unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
  2782. if (file.PerConfig) {
  2783. unity->SetProperty("COMPILE_DEFINITIONS",
  2784. "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
  2785. }
  2786. }
  2787. }
  2788. }
  2789. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2790. cmGeneratorTarget* target,
  2791. const std::string& config,
  2792. const std::string& lang)
  2793. {
  2794. if (!target->IsIPOEnabled(lang, config)) {
  2795. return;
  2796. }
  2797. switch (target->GetType()) {
  2798. case cmStateEnums::EXECUTABLE:
  2799. case cmStateEnums::SHARED_LIBRARY:
  2800. case cmStateEnums::MODULE_LIBRARY:
  2801. break;
  2802. default:
  2803. return;
  2804. }
  2805. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2806. cmValue rawFlagsList = this->Makefile->GetDefinition(name);
  2807. if (!rawFlagsList) {
  2808. return;
  2809. }
  2810. std::vector<std::string> flagsList = cmExpandedList(*rawFlagsList);
  2811. for (std::string const& o : flagsList) {
  2812. this->AppendFlagEscape(flags, o);
  2813. }
  2814. }
  2815. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2816. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2817. const std::string& lang)
  2818. {
  2819. // For now, only EXECUTABLE is concerned
  2820. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2821. return;
  2822. }
  2823. const char* PICValue = target->GetLinkPIEProperty(config);
  2824. if (PICValue == nullptr) {
  2825. // POSITION_INDEPENDENT_CODE is not set
  2826. return;
  2827. }
  2828. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2829. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2830. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2831. return;
  2832. }
  2833. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2834. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2835. if (pieFlags.empty()) {
  2836. return;
  2837. }
  2838. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2839. for (const auto& flag : flagsList) {
  2840. this->AppendFlagEscape(flags, flag);
  2841. }
  2842. }
  2843. void cmLocalGenerator::AppendModuleDefinitionFlag(
  2844. std::string& flags, cmGeneratorTarget const* target,
  2845. cmLinkLineComputer* linkLineComputer, std::string const& config)
  2846. {
  2847. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  2848. target->GetModuleDefinitionInfo(config);
  2849. if (!mdi || mdi->DefFile.empty()) {
  2850. return;
  2851. }
  2852. cmValue defFileFlag =
  2853. this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  2854. if (!defFileFlag) {
  2855. return;
  2856. }
  2857. // Append the flag and value. Use ConvertToLinkReference to help
  2858. // vs6's "cl -link" pass it to the linker.
  2859. std::string flag =
  2860. cmStrCat(*defFileFlag,
  2861. this->ConvertToOutputFormat(
  2862. linkLineComputer->ConvertToLinkReference(mdi->DefFile),
  2863. cmOutputConverter::SHELL));
  2864. this->AppendFlags(flags, flag);
  2865. }
  2866. bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
  2867. const cmGeneratorTarget* target,
  2868. const std::string& lang)
  2869. {
  2870. auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  2871. (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
  2872. target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
  2873. target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
  2874. if (useLWYU) {
  2875. const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
  2876. cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
  2877. useLWYU = !lwyuFlag.empty();
  2878. if (useLWYU) {
  2879. std::vector<BT<std::string>> lwyuOpts;
  2880. lwyuOpts.emplace_back(lwyuFlag);
  2881. this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
  2882. }
  2883. }
  2884. return useLWYU;
  2885. }
  2886. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2887. std::string const& options_list,
  2888. const char* regex) const
  2889. {
  2890. // Short-circuit if there are no options.
  2891. if (options_list.empty()) {
  2892. return;
  2893. }
  2894. // Expand the list of options.
  2895. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2896. this->AppendCompileOptions(options, options_vec, regex);
  2897. }
  2898. void cmLocalGenerator::AppendCompileOptions(
  2899. std::string& options, const std::vector<std::string>& options_vec,
  2900. const char* regex) const
  2901. {
  2902. if (regex != nullptr) {
  2903. // Filter flags upon specified reges.
  2904. cmsys::RegularExpression r(regex);
  2905. for (std::string const& opt : options_vec) {
  2906. if (r.find(opt)) {
  2907. this->AppendFlagEscape(options, opt);
  2908. }
  2909. }
  2910. } else {
  2911. for (std::string const& opt : options_vec) {
  2912. this->AppendFlagEscape(options, opt);
  2913. }
  2914. }
  2915. }
  2916. void cmLocalGenerator::AppendCompileOptions(
  2917. std::vector<BT<std::string>>& options,
  2918. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2919. {
  2920. if (regex != nullptr) {
  2921. // Filter flags upon specified regular expressions.
  2922. cmsys::RegularExpression r(regex);
  2923. for (BT<std::string> const& opt : options_vec) {
  2924. if (r.find(opt.Value)) {
  2925. std::string flag;
  2926. this->AppendFlagEscape(flag, opt.Value);
  2927. options.emplace_back(std::move(flag), opt.Backtrace);
  2928. }
  2929. }
  2930. } else {
  2931. for (BT<std::string> const& opt : options_vec) {
  2932. std::string flag;
  2933. this->AppendFlagEscape(flag, opt.Value);
  2934. options.emplace_back(std::move(flag), opt.Backtrace);
  2935. }
  2936. }
  2937. }
  2938. void cmLocalGenerator::AppendIncludeDirectories(
  2939. std::vector<std::string>& includes, const std::string& includes_list,
  2940. const cmSourceFile& sourceFile) const
  2941. {
  2942. // Short-circuit if there are no includes.
  2943. if (includes_list.empty()) {
  2944. return;
  2945. }
  2946. // Expand the list of includes.
  2947. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2948. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2949. }
  2950. void cmLocalGenerator::AppendIncludeDirectories(
  2951. std::vector<std::string>& includes,
  2952. const std::vector<std::string>& includes_vec,
  2953. const cmSourceFile& sourceFile) const
  2954. {
  2955. std::unordered_set<std::string> uniqueIncludes;
  2956. for (const std::string& include : includes_vec) {
  2957. if (!cmSystemTools::FileIsFullPath(include)) {
  2958. std::ostringstream e;
  2959. e << "Found relative path while evaluating include directories of "
  2960. "\""
  2961. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2962. << "\"\n";
  2963. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2964. return;
  2965. }
  2966. std::string inc = include;
  2967. if (!cmIsOff(inc)) {
  2968. cmSystemTools::ConvertToUnixSlashes(inc);
  2969. }
  2970. if (uniqueIncludes.insert(inc).second) {
  2971. includes.push_back(std::move(inc));
  2972. }
  2973. }
  2974. }
  2975. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2976. std::string const& defines_list) const
  2977. {
  2978. std::set<BT<std::string>> tmp;
  2979. this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
  2980. for (BT<std::string> const& i : tmp) {
  2981. defines.emplace(i.Value);
  2982. }
  2983. }
  2984. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2985. std::string const& defines_list) const
  2986. {
  2987. // Short-circuit if there are no definitions.
  2988. if (defines_list.empty()) {
  2989. return;
  2990. }
  2991. // Expand the list of definitions.
  2992. this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
  2993. }
  2994. void cmLocalGenerator::AppendDefines(
  2995. std::set<BT<std::string>>& defines,
  2996. const std::vector<BT<std::string>>& defines_vec) const
  2997. {
  2998. for (BT<std::string> const& d : defines_vec) {
  2999. // Skip unsupported definitions.
  3000. if (!this->CheckDefinition(d.Value)) {
  3001. continue;
  3002. }
  3003. defines.insert(d);
  3004. }
  3005. }
  3006. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  3007. std::string& definesString,
  3008. const std::string& lang)
  3009. {
  3010. // Lookup the define flag for the current language.
  3011. std::string dflag = "-D";
  3012. if (!lang.empty()) {
  3013. cmValue df =
  3014. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  3015. if (cmNonempty(df)) {
  3016. dflag = *df;
  3017. }
  3018. }
  3019. const char* itemSeparator = definesString.empty() ? "" : " ";
  3020. for (std::string const& define : defines) {
  3021. // Append the definition with proper escaping.
  3022. std::string def = dflag;
  3023. if (this->GetState()->UseWatcomWMake()) {
  3024. // The Watcom compiler does its own command line parsing instead
  3025. // of using the windows shell rules. Definitions are one of
  3026. // -DNAME
  3027. // -DNAME=<cpp-token>
  3028. // -DNAME="c-string with spaces and other characters(?@#$)"
  3029. //
  3030. // Watcom will properly parse each of these cases from the
  3031. // command line without any escapes. However we still have to
  3032. // get the '$' and '#' characters through WMake as '$$' and
  3033. // '$#'.
  3034. for (char c : define) {
  3035. if (c == '$' || c == '#') {
  3036. def += '$';
  3037. }
  3038. def += c;
  3039. }
  3040. } else {
  3041. // Make the definition appear properly on the command line. Use
  3042. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  3043. std::string::size_type eq = define.find('=');
  3044. def += define.substr(0, eq);
  3045. if (eq != std::string::npos) {
  3046. def += "=";
  3047. def += this->EscapeForShell(define.substr(eq + 1), true);
  3048. }
  3049. }
  3050. definesString += itemSeparator;
  3051. itemSeparator = " ";
  3052. definesString += def;
  3053. }
  3054. }
  3055. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  3056. const std::string& lang,
  3057. const char* feature)
  3058. {
  3059. cmValue optionList = this->Makefile->GetDefinition(
  3060. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  3061. if (optionList) {
  3062. std::vector<std::string> options = cmExpandedList(*optionList);
  3063. for (std::string const& o : options) {
  3064. this->AppendFlagEscape(flags, o);
  3065. }
  3066. }
  3067. }
  3068. cmValue cmLocalGenerator::GetFeature(const std::string& feature,
  3069. const std::string& config)
  3070. {
  3071. std::string featureName = feature;
  3072. // TODO: Define accumulation policy for features (prepend, append,
  3073. // replace). Currently we always replace.
  3074. if (!config.empty()) {
  3075. featureName += "_";
  3076. featureName += cmSystemTools::UpperCase(config);
  3077. }
  3078. cmStateSnapshot snp = this->StateSnapshot;
  3079. while (snp.IsValid()) {
  3080. if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
  3081. return value;
  3082. }
  3083. snp = snp.GetBuildsystemDirectoryParent();
  3084. }
  3085. return nullptr;
  3086. }
  3087. std::string cmLocalGenerator::GetProjectName() const
  3088. {
  3089. return this->StateSnapshot.GetProjectName();
  3090. }
  3091. std::string cmLocalGenerator::ConstructComment(
  3092. cmCustomCommandGenerator const& ccg, const char* default_comment) const
  3093. {
  3094. // Check for a comment provided with the command.
  3095. if (ccg.GetComment()) {
  3096. return ccg.GetComment();
  3097. }
  3098. // Construct a reasonable default comment if possible.
  3099. if (!ccg.GetOutputs().empty()) {
  3100. std::string comment;
  3101. comment = "Generating ";
  3102. const char* sep = "";
  3103. for (std::string const& o : ccg.GetOutputs()) {
  3104. comment += sep;
  3105. comment += this->MaybeRelativeToCurBinDir(o);
  3106. sep = ", ";
  3107. }
  3108. return comment;
  3109. }
  3110. // Otherwise use the provided default.
  3111. return default_comment;
  3112. }
  3113. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  3114. {
  3115. public:
  3116. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  3117. std::string const& dest, bool implib)
  3118. : cmInstallTargetGenerator(
  3119. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  3120. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  3121. false)
  3122. {
  3123. this->Compute(lg);
  3124. }
  3125. };
  3126. void cmLocalGenerator::GenerateTargetInstallRules(
  3127. std::ostream& os, const std::string& config,
  3128. std::vector<std::string> const& configurationTypes)
  3129. {
  3130. // Convert the old-style install specification from each target to
  3131. // an install generator and run it.
  3132. const auto& tgts = this->GetGeneratorTargets();
  3133. for (const auto& l : tgts) {
  3134. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3135. continue;
  3136. }
  3137. // Include the user-specified pre-install script for this target.
  3138. if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3139. cmInstallScriptGenerator g(*preinstall, false, "", false, false);
  3140. g.Generate(os, config, configurationTypes);
  3141. }
  3142. // Install this target if a destination is given.
  3143. if (!l->Target->GetInstallPath().empty()) {
  3144. // Compute the full install destination. Note that converting
  3145. // to unix slashes also removes any trailing slash.
  3146. // We also skip over the leading slash given by the user.
  3147. std::string destination = l->Target->GetInstallPath().substr(1);
  3148. cmSystemTools::ConvertToUnixSlashes(destination);
  3149. if (destination.empty()) {
  3150. destination = ".";
  3151. }
  3152. // Generate the proper install generator for this target type.
  3153. switch (l->GetType()) {
  3154. case cmStateEnums::EXECUTABLE:
  3155. case cmStateEnums::STATIC_LIBRARY:
  3156. case cmStateEnums::MODULE_LIBRARY: {
  3157. // Use a target install generator.
  3158. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3159. false);
  3160. g.Generate(os, config, configurationTypes);
  3161. } break;
  3162. case cmStateEnums::SHARED_LIBRARY: {
  3163. #if defined(_WIN32) || defined(__CYGWIN__)
  3164. // Special code to handle DLL. Install the import library
  3165. // to the normal destination and the DLL to the runtime
  3166. // destination.
  3167. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3168. true);
  3169. g1.Generate(os, config, configurationTypes);
  3170. // We also skip over the leading slash given by the user.
  3171. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3172. cmSystemTools::ConvertToUnixSlashes(destination);
  3173. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3174. false);
  3175. g2.Generate(os, config, configurationTypes);
  3176. #else
  3177. // Use a target install generator.
  3178. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3179. false);
  3180. g.Generate(os, config, configurationTypes);
  3181. #endif
  3182. } break;
  3183. default:
  3184. break;
  3185. }
  3186. }
  3187. // Include the user-specified post-install script for this target.
  3188. if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3189. cmInstallScriptGenerator g(*postinstall, false, "", false, false);
  3190. g.Generate(os, config, configurationTypes);
  3191. }
  3192. }
  3193. }
  3194. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  3195. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3196. std::string::size_type max_len)
  3197. {
  3198. // Check if the path can be shortened using an md5 sum replacement for
  3199. // a portion of the path.
  3200. std::string::size_type md5Len = 32;
  3201. std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
  3202. std::string::size_type pos = objName.find('/', numExtraChars);
  3203. if (pos == std::string::npos) {
  3204. pos = objName.rfind('/', numExtraChars);
  3205. if (pos == std::string::npos || pos <= md5Len) {
  3206. return false;
  3207. }
  3208. }
  3209. // Replace the beginning of the path portion of the object name with
  3210. // its own md5 sum.
  3211. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3212. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3213. cm::string_view(objName).substr(pos));
  3214. objName = md5name;
  3215. // The object name is now shorter, check if it is short enough.
  3216. return pos >= numExtraChars;
  3217. }
  3218. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3219. std::string::size_type dir_len,
  3220. std::string::size_type max_total_len)
  3221. {
  3222. // Enforce the maximum file name length if possible.
  3223. std::string::size_type max_obj_len = max_total_len;
  3224. if (dir_len < max_total_len) {
  3225. max_obj_len = max_total_len - dir_len;
  3226. if (objName.size() > max_obj_len) {
  3227. // The current object file name is too long. Try to shorten it.
  3228. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3229. }
  3230. // The object file name is short enough.
  3231. return true;
  3232. }
  3233. // The build directory in which the object will be stored is
  3234. // already too deep.
  3235. return false;
  3236. }
  3237. #endif
  3238. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3239. const std::string& sin, std::string const& dir_max)
  3240. {
  3241. // Look for an existing mapped name for this object file.
  3242. auto it = this->UniqueObjectNamesMap.find(sin);
  3243. // If no entry exists create one.
  3244. if (it == this->UniqueObjectNamesMap.end()) {
  3245. // Start with the original name.
  3246. std::string ssin = sin;
  3247. // Avoid full paths by removing leading slashes.
  3248. ssin.erase(0, ssin.find_first_not_of('/'));
  3249. // Avoid full paths by removing colons.
  3250. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3251. // Avoid relative paths that go up the tree.
  3252. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3253. // Avoid spaces.
  3254. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3255. // Mangle the name if necessary.
  3256. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3257. bool done;
  3258. int cc = 0;
  3259. char rpstr[100];
  3260. snprintf(rpstr, sizeof(rpstr), "_p_");
  3261. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3262. std::string sssin = sin;
  3263. do {
  3264. done = true;
  3265. for (it = this->UniqueObjectNamesMap.begin();
  3266. it != this->UniqueObjectNamesMap.end(); ++it) {
  3267. if (it->second == ssin) {
  3268. done = false;
  3269. }
  3270. }
  3271. if (done) {
  3272. break;
  3273. }
  3274. sssin = ssin;
  3275. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3276. snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
  3277. } while (!done);
  3278. }
  3279. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  3280. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3281. this->ObjectPathMax)) {
  3282. // Warn if this is the first time the path has been seen.
  3283. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3284. std::ostringstream m;
  3285. /* clang-format off */
  3286. m << "The object file directory\n"
  3287. << " " << dir_max << "\n"
  3288. << "has " << dir_max.size() << " characters. "
  3289. << "The maximum full path to an object file is "
  3290. << this->ObjectPathMax << " characters "
  3291. << "(see CMAKE_OBJECT_PATH_MAX). "
  3292. << "Object file\n"
  3293. << " " << ssin << "\n"
  3294. << "cannot be safely placed under this directory. "
  3295. << "The build may not work correctly.";
  3296. /* clang-format on */
  3297. this->IssueMessage(MessageType::WARNING, m.str());
  3298. }
  3299. }
  3300. #else
  3301. (void)dir_max;
  3302. #endif
  3303. // Insert the newly mapped object file name.
  3304. std::map<std::string, std::string>::value_type e(sin, ssin);
  3305. it = this->UniqueObjectNamesMap.insert(e).first;
  3306. }
  3307. // Return the map entry.
  3308. return it->second;
  3309. }
  3310. void cmLocalGenerator::ComputeObjectFilenames(
  3311. std::map<cmSourceFile const*, std::string>& /*unused*/,
  3312. cmGeneratorTarget const* /*unused*/)
  3313. {
  3314. }
  3315. bool cmLocalGenerator::IsWindowsShell() const
  3316. {
  3317. return this->GetState()->UseWindowsShell();
  3318. }
  3319. bool cmLocalGenerator::IsWatcomWMake() const
  3320. {
  3321. return this->GetState()->UseWatcomWMake();
  3322. }
  3323. bool cmLocalGenerator::IsMinGWMake() const
  3324. {
  3325. return this->GetState()->UseMinGWMake();
  3326. }
  3327. bool cmLocalGenerator::IsNMake() const
  3328. {
  3329. return this->GetState()->UseNMake();
  3330. }
  3331. bool cmLocalGenerator::IsNinjaMulti() const
  3332. {
  3333. return this->GetState()->UseNinjaMulti();
  3334. }
  3335. namespace {
  3336. std::string relativeIfUnder(std::string const& top, std::string const& cur,
  3337. std::string const& path)
  3338. {
  3339. // Use a path relative to 'cur' if it can be expressed without
  3340. // a `../` sequence that leaves 'top'.
  3341. if (cmSystemTools::IsSubDirectory(path, cur) ||
  3342. (cmSystemTools::IsSubDirectory(cur, top) &&
  3343. cmSystemTools::IsSubDirectory(path, top))) {
  3344. return cmSystemTools::ForceToRelativePath(cur, path);
  3345. }
  3346. return path;
  3347. }
  3348. }
  3349. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3350. const cmSourceFile& source, std::string const& dir_max,
  3351. bool* hasSourceExtension, char const* customOutputExtension)
  3352. {
  3353. // Construct the object file name using the full path to the source
  3354. // file which is its only unique identification.
  3355. std::string const& fullPath = source.GetFullPath();
  3356. // Try referencing the source relative to the source tree.
  3357. std::string relFromSource = relativeIfUnder(
  3358. this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
  3359. assert(!relFromSource.empty());
  3360. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3361. bool subSource = relSource && relFromSource[0] != '.';
  3362. // Try referencing the source relative to the binary tree.
  3363. std::string relFromBinary = relativeIfUnder(
  3364. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
  3365. assert(!relFromBinary.empty());
  3366. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3367. bool subBinary = relBinary && relFromBinary[0] != '.';
  3368. // Select a nice-looking reference to the source file to construct
  3369. // the object file name.
  3370. std::string objectName;
  3371. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3372. // NOLINTNEXTLINE(bugprone-branch-clone)
  3373. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3374. objectName = relFromSource;
  3375. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3376. relFromBinary.length() < relFromSource.length()) {
  3377. objectName = relFromBinary;
  3378. } else {
  3379. objectName = relFromSource;
  3380. }
  3381. // if it is still a full path check for the try compile case
  3382. // try compile never have in source sources, and should not
  3383. // have conflicting source file names in the same target
  3384. if (cmSystemTools::FileIsFullPath(objectName)) {
  3385. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  3386. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  3387. }
  3388. }
  3389. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  3390. // we don't end up having:
  3391. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  3392. cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  3393. cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
  3394. const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
  3395. if (unitySourceFile || pchExtension || isPchObject) {
  3396. if (pchExtension) {
  3397. customOutputExtension = pchExtension->c_str();
  3398. }
  3399. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  3400. if (var.find(objectName)) {
  3401. objectName.erase(var.start(), var.end() - var.start());
  3402. }
  3403. }
  3404. // Replace the original source file extension with the object file
  3405. // extension.
  3406. bool keptSourceExtension = true;
  3407. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  3408. // Decide whether this language wants to replace the source
  3409. // extension with the object extension. For CMake 2.4
  3410. // compatibility do this by default.
  3411. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  3412. if (!replaceExt) {
  3413. std::string lang = source.GetLanguage();
  3414. if (!lang.empty()) {
  3415. replaceExt = this->Makefile->IsOn(
  3416. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  3417. }
  3418. }
  3419. // Remove the source extension if it is to be replaced.
  3420. if (replaceExt || customOutputExtension) {
  3421. keptSourceExtension = false;
  3422. std::string::size_type dot_pos = objectName.rfind('.');
  3423. if (dot_pos != std::string::npos) {
  3424. objectName = objectName.substr(0, dot_pos);
  3425. }
  3426. }
  3427. // Store the new extension.
  3428. if (customOutputExtension) {
  3429. objectName += customOutputExtension;
  3430. } else {
  3431. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  3432. }
  3433. }
  3434. if (hasSourceExtension) {
  3435. *hasSourceExtension = keptSourceExtension;
  3436. }
  3437. // Convert to a safe name.
  3438. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  3439. }
  3440. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  3441. {
  3442. return source.GetLanguage();
  3443. }
  3444. cmake* cmLocalGenerator::GetCMakeInstance() const
  3445. {
  3446. return this->GlobalGenerator->GetCMakeInstance();
  3447. }
  3448. std::string const& cmLocalGenerator::GetSourceDirectory() const
  3449. {
  3450. return this->GetCMakeInstance()->GetHomeDirectory();
  3451. }
  3452. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  3453. {
  3454. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3455. }
  3456. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  3457. {
  3458. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  3459. }
  3460. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  3461. {
  3462. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  3463. }
  3464. std::string cmLocalGenerator::GetTargetDirectory(
  3465. const cmGeneratorTarget* /*unused*/) const
  3466. {
  3467. cmSystemTools::Error("GetTargetDirectory"
  3468. " called on cmLocalGenerator");
  3469. return "";
  3470. }
  3471. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3472. {
  3473. // The computed version may change until the project is fully
  3474. // configured.
  3475. if (!this->BackwardsCompatibilityFinal) {
  3476. unsigned int major = 0;
  3477. unsigned int minor = 0;
  3478. unsigned int patch = 0;
  3479. if (cmValue value =
  3480. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3481. switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
  3482. case 2:
  3483. patch = 0;
  3484. break;
  3485. case 1:
  3486. minor = 0;
  3487. patch = 0;
  3488. break;
  3489. default:
  3490. break;
  3491. }
  3492. }
  3493. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3494. this->BackwardsCompatibilityFinal = true;
  3495. }
  3496. return this->BackwardsCompatibility;
  3497. }
  3498. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3499. {
  3500. // Check the policy to decide whether to pay attention to this
  3501. // variable.
  3502. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3503. case cmPolicies::WARN:
  3504. // WARN is just OLD without warning because user code does not
  3505. // always affect whether this check is done.
  3506. CM_FALLTHROUGH;
  3507. case cmPolicies::OLD:
  3508. // Old behavior is to check the variable.
  3509. break;
  3510. case cmPolicies::NEW:
  3511. // New behavior is to ignore the variable.
  3512. case cmPolicies::REQUIRED_IF_USED:
  3513. case cmPolicies::REQUIRED_ALWAYS:
  3514. // This will never be the case because the only way to require
  3515. // the setting is to require the user to specify version policy
  3516. // 2.6 or higher. Once we add that requirement then this whole
  3517. // method can be removed anyway.
  3518. return false;
  3519. }
  3520. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3521. // equal to or lower than the given version.
  3522. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3523. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3524. }
  3525. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3526. cmPolicies::PolicyID id) const
  3527. {
  3528. return this->Makefile->GetPolicyStatus(id);
  3529. }
  3530. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3531. {
  3532. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3533. std::string::size_type pos = define.find_first_of("(=");
  3534. if (pos != std::string::npos) {
  3535. if (define[pos] == '(') {
  3536. std::ostringstream e;
  3537. /* clang-format off */
  3538. e << "WARNING: Function-style preprocessor definitions may not be "
  3539. << "passed on the compiler command line because many compilers "
  3540. << "do not support it.\n"
  3541. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3542. << "Consider defining the macro in a (configured) header file.\n";
  3543. /* clang-format on */
  3544. cmSystemTools::Message(e.str());
  3545. return false;
  3546. }
  3547. }
  3548. // Many compilers do not support # in the value so we disable it.
  3549. if (define.find_first_of('#') != std::string::npos) {
  3550. std::ostringstream e;
  3551. /* clang-format off */
  3552. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3553. << "passed on the compiler command line because many compilers "
  3554. << "do not support it.\n"
  3555. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3556. << "Consider defining the macro in a (configured) header file.\n";
  3557. /* clang-format on */
  3558. cmSystemTools::Message(e.str());
  3559. return false;
  3560. }
  3561. // Assume it is supported.
  3562. return true;
  3563. }
  3564. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3565. const std::string& prop)
  3566. {
  3567. if (cmValue val = target->GetProperty(prop)) {
  3568. mf->AddDefinition(prop, *val);
  3569. }
  3570. }
  3571. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3572. const std::string& targetName,
  3573. const std::string& fname)
  3574. {
  3575. // Find the Info.plist template.
  3576. cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3577. std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
  3578. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3579. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3580. if (!inMod.empty()) {
  3581. inFile = inMod;
  3582. }
  3583. }
  3584. if (!cmSystemTools::FileExists(inFile, true)) {
  3585. std::ostringstream e;
  3586. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3587. << "\" could not be found.";
  3588. cmSystemTools::Error(e.str());
  3589. return;
  3590. }
  3591. // Convert target properties to variables in an isolated makefile
  3592. // scope to configure the file. If properties are set they will
  3593. // override user make variables. If not the configuration will fall
  3594. // back to the directory-level values set by the user.
  3595. cmMakefile* mf = this->Makefile;
  3596. cmMakefile::ScopePushPop varScope(mf);
  3597. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3598. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3599. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3600. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3601. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3602. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3603. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3604. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3605. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3606. mf->ConfigureFile(inFile, fname, false, false, false);
  3607. }
  3608. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3609. cmGeneratorTarget* target, const std::string& targetName,
  3610. const std::string& fname)
  3611. {
  3612. // Find the Info.plist template.
  3613. cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3614. std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
  3615. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3616. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3617. if (!inMod.empty()) {
  3618. inFile = inMod;
  3619. }
  3620. }
  3621. if (!cmSystemTools::FileExists(inFile, true)) {
  3622. std::ostringstream e;
  3623. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3624. << "\" could not be found.";
  3625. cmSystemTools::Error(e.str());
  3626. return;
  3627. }
  3628. // Convert target properties to variables in an isolated makefile
  3629. // scope to configure the file. If properties are set they will
  3630. // override user make variables. If not the configuration will fall
  3631. // back to the directory-level values set by the user.
  3632. cmMakefile* mf = this->Makefile;
  3633. cmMakefile::ScopePushPop varScope(mf);
  3634. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3635. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3636. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3637. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3638. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3639. mf->ConfigureFile(inFile, fname, false, false, false);
  3640. }
  3641. namespace {
  3642. cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
  3643. {
  3644. return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
  3645. : "BYPRODUCTS"_s);
  3646. }
  3647. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3648. cmLocalGenerator::OutputRole role,
  3649. cmCommandOrigin origin,
  3650. const cmListFileBacktrace& lfbt)
  3651. {
  3652. if (cmGeneratorExpression::Find(output) != std::string::npos) {
  3653. lg.GetCMakeInstance()->IssueMessage(
  3654. MessageType::FATAL_ERROR,
  3655. "Generator expressions in custom command outputs are not implemented!",
  3656. lfbt);
  3657. return;
  3658. }
  3659. // Make sure the file will not be generated into the source
  3660. // directory during an out of source build.
  3661. if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
  3662. lg.GetCMakeInstance()->IssueMessage(
  3663. MessageType::FATAL_ERROR,
  3664. cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
  3665. "\nin a source directory as an output of custom command."),
  3666. lfbt);
  3667. return;
  3668. }
  3669. // Make sure the output file name has no invalid characters.
  3670. std::string::size_type pos = output.find_first_of("#<>");
  3671. if (pos != std::string::npos) {
  3672. lg.GetCMakeInstance()->IssueMessage(
  3673. MessageType::FATAL_ERROR,
  3674. cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
  3675. "\" is not allowed."),
  3676. lfbt);
  3677. return;
  3678. }
  3679. // Outputs without generator expressions from the project are already
  3680. // created and marked as generated. Do not mark them again, because
  3681. // other commands might have overwritten the property.
  3682. if (origin == cmCommandOrigin::Generator) {
  3683. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3684. }
  3685. }
  3686. std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
  3687. cmListFileBacktrace const& bt,
  3688. std::string const& output)
  3689. {
  3690. // If the output path has no generator expressions, use it directly.
  3691. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3692. return output;
  3693. }
  3694. // The output path contains a generator expression, but we must choose
  3695. // a single source file path to which to attach the custom command.
  3696. // Use some heuristics to provide a nice-looking name when possible.
  3697. // If the only genex is $<CONFIG>, replace that gracefully.
  3698. {
  3699. std::string simple = output;
  3700. cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
  3701. if (cmGeneratorExpression::Find(simple) == std::string::npos) {
  3702. return simple;
  3703. }
  3704. }
  3705. // If the genex evaluates to the same value in all configurations, use that.
  3706. {
  3707. std::vector<std::string> allConfigOutputs =
  3708. lg.ExpandCustomCommandOutputGenex(output, bt);
  3709. if (allConfigOutputs.size() == 1) {
  3710. return allConfigOutputs.front();
  3711. }
  3712. }
  3713. // Fall back to a deterministic unique name.
  3714. cmCryptoHash h(cmCryptoHash::AlgoSHA256);
  3715. return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
  3716. h.HashString(output).substr(0, 16));
  3717. }
  3718. cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3719. std::unique_ptr<cmCustomCommand> cc,
  3720. bool replace)
  3721. {
  3722. cmMakefile* mf = lg.GetMakefile();
  3723. const auto& lfbt = cc->GetBacktrace();
  3724. const auto& outputs = cc->GetOutputs();
  3725. const auto& byproducts = cc->GetByproducts();
  3726. const auto& commandLines = cc->GetCommandLines();
  3727. // Choose a source file on which to store the custom command.
  3728. cmSourceFile* file = nullptr;
  3729. if (!commandLines.empty() && cc->HasMainDependency()) {
  3730. const auto& main_dependency = cc->GetMainDependency();
  3731. // The main dependency was specified. Use it unless a different
  3732. // custom command already used it.
  3733. file = mf->GetSource(main_dependency);
  3734. if (file && file->GetCustomCommand() && !replace) {
  3735. // The main dependency already has a custom command.
  3736. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  3737. // The existing custom command is identical. Silently ignore
  3738. // the duplicate.
  3739. return file;
  3740. }
  3741. // The existing custom command is different. We need to
  3742. // generate a rule file for this new command.
  3743. file = nullptr;
  3744. } else if (!file) {
  3745. file = mf->CreateSource(main_dependency);
  3746. }
  3747. }
  3748. // Generate a rule file if the main dependency is not available.
  3749. if (!file) {
  3750. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  3751. // Construct a rule file associated with the first output produced.
  3752. std::string outName = gg->GenerateRuleFile(
  3753. ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
  3754. // Check if the rule file already exists.
  3755. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  3756. if (file && file->GetCustomCommand() && !replace) {
  3757. // The rule file already exists.
  3758. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  3759. lg.GetCMakeInstance()->IssueMessage(
  3760. MessageType::FATAL_ERROR,
  3761. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  3762. "\nwhich already has a custom rule."),
  3763. lfbt);
  3764. }
  3765. return file;
  3766. }
  3767. // Create a cmSourceFile for the rule file.
  3768. if (!file) {
  3769. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  3770. }
  3771. file->SetProperty("__CMAKE_RULE", "1");
  3772. }
  3773. // Attach the custom command to the file.
  3774. if (file) {
  3775. cc->SetEscapeAllowMakeVars(true);
  3776. lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
  3777. lfbt, origin);
  3778. lg.AddSourceOutputs(file, byproducts,
  3779. cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
  3780. file->SetCustomCommand(std::move(cc));
  3781. }
  3782. return file;
  3783. }
  3784. bool AnyOutputMatches(const std::string& name,
  3785. const std::vector<std::string>& outputs)
  3786. {
  3787. return std::any_of(outputs.begin(), outputs.end(),
  3788. [&name](std::string const& output) -> bool {
  3789. std::string::size_type pos = output.rfind(name);
  3790. // If the output matches exactly
  3791. return (pos != std::string::npos &&
  3792. pos == output.size() - name.size() &&
  3793. (pos == 0 || output[pos - 1] == '/'));
  3794. });
  3795. }
  3796. bool AnyTargetCommandOutputMatches(
  3797. const std::string& name, const std::vector<cmCustomCommand>& commands)
  3798. {
  3799. return std::any_of(commands.begin(), commands.end(),
  3800. [&name](cmCustomCommand const& command) -> bool {
  3801. return AnyOutputMatches(name, command.GetByproducts());
  3802. });
  3803. }
  3804. }
  3805. namespace detail {
  3806. void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
  3807. cmTarget* target, cmCustomCommandType type,
  3808. std::unique_ptr<cmCustomCommand> cc)
  3809. {
  3810. // Add the command to the appropriate build step for the target.
  3811. cc->SetEscapeAllowMakeVars(true);
  3812. cc->SetTarget(target->GetName());
  3813. lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
  3814. origin);
  3815. switch (type) {
  3816. case cmCustomCommandType::PRE_BUILD:
  3817. target->AddPreBuildCommand(std::move(*cc));
  3818. break;
  3819. case cmCustomCommandType::PRE_LINK:
  3820. target->AddPreLinkCommand(std::move(*cc));
  3821. break;
  3822. case cmCustomCommandType::POST_BUILD:
  3823. target->AddPostBuildCommand(std::move(*cc));
  3824. break;
  3825. }
  3826. cc.reset();
  3827. }
  3828. cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
  3829. cmCommandOrigin origin,
  3830. std::unique_ptr<cmCustomCommand> cc,
  3831. bool replace)
  3832. {
  3833. return AddCustomCommand(lg, origin, std::move(cc), replace);
  3834. }
  3835. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  3836. const cmListFileBacktrace& lfbt,
  3837. const std::string& output,
  3838. const std::vector<std::string>& depends,
  3839. const cmImplicitDependsList& implicit_depends,
  3840. const cmCustomCommandLines& commandLines)
  3841. {
  3842. // Lookup an existing command.
  3843. cmSourceFile* sf = nullptr;
  3844. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3845. sf = lg.GetSourceFileWithOutput(output);
  3846. } else {
  3847. // This output path has a generator expression. Evaluate it to
  3848. // find the output for any configurations.
  3849. for (std::string const& out :
  3850. lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
  3851. sf = lg.GetSourceFileWithOutput(out);
  3852. if (sf) {
  3853. break;
  3854. }
  3855. }
  3856. }
  3857. if (sf) {
  3858. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  3859. cc->AppendCommands(commandLines);
  3860. cc->AppendDepends(depends);
  3861. cc->AppendImplicitDepends(implicit_depends);
  3862. return;
  3863. }
  3864. }
  3865. // No existing command found.
  3866. lg.GetCMakeInstance()->IssueMessage(
  3867. MessageType::FATAL_ERROR,
  3868. cmStrCat("Attempt to APPEND to custom command with output\n ", output,
  3869. "\nwhich is not already a custom command output."),
  3870. lfbt);
  3871. }
  3872. void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3873. cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
  3874. {
  3875. // They might be moved away
  3876. auto byproducts = cc->GetByproducts();
  3877. auto lfbt = cc->GetBacktrace();
  3878. // Use an empty comment to avoid generation of default comment.
  3879. if (!cc->GetComment()) {
  3880. cc->SetComment("");
  3881. }
  3882. // Create the generated symbolic output name of the utility target.
  3883. std::string output =
  3884. lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
  3885. cc->SetOutputs(output);
  3886. cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
  3887. /*replace=*/false);
  3888. if (rule) {
  3889. lg.AddTargetByproducts(target, byproducts, lfbt, origin);
  3890. }
  3891. target->AddSource(output);
  3892. }
  3893. std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
  3894. {
  3895. const std::string& targetProperty =
  3896. target->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  3897. std::vector<std::string> ispcTargets;
  3898. if (!cmIsOff(targetProperty)) {
  3899. cmExpandList(targetProperty, ispcTargets);
  3900. for (auto& ispcTarget : ispcTargets) {
  3901. // transform targets into the suffixes
  3902. auto pos = ispcTarget.find('-');
  3903. auto target_suffix = ispcTarget.substr(0, pos);
  3904. if (target_suffix ==
  3905. "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
  3906. target_suffix = "avx";
  3907. }
  3908. ispcTarget = target_suffix;
  3909. }
  3910. }
  3911. return ispcTargets;
  3912. }
  3913. std::vector<std::string> ComputeISPCExtraObjects(
  3914. std::string const& objectName, std::string const& buildDirectory,
  3915. std::vector<std::string> const& ispcSuffixes)
  3916. {
  3917. auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
  3918. std::vector<std::string> computedObjects;
  3919. computedObjects.reserve(ispcSuffixes.size());
  3920. auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
  3921. // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
  3922. // drops any directories in objectName
  3923. auto objNameNoExt = objectName;
  3924. std::string::size_type dot_pos = objectName.rfind('.');
  3925. if (dot_pos != std::string::npos) {
  3926. objNameNoExt.resize(dot_pos);
  3927. }
  3928. for (const auto& ispcTarget : ispcSuffixes) {
  3929. computedObjects.emplace_back(
  3930. cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
  3931. }
  3932. return computedObjects;
  3933. }
  3934. }
  3935. cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
  3936. const std::string& name) const
  3937. {
  3938. // Linear search? Also see GetSourceFileWithOutput for detail.
  3939. if (!cmSystemTools::FileIsFullPath(name)) {
  3940. cmSourcesWithOutput sources;
  3941. sources.Target = this->LinearGetTargetWithOutput(name);
  3942. sources.Source = this->LinearGetSourceFileWithOutput(
  3943. name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
  3944. return sources;
  3945. }
  3946. // Otherwise we use an efficient lookup map.
  3947. auto o = this->OutputToSource.find(name);
  3948. if (o != this->OutputToSource.end()) {
  3949. return o->second.Sources;
  3950. }
  3951. return {};
  3952. }
  3953. cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
  3954. const std::string& name, cmSourceOutputKind kind) const
  3955. {
  3956. // If the queried path is not absolute we use the backward compatible
  3957. // linear-time search for an output with a matching suffix.
  3958. if (!cmSystemTools::FileIsFullPath(name)) {
  3959. bool byproduct = false;
  3960. return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
  3961. }
  3962. // Otherwise we use an efficient lookup map.
  3963. auto o = this->OutputToSource.find(name);
  3964. if (o != this->OutputToSource.end() &&
  3965. (!o->second.Sources.SourceIsByproduct ||
  3966. kind == cmSourceOutputKind::OutputOrByproduct)) {
  3967. // Source file could also be null pointer for example if we found the
  3968. // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
  3969. // command of a target, or a not yet created custom command.
  3970. return o->second.Sources.Source;
  3971. }
  3972. return nullptr;
  3973. }
  3974. std::string cmLocalGenerator::CreateUtilityOutput(
  3975. std::string const& targetName, std::vector<std::string> const&,
  3976. cmListFileBacktrace const&)
  3977. {
  3978. std::string force =
  3979. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
  3980. // The output is not actually created so mark it symbolic.
  3981. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  3982. sf->SetProperty("SYMBOLIC", "1");
  3983. } else {
  3984. cmSystemTools::Error("Could not get source file entry for " + force);
  3985. }
  3986. return force;
  3987. }
  3988. std::vector<cmCustomCommandGenerator>
  3989. cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
  3990. std::string const& config)
  3991. {
  3992. std::vector<cmCustomCommandGenerator> ccgs;
  3993. ccgs.emplace_back(cc, config, this);
  3994. return ccgs;
  3995. }
  3996. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
  3997. cmCompiledGeneratorExpression const& cge, std::string const& config)
  3998. {
  3999. std::vector<std::string> paths = cmExpandedList(cge.Evaluate(this, config));
  4000. for (std::string& p : paths) {
  4001. p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
  4002. }
  4003. return paths;
  4004. }
  4005. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
  4006. std::string const& o, cmListFileBacktrace const& bt)
  4007. {
  4008. std::vector<std::string> allConfigOutputs;
  4009. cmGeneratorExpression ge(bt);
  4010. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
  4011. std::vector<std::string> configs =
  4012. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4013. for (std::string const& config : configs) {
  4014. std::vector<std::string> configOutputs =
  4015. this->ExpandCustomCommandOutputPaths(*cge, config);
  4016. allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
  4017. std::move(configOutputs.begin(), configOutputs.end(),
  4018. std::back_inserter(allConfigOutputs));
  4019. }
  4020. auto endUnique =
  4021. cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
  4022. allConfigOutputs.erase(endUnique, allConfigOutputs.end());
  4023. return allConfigOutputs;
  4024. }
  4025. void cmLocalGenerator::AddTargetByproducts(
  4026. cmTarget* target, const std::vector<std::string>& byproducts,
  4027. cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4028. {
  4029. for (std::string const& o : byproducts) {
  4030. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4031. this->UpdateOutputToSourceMap(o, target, bt, origin);
  4032. continue;
  4033. }
  4034. // This byproduct path has a generator expression. Evaluate it to
  4035. // register the byproducts for all configurations.
  4036. for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
  4037. this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
  4038. }
  4039. }
  4040. }
  4041. void cmLocalGenerator::AddSourceOutputs(
  4042. cmSourceFile* source, const std::vector<std::string>& outputs,
  4043. OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4044. {
  4045. for (std::string const& o : outputs) {
  4046. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4047. this->UpdateOutputToSourceMap(o, source, role, bt, origin);
  4048. continue;
  4049. }
  4050. // This output path has a generator expression. Evaluate it to
  4051. // register the outputs for all configurations.
  4052. for (std::string const& out :
  4053. this->ExpandCustomCommandOutputGenex(o, bt)) {
  4054. this->UpdateOutputToSourceMap(out, source, role, bt,
  4055. cmCommandOrigin::Generator);
  4056. }
  4057. }
  4058. }
  4059. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
  4060. cmTarget* target,
  4061. cmListFileBacktrace const& bt,
  4062. cmCommandOrigin origin)
  4063. {
  4064. SourceEntry entry;
  4065. entry.Sources.Target = target;
  4066. auto pr = this->OutputToSource.emplace(byproduct, entry);
  4067. if (pr.second) {
  4068. CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
  4069. } else {
  4070. SourceEntry& current = pr.first->second;
  4071. // Has the target already been set?
  4072. if (!current.Sources.Target) {
  4073. current.Sources.Target = target;
  4074. } else {
  4075. // Multiple custom commands/targets produce the same output (source file
  4076. // or target). See also comment in other UpdateOutputToSourceMap
  4077. // overload.
  4078. //
  4079. // TODO: Warn the user about this case.
  4080. }
  4081. }
  4082. }
  4083. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
  4084. cmSourceFile* source,
  4085. OutputRole role,
  4086. cmListFileBacktrace const& bt,
  4087. cmCommandOrigin origin)
  4088. {
  4089. SourceEntry entry;
  4090. entry.Sources.Source = source;
  4091. entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
  4092. auto pr = this->OutputToSource.emplace(output, entry);
  4093. if (pr.second) {
  4094. CreateGeneratedSource(*this, output, role, origin, bt);
  4095. } else {
  4096. SourceEntry& current = pr.first->second;
  4097. // Outputs take precedence over byproducts
  4098. if (!current.Sources.Source ||
  4099. (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
  4100. current.Sources.Source = source;
  4101. current.Sources.SourceIsByproduct = false;
  4102. } else {
  4103. // Multiple custom commands produce the same output but may
  4104. // be attached to a different source file (MAIN_DEPENDENCY).
  4105. // LinearGetSourceFileWithOutput would return the first one,
  4106. // so keep the mapping for the first one.
  4107. //
  4108. // TODO: Warn the user about this case. However, the VS 8 generator
  4109. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  4110. // individual targets.
  4111. }
  4112. }
  4113. }
  4114. cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
  4115. const std::string& name) const
  4116. {
  4117. // We go through the ordered vector of targets to get reproducible results
  4118. // should multiple names match.
  4119. for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
  4120. // Does the output of any command match the source file name?
  4121. if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
  4122. return t;
  4123. }
  4124. if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
  4125. return t;
  4126. }
  4127. if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
  4128. return t;
  4129. }
  4130. }
  4131. return nullptr;
  4132. }
  4133. cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
  4134. const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
  4135. {
  4136. // Outputs take precedence over byproducts.
  4137. byproduct = false;
  4138. cmSourceFile* fallback = nullptr;
  4139. // Look through all the source files that have custom commands and see if the
  4140. // custom command has the passed source file as an output.
  4141. for (const auto& src : this->Makefile->GetSourceFiles()) {
  4142. // Does this source file have a custom command?
  4143. if (src->GetCustomCommand()) {
  4144. // Does the output of the custom command match the source file name?
  4145. if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
  4146. // Return the first matching output.
  4147. return src.get();
  4148. }
  4149. if (kind == cmSourceOutputKind::OutputOrByproduct) {
  4150. if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
  4151. // Do not return the source yet as there might be a matching output.
  4152. fallback = src.get();
  4153. }
  4154. }
  4155. }
  4156. }
  4157. // Did we find a byproduct?
  4158. byproduct = fallback != nullptr;
  4159. return fallback;
  4160. }