cmLocalGenerator.cxx 143 KB

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