cmLocalGenerator.cxx 160 KB

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