cmLocalGenerator.cxx 160 KB

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