cmLocalGenerator.cxx 160 KB

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