cmLocalGenerator.cxx 139 KB

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