cmLocalGenerator.cxx 156 KB

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