cmLocalGenerator.cxx 159 KB

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