cmLocalGenerator.cxx 138 KB

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