cmLocalGenerator.cxx 134 KB

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