cmLocalGenerator.cxx 149 KB

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