cmLocalGenerator.cxx 160 KB

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