cmLocalGenerator.cxx 159 KB

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