cmLocalGenerator.cxx 145 KB

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