cmLocalGenerator.cxx 159 KB

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