cmLocalGenerator.cxx 143 KB

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