cmLocalGenerator.cxx 138 KB

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