cmLocalGenerator.cxx 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159
  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. }
  1800. }
  1801. }
  1802. // Add MSVC runtime library flags. This is activated by the presence
  1803. // of a default selection whether or not it is overridden by a property.
  1804. cmProp msvcRuntimeLibraryDefault =
  1805. this->Makefile->GetDef("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1806. if (msvcRuntimeLibraryDefault && !msvcRuntimeLibraryDefault->empty()) {
  1807. cmProp msvcRuntimeLibraryValue =
  1808. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1809. if (!msvcRuntimeLibraryValue) {
  1810. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1811. }
  1812. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1813. *msvcRuntimeLibraryValue, this, config, target);
  1814. if (!msvcRuntimeLibrary.empty()) {
  1815. if (const char* msvcRuntimeLibraryOptions =
  1816. this->Makefile->GetDefinition(
  1817. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1818. msvcRuntimeLibrary)) {
  1819. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1820. } else if ((this->Makefile->GetSafeDefinition(
  1821. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1822. this->Makefile->GetSafeDefinition(
  1823. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1824. !cmSystemTools::GetErrorOccuredFlag()) {
  1825. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1826. this->IssueMessage(MessageType::FATAL_ERROR,
  1827. "MSVC_RUNTIME_LIBRARY value '" +
  1828. msvcRuntimeLibrary + "' not known for this " +
  1829. lang + " compiler.");
  1830. }
  1831. }
  1832. }
  1833. }
  1834. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1835. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1836. const std::string& config)
  1837. {
  1838. if (this->Makefile->IsOn("CMAKE_" + lang +
  1839. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1840. // This toolchain requires use of the language standard flag
  1841. // when linking in order to use the matching standard library.
  1842. // FIXME: If CMake gains an abstraction for standard library
  1843. // selection, this will have to be reconciled with it.
  1844. this->AddCompilerRequirementFlag(flags, target, lang);
  1845. }
  1846. this->AddLanguageFlags(flags, target, lang, config);
  1847. if (target->IsIPOEnabled(lang, config)) {
  1848. this->AppendFeatureOptions(flags, lang, "IPO");
  1849. }
  1850. }
  1851. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1852. const std::string& name) const
  1853. {
  1854. auto imported = this->ImportedGeneratorTargets.find(name);
  1855. if (imported != this->ImportedGeneratorTargets.end()) {
  1856. return imported->second;
  1857. }
  1858. // find local alias to imported target
  1859. auto aliased = this->AliasTargets.find(name);
  1860. if (aliased != this->AliasTargets.end()) {
  1861. imported = this->ImportedGeneratorTargets.find(aliased->second);
  1862. if (imported != this->ImportedGeneratorTargets.end()) {
  1863. return imported->second;
  1864. }
  1865. }
  1866. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1867. return t;
  1868. }
  1869. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1870. }
  1871. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1872. const std::string& config,
  1873. std::string& dep)
  1874. {
  1875. // Older CMake code may specify the dependency using the target
  1876. // output file rather than the target name. Such code would have
  1877. // been written before there was support for target properties that
  1878. // modify the name so stripping down to just the file name should
  1879. // produce the target name in this case.
  1880. std::string name = cmSystemTools::GetFilenameName(inName);
  1881. // If the input name is the empty string, there is no real
  1882. // dependency. Short-circuit the other checks:
  1883. if (name.empty()) {
  1884. return false;
  1885. }
  1886. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1887. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1888. }
  1889. // Look for a CMake target with the given name.
  1890. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1891. // make sure it is not just a coincidence that the target name
  1892. // found is part of the inName
  1893. if (cmSystemTools::FileIsFullPath(inName)) {
  1894. std::string tLocation;
  1895. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1896. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1897. tLocation = target->GetLocation(config);
  1898. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1899. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1900. }
  1901. std::string depLocation =
  1902. cmSystemTools::GetFilenamePath(std::string(inName));
  1903. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1904. if (depLocation != tLocation) {
  1905. // it is a full path to a depend that has the same name
  1906. // as a target but is in a different location so do not use
  1907. // the target as the depend
  1908. dep = inName;
  1909. return true;
  1910. }
  1911. }
  1912. switch (target->GetType()) {
  1913. case cmStateEnums::EXECUTABLE:
  1914. case cmStateEnums::STATIC_LIBRARY:
  1915. case cmStateEnums::SHARED_LIBRARY:
  1916. case cmStateEnums::MODULE_LIBRARY:
  1917. case cmStateEnums::UNKNOWN_LIBRARY:
  1918. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  1919. /*realname=*/true);
  1920. return true;
  1921. case cmStateEnums::OBJECT_LIBRARY:
  1922. // An object library has no single file on which to depend.
  1923. // This was listed to get the target-level dependency.
  1924. case cmStateEnums::INTERFACE_LIBRARY:
  1925. // An interface library has no file on which to depend.
  1926. // This was listed to get the target-level dependency.
  1927. case cmStateEnums::UTILITY:
  1928. case cmStateEnums::GLOBAL_TARGET:
  1929. // A utility target has no file on which to depend. This was listed
  1930. // only to get the target-level dependency.
  1931. return false;
  1932. }
  1933. }
  1934. // The name was not that of a CMake target. It must name a file.
  1935. if (cmSystemTools::FileIsFullPath(inName)) {
  1936. // This is a full path. Return it as given.
  1937. dep = inName;
  1938. return true;
  1939. }
  1940. // Check for a source file in this directory that matches the
  1941. // dependency.
  1942. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1943. dep = sf->ResolveFullPath();
  1944. return true;
  1945. }
  1946. // Treat the name as relative to the source directory in which it
  1947. // was given.
  1948. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  1949. // If the in-source path does not exist, assume it instead lives in the
  1950. // binary directory.
  1951. if (!cmSystemTools::FileExists(dep)) {
  1952. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  1953. }
  1954. dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
  1955. return true;
  1956. }
  1957. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1958. const std::string& lang, bool shared)
  1959. {
  1960. std::string flagsVar;
  1961. // Add flags for dealing with shared libraries for this language.
  1962. if (shared) {
  1963. this->AppendFlags(flags,
  1964. this->Makefile->GetSafeDefinition(
  1965. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1966. }
  1967. }
  1968. void cmLocalGenerator::AddCompilerRequirementFlag(
  1969. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1970. {
  1971. if (lang.empty()) {
  1972. return;
  1973. }
  1974. const char* defaultStd =
  1975. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1976. if (!defaultStd || !*defaultStd) {
  1977. // This compiler has no notion of language standard levels.
  1978. return;
  1979. }
  1980. std::string extProp = lang + "_EXTENSIONS";
  1981. bool ext = true;
  1982. if (cmProp extPropValue = target->GetProperty(extProp)) {
  1983. if (cmIsOff(*extPropValue)) {
  1984. ext = false;
  1985. }
  1986. }
  1987. std::string stdProp = lang + "_STANDARD";
  1988. cmProp standardProp = target->GetProperty(stdProp);
  1989. if (!standardProp) {
  1990. if (ext) {
  1991. // No language standard is specified and extensions are not disabled.
  1992. // Check if this compiler needs a flag to enable extensions.
  1993. std::string const option_flag =
  1994. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1995. if (const char* opt =
  1996. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1997. std::vector<std::string> optVec = cmExpandedList(opt);
  1998. for (std::string const& i : optVec) {
  1999. this->AppendFlagEscape(flags, i);
  2000. }
  2001. }
  2002. }
  2003. return;
  2004. }
  2005. std::string const type = ext ? "EXTENSION" : "STANDARD";
  2006. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  2007. std::string option_flag =
  2008. "CMAKE_" + lang + *standardProp + "_" + type + "_COMPILE_OPTION";
  2009. const char* opt =
  2010. target->Target->GetMakefile()->GetDefinition(option_flag);
  2011. if (!opt) {
  2012. std::ostringstream e;
  2013. e << "Target \"" << target->GetName()
  2014. << "\" requires the language "
  2015. "dialect \""
  2016. << lang << *standardProp << "\" "
  2017. << (ext ? "(with compiler extensions)" : "")
  2018. << ", but CMake "
  2019. "does not know the compile flags to use to enable it.";
  2020. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2021. } else {
  2022. std::vector<std::string> optVec = cmExpandedList(opt);
  2023. for (std::string const& i : optVec) {
  2024. this->AppendFlagEscape(flags, i);
  2025. }
  2026. }
  2027. return;
  2028. }
  2029. static std::map<std::string, std::vector<std::string>> langStdMap;
  2030. if (langStdMap.empty()) {
  2031. // Maintain sorted order, most recent first.
  2032. langStdMap["CXX"].emplace_back("20");
  2033. langStdMap["CXX"].emplace_back("17");
  2034. langStdMap["CXX"].emplace_back("14");
  2035. langStdMap["CXX"].emplace_back("11");
  2036. langStdMap["CXX"].emplace_back("98");
  2037. langStdMap["OBJCXX"].emplace_back("20");
  2038. langStdMap["OBJCXX"].emplace_back("17");
  2039. langStdMap["OBJCXX"].emplace_back("14");
  2040. langStdMap["OBJCXX"].emplace_back("11");
  2041. langStdMap["OBJCXX"].emplace_back("98");
  2042. langStdMap["C"].emplace_back("11");
  2043. langStdMap["C"].emplace_back("99");
  2044. langStdMap["C"].emplace_back("90");
  2045. langStdMap["OBJC"].emplace_back("11");
  2046. langStdMap["OBJC"].emplace_back("99");
  2047. langStdMap["OBJC"].emplace_back("90");
  2048. langStdMap["CUDA"].emplace_back("20");
  2049. langStdMap["CUDA"].emplace_back("17");
  2050. langStdMap["CUDA"].emplace_back("14");
  2051. langStdMap["CUDA"].emplace_back("11");
  2052. langStdMap["CUDA"].emplace_back("03");
  2053. }
  2054. std::string standard(*standardProp);
  2055. if (lang == "CUDA" && standard == "98") {
  2056. standard = "03";
  2057. }
  2058. std::vector<std::string>& stds = langStdMap[lang];
  2059. auto stdIt = std::find(stds.begin(), stds.end(), standard);
  2060. if (stdIt == stds.end()) {
  2061. std::string e =
  2062. lang + "_STANDARD is set to invalid value '" + standard + "'";
  2063. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  2064. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  2065. return;
  2066. }
  2067. auto defaultStdIt = std::find(stds.begin(), stds.end(), defaultStd);
  2068. if (defaultStdIt == stds.end()) {
  2069. std::string e = "CMAKE_" + lang +
  2070. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  2071. "'";
  2072. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  2073. return;
  2074. }
  2075. // If the standard requested is older than the compiler's default
  2076. // then we need to use a flag to change it. The comparison is
  2077. // greater-or-equal because the standards are stored in backward
  2078. // chronological order.
  2079. if (stdIt >= defaultStdIt) {
  2080. std::string option_flag =
  2081. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  2082. std::string const& opt =
  2083. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  2084. std::vector<std::string> optVec = cmExpandedList(opt);
  2085. for (std::string const& i : optVec) {
  2086. this->AppendFlagEscape(flags, i);
  2087. }
  2088. return;
  2089. }
  2090. // The standard requested is at least as new as the compiler's default,
  2091. // and the standard request is not required. Decay to the newest standard
  2092. // for which a flag is defined.
  2093. for (; stdIt < defaultStdIt; ++stdIt) {
  2094. std::string option_flag =
  2095. cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION");
  2096. if (const char* opt =
  2097. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  2098. std::vector<std::string> optVec = cmExpandedList(opt);
  2099. for (std::string const& i : optVec) {
  2100. this->AppendFlagEscape(flags, i);
  2101. }
  2102. return;
  2103. }
  2104. }
  2105. }
  2106. static void AddVisibilityCompileOption(std::string& flags,
  2107. cmGeneratorTarget const* target,
  2108. cmLocalGenerator* lg,
  2109. const std::string& lang,
  2110. std::string* warnCMP0063)
  2111. {
  2112. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2113. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  2114. if (!opt) {
  2115. return;
  2116. }
  2117. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2118. cmProp prop = target->GetProperty(flagDefine);
  2119. if (!prop) {
  2120. return;
  2121. }
  2122. if (warnCMP0063) {
  2123. *warnCMP0063 += " " + flagDefine + "\n";
  2124. return;
  2125. }
  2126. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2127. (*prop != "internal")) {
  2128. std::ostringstream e;
  2129. e << "Target " << target->GetName() << " uses unsupported value \""
  2130. << *prop << "\" for " << flagDefine << "."
  2131. << " The supported values are: default, hidden, protected, and "
  2132. "internal.";
  2133. cmSystemTools::Error(e.str());
  2134. return;
  2135. }
  2136. std::string option = opt + *prop;
  2137. lg->AppendFlags(flags, option);
  2138. }
  2139. static void AddInlineVisibilityCompileOption(std::string& flags,
  2140. cmGeneratorTarget const* target,
  2141. cmLocalGenerator* lg,
  2142. std::string* warnCMP0063,
  2143. const std::string& lang)
  2144. {
  2145. std::string compileOption =
  2146. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2147. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  2148. if (!opt) {
  2149. return;
  2150. }
  2151. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2152. if (!prop) {
  2153. return;
  2154. }
  2155. if (warnCMP0063) {
  2156. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2157. return;
  2158. }
  2159. lg->AppendFlags(flags, opt);
  2160. }
  2161. void cmLocalGenerator::AddVisibilityPresetFlags(
  2162. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2163. {
  2164. if (lang.empty()) {
  2165. return;
  2166. }
  2167. std::string warnCMP0063;
  2168. std::string* pWarnCMP0063 = nullptr;
  2169. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2170. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2171. !target->IsExecutableWithExports()) {
  2172. switch (target->GetPolicyStatusCMP0063()) {
  2173. case cmPolicies::OLD:
  2174. return;
  2175. case cmPolicies::WARN:
  2176. pWarnCMP0063 = &warnCMP0063;
  2177. break;
  2178. default:
  2179. break;
  2180. }
  2181. }
  2182. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2183. if (lang == "CXX" || lang == "OBJCXX") {
  2184. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2185. }
  2186. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2187. std::ostringstream w;
  2188. /* clang-format off */
  2189. w <<
  2190. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2191. "Target \"" << target->GetName() << "\" of "
  2192. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2193. "has the following visibility properties set for " << lang << ":\n" <<
  2194. warnCMP0063 <<
  2195. "For compatibility CMake is not honoring them for this target.";
  2196. /* clang-format on */
  2197. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2198. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2199. }
  2200. }
  2201. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2202. cmGeneratorTarget const* target,
  2203. std::string const& lang,
  2204. const std::string& config)
  2205. {
  2206. int targetType = target->GetType();
  2207. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2208. (targetType == cmStateEnums::MODULE_LIBRARY));
  2209. if (this->GetShouldUseOldFlags(shared, lang)) {
  2210. this->AddSharedFlags(flags, lang, shared);
  2211. } else {
  2212. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2213. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  2214. this->AddPositionIndependentFlags(flags, lang, targetType);
  2215. }
  2216. return;
  2217. }
  2218. if (target->GetLinkInterfaceDependentBoolProperty(
  2219. "POSITION_INDEPENDENT_CODE", config)) {
  2220. this->AddPositionIndependentFlags(flags, lang, targetType);
  2221. }
  2222. if (shared) {
  2223. this->AppendFeatureOptions(flags, lang, "DLL");
  2224. }
  2225. }
  2226. }
  2227. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2228. const std::string& lang) const
  2229. {
  2230. std::string originalFlags =
  2231. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2232. if (shared) {
  2233. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2234. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2235. if (flags != originalFlags) {
  2236. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2237. case cmPolicies::WARN: {
  2238. std::ostringstream e;
  2239. e << "Variable " << flagsVar
  2240. << " has been modified. CMake "
  2241. "will ignore the POSITION_INDEPENDENT_CODE target property "
  2242. "for "
  2243. "shared libraries and will use the "
  2244. << flagsVar
  2245. << " variable "
  2246. "instead. This may cause errors if the original content of "
  2247. << flagsVar << " was removed.\n"
  2248. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2249. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2250. CM_FALLTHROUGH;
  2251. }
  2252. case cmPolicies::OLD:
  2253. return true;
  2254. case cmPolicies::REQUIRED_IF_USED:
  2255. case cmPolicies::REQUIRED_ALWAYS:
  2256. case cmPolicies::NEW:
  2257. return false;
  2258. }
  2259. }
  2260. }
  2261. return false;
  2262. }
  2263. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2264. std::string const& lang,
  2265. int targetType)
  2266. {
  2267. std::string picFlags;
  2268. if (targetType == cmStateEnums::EXECUTABLE) {
  2269. picFlags = this->Makefile->GetSafeDefinition(
  2270. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2271. }
  2272. if (picFlags.empty()) {
  2273. picFlags = this->Makefile->GetSafeDefinition(
  2274. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2275. }
  2276. if (!picFlags.empty()) {
  2277. std::vector<std::string> options = cmExpandedList(picFlags);
  2278. for (std::string const& o : options) {
  2279. this->AppendFlagEscape(flags, o);
  2280. }
  2281. }
  2282. }
  2283. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2284. const std::string& var,
  2285. const std::string& config)
  2286. {
  2287. // Add the flags from the variable itself.
  2288. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2289. // Add the flags from the build-type specific variable.
  2290. if (!config.empty()) {
  2291. const std::string flagsVar =
  2292. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2293. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2294. }
  2295. }
  2296. void cmLocalGenerator::AppendFlags(std::string& flags,
  2297. const std::string& newFlags) const
  2298. {
  2299. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2300. if (!newFlags.empty() && !allSpaces) {
  2301. if (!flags.empty()) {
  2302. flags += " ";
  2303. }
  2304. flags += newFlags;
  2305. }
  2306. }
  2307. void cmLocalGenerator::AppendFlags(
  2308. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2309. {
  2310. for (BT<std::string> const& flag : newFlags) {
  2311. this->AppendFlags(flags, flag.Value);
  2312. }
  2313. }
  2314. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2315. const std::string& rawFlag) const
  2316. {
  2317. this->AppendFlags(
  2318. flags,
  2319. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2320. }
  2321. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2322. {
  2323. std::vector<std::string> configsList;
  2324. std::string configDefault = this->Makefile->GetConfigurations(configsList);
  2325. if (configsList.empty()) {
  2326. configsList.push_back(configDefault);
  2327. }
  2328. for (std::string const& config : configsList) {
  2329. // FIXME: Refactor collection of sources to not evaluate object
  2330. // libraries.
  2331. std::vector<cmSourceFile*> sources;
  2332. target->GetSourceFiles(sources, config);
  2333. const std::string configUpper = cmSystemTools::UpperCase(config);
  2334. for (const std::string& lang : { "C", "CXX", "OBJC", "OBJCXX" }) {
  2335. auto langSources = std::count_if(
  2336. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2337. return lang == sf->GetLanguage() &&
  2338. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2339. });
  2340. if (langSources == 0) {
  2341. continue;
  2342. }
  2343. std::vector<std::string> architectures;
  2344. if (!this->GetGlobalGenerator()->IsXcode()) {
  2345. target->GetAppleArchs(config, architectures);
  2346. }
  2347. if (architectures.empty()) {
  2348. architectures.emplace_back();
  2349. } else {
  2350. std::string useMultiArchPch;
  2351. for (const std::string& arch : architectures) {
  2352. const std::string pchHeader =
  2353. target->GetPchHeader(config, lang, arch);
  2354. if (!pchHeader.empty()) {
  2355. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2356. ";-include", pchHeader);
  2357. }
  2358. }
  2359. if (!useMultiArchPch.empty()) {
  2360. target->Target->SetProperty(
  2361. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"), useMultiArchPch);
  2362. }
  2363. }
  2364. for (const std::string& arch : architectures) {
  2365. const std::string pchSource = target->GetPchSource(config, lang, arch);
  2366. const std::string pchHeader = target->GetPchHeader(config, lang, arch);
  2367. if (pchSource.empty() || pchHeader.empty()) {
  2368. continue;
  2369. }
  2370. const std::string pchExtension =
  2371. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2372. if (pchExtension.empty()) {
  2373. continue;
  2374. }
  2375. cmProp ReuseFrom =
  2376. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2377. auto pch_sf = this->Makefile->GetOrCreateSource(
  2378. pchSource, false, cmSourceFileLocationKind::Known);
  2379. if (!this->GetGlobalGenerator()->IsXcode()) {
  2380. if (!ReuseFrom) {
  2381. target->AddSource(pchSource, true);
  2382. }
  2383. const std::string pchFile = target->GetPchFile(config, lang, arch);
  2384. // Exclude the pch files from linking
  2385. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2386. if (!ReuseFrom) {
  2387. pch_sf->AppendProperty(
  2388. "OBJECT_OUTPUTS",
  2389. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
  2390. } else {
  2391. auto reuseTarget =
  2392. this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
  2393. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2394. const std::string compilerId =
  2395. this->Makefile->GetSafeDefinition(
  2396. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2397. const std::string compilerVersion =
  2398. this->Makefile->GetSafeDefinition(
  2399. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2400. const std::string langFlags =
  2401. this->Makefile->GetSafeDefinition(
  2402. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2403. // MSVC 2008 is producing both .pdb and .idb files with /Zi.
  2404. if ((langFlags.find("/ZI") != std::string::npos ||
  2405. langFlags.find("-ZI") != std::string::npos) ||
  2406. (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  2407. compilerVersion.c_str(),
  2408. "16.0") &&
  2409. compilerId == "MSVC")) {
  2410. CopyPchCompilePdb(config, target, *ReuseFrom, reuseTarget,
  2411. { ".pdb", ".idb" });
  2412. } else if ((langFlags.find("/Zi") != std::string::npos ||
  2413. langFlags.find("-Zi") != std::string::npos)) {
  2414. CopyPchCompilePdb(config, target, *ReuseFrom, reuseTarget,
  2415. { ".pdb" });
  2416. }
  2417. }
  2418. if (reuseTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2419. std::string pchSourceObj =
  2420. reuseTarget->GetPchFileObject(config, lang, arch);
  2421. // Link to the pch object file
  2422. target->Target->AppendProperty(
  2423. cmStrCat("LINK_FLAGS_", configUpper),
  2424. cmStrCat(" ",
  2425. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2426. true);
  2427. }
  2428. }
  2429. } else {
  2430. pch_sf->SetProperty("PCH_EXTENSION", pchExtension.c_str());
  2431. }
  2432. // Add pchHeader to source files, which will
  2433. // be grouped as "Precompile Header File"
  2434. auto pchHeader_sf = this->Makefile->GetOrCreateSource(
  2435. pchHeader, true, cmSourceFileLocationKind::Known);
  2436. std::string err;
  2437. pchHeader_sf->ResolveFullPath(&err);
  2438. // The pch file is generated, but mark it as not generated
  2439. // so that a clean operation will not remove it from disk
  2440. pchHeader_sf->SetProperty("GENERATED", "0");
  2441. target->AddSource(pchHeader);
  2442. }
  2443. }
  2444. }
  2445. }
  2446. }
  2447. void cmLocalGenerator::CopyPchCompilePdb(
  2448. const std::string& config, cmGeneratorTarget* target,
  2449. const std::string& ReuseFrom, cmGeneratorTarget* reuseTarget,
  2450. const std::vector<std::string>& extensions)
  2451. {
  2452. const std::string pdb_prefix =
  2453. this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
  2454. const std::string target_compile_pdb_dir =
  2455. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2456. target->GetName(), ".dir/");
  2457. const std::string copy_script =
  2458. cmStrCat(target_compile_pdb_dir, "copy_idb_pdb.cmake");
  2459. cmGeneratedFileStream file(copy_script);
  2460. file << "# CMake generated file\n";
  2461. file << "# The compiler generated pdb file needs to be written to disk\n"
  2462. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2463. << "# the pdb file is ready to be copied.\n\n";
  2464. for (auto const& extension : extensions) {
  2465. const std::string from_file =
  2466. cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2467. "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
  2468. const std::string to_dir =
  2469. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2470. target->GetName(), ".dir/${PDB_PREFIX}");
  2471. const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
  2472. std::string dest_file = to_file;
  2473. std::string const& prefix = target->GetSafeProperty("PREFIX");
  2474. if (!prefix.empty()) {
  2475. dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
  2476. }
  2477. file << "foreach(retry RANGE 1 30)\n";
  2478. file << " if (EXISTS \"" << from_file << "\" AND \"" << from_file
  2479. << " \" IS_NEWER_THAN \"" << dest_file << "\")\n";
  2480. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2481. file << " \"" << from_file << "\""
  2482. << " \"" << to_dir << "\" RESULT_VARIABLE result "
  2483. << " ERROR_QUIET)\n";
  2484. file << " if (NOT result EQUAL 0)\n"
  2485. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2486. << " -E sleep 1)\n"
  2487. << " else()\n";
  2488. if (!prefix.empty()) {
  2489. file << " file(REMOVE \"" << dest_file << "\")\n";
  2490. file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
  2491. }
  2492. file << " break()\n"
  2493. << " endif()\n";
  2494. file << " else()\n"
  2495. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2496. << " -E sleep 1)\n"
  2497. << " endif()\n";
  2498. file << "endforeach()\n";
  2499. }
  2500. bool stdPipesUTF8 = true;
  2501. auto configGenex = [&](cm::string_view expr) -> std::string {
  2502. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2503. return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
  2504. }
  2505. return std::string(expr);
  2506. };
  2507. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2508. { configGenex(cmSystemTools::GetCMakeCommand()),
  2509. configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
  2510. configGenex(copy_script) });
  2511. const std::string no_main_dependency;
  2512. const std::vector<std::string> no_deps;
  2513. const char* no_message = "";
  2514. const char* no_current_dir = nullptr;
  2515. std::vector<std::string> no_byproducts;
  2516. std::vector<std::string> outputs;
  2517. outputs.push_back(
  2518. cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb"));
  2519. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2520. this->AddCustomCommandToTarget(
  2521. target->GetName(), outputs, no_deps, commandLines,
  2522. cmCustomCommandType::PRE_BUILD, no_message, no_current_dir, true, false,
  2523. "", "", false, cmObjectLibraryCommands::Reject, stdPipesUTF8);
  2524. } else {
  2525. cmImplicitDependsList no_implicit_depends;
  2526. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(
  2527. outputs, no_byproducts, no_deps, no_main_dependency, no_implicit_depends,
  2528. commandLines, no_message, no_current_dir, false, true, false, false, "",
  2529. "", stdPipesUTF8);
  2530. if (copy_rule) {
  2531. target->AddSource(copy_rule->ResolveFullPath());
  2532. }
  2533. }
  2534. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2535. target_compile_pdb_dir);
  2536. }
  2537. namespace {
  2538. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2539. std::string const& filename)
  2540. {
  2541. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2542. sf->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2543. sf->SetProperty("SKIP_AUTOGEN", "ON");
  2544. }
  2545. inline void IncludeFileInUnitySources(cmGeneratedFileStream& unity_file,
  2546. std::string const& sf_full_path,
  2547. cmProp beforeInclude,
  2548. cmProp afterInclude)
  2549. {
  2550. if (beforeInclude) {
  2551. unity_file << *beforeInclude << "\n";
  2552. }
  2553. unity_file << "#include \"" << sf_full_path << "\"\n";
  2554. if (afterInclude) {
  2555. unity_file << *afterInclude << "\n";
  2556. }
  2557. }
  2558. std::vector<std::string> AddUnityFilesModeAuto(
  2559. cmGeneratorTarget* target, std::string const& lang,
  2560. std::vector<cmSourceFile*> const& filtered_sources, cmProp beforeInclude,
  2561. cmProp afterInclude, std::string const& filename_base, size_t batchSize)
  2562. {
  2563. if (batchSize == 0) {
  2564. batchSize = filtered_sources.size();
  2565. }
  2566. std::vector<std::string> unity_files;
  2567. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2568. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2569. chunk = std::min(itemsLeft, batchSize);
  2570. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2571. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2572. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2573. {
  2574. size_t begin = batch * batchSize;
  2575. size_t end = begin + chunk;
  2576. cmGeneratedFileStream file(
  2577. filename_tmp, false,
  2578. target->GetGlobalGenerator()->GetMakefileEncoding());
  2579. file << "/* generated by CMake */\n\n";
  2580. for (; begin != end; ++begin) {
  2581. cmSourceFile* sf = filtered_sources[begin];
  2582. RegisterUnitySources(target, sf, filename);
  2583. IncludeFileInUnitySources(file, sf->ResolveFullPath(), beforeInclude,
  2584. afterInclude);
  2585. }
  2586. }
  2587. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2588. unity_files.emplace_back(std::move(filename));
  2589. }
  2590. return unity_files;
  2591. }
  2592. std::vector<std::string> AddUnityFilesModeGroup(
  2593. cmGeneratorTarget* target, std::string const& lang,
  2594. std::vector<cmSourceFile*> const& filtered_sources, cmProp beforeInclude,
  2595. cmProp afterInclude, std::string const& filename_base)
  2596. {
  2597. std::vector<std::string> unity_files;
  2598. // sources organized by group name. Drop any source
  2599. // without a group
  2600. std::unordered_map<std::string, std::vector<cmSourceFile*>> explicit_mapping;
  2601. for (cmSourceFile* sf : filtered_sources) {
  2602. if (cmProp value = sf->GetProperty("UNITY_GROUP")) {
  2603. auto i = explicit_mapping.find(*value);
  2604. if (i == explicit_mapping.end()) {
  2605. std::vector<cmSourceFile*> sources{ sf };
  2606. explicit_mapping.emplace(*value, sources);
  2607. } else {
  2608. i->second.emplace_back(sf);
  2609. }
  2610. }
  2611. }
  2612. for (auto const& item : explicit_mapping) {
  2613. auto const& name = item.first;
  2614. std::string filename = cmStrCat(filename_base, "unity_", name,
  2615. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2616. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2617. {
  2618. cmGeneratedFileStream file(
  2619. filename_tmp, false,
  2620. target->GetGlobalGenerator()->GetMakefileEncoding());
  2621. file << "/* generated by CMake */\n\n";
  2622. for (cmSourceFile* sf : item.second) {
  2623. RegisterUnitySources(target, sf, filename);
  2624. IncludeFileInUnitySources(file, sf->ResolveFullPath(), beforeInclude,
  2625. afterInclude);
  2626. }
  2627. }
  2628. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2629. unity_files.emplace_back(std::move(filename));
  2630. }
  2631. return unity_files;
  2632. }
  2633. }
  2634. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2635. {
  2636. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2637. return;
  2638. }
  2639. // FIXME: Handle all configurations in multi-config generators.
  2640. std::string config;
  2641. if (!this->GetGlobalGenerator()->IsMultiConfig()) {
  2642. config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2643. }
  2644. std::string filename_base =
  2645. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2646. target->GetName(), ".dir/Unity/");
  2647. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2648. std::vector<cmSourceFile*> sources;
  2649. target->GetSourceFiles(sources, config);
  2650. cmProp batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2651. const size_t unityBatchSize = batchSizeString
  2652. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2653. : 0;
  2654. cmProp beforeInclude =
  2655. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2656. cmProp afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2657. cmProp unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2658. for (std::string lang : { "C", "CXX" }) {
  2659. std::vector<cmSourceFile*> filtered_sources;
  2660. std::copy_if(sources.begin(), sources.end(),
  2661. std::back_inserter(filtered_sources), [&](cmSourceFile* sf) {
  2662. return sf->GetLanguage() == lang &&
  2663. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2664. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2665. !sf->GetProperty("COMPILE_OPTIONS") &&
  2666. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2667. !sf->GetProperty("COMPILE_FLAGS") &&
  2668. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2669. });
  2670. std::vector<std::string> unity_files;
  2671. if (!unityMode || *unityMode == "BATCH") {
  2672. unity_files =
  2673. AddUnityFilesModeAuto(target, lang, filtered_sources, beforeInclude,
  2674. afterInclude, filename_base, unityBatchSize);
  2675. } else if (unityMode && *unityMode == "GROUP") {
  2676. unity_files =
  2677. AddUnityFilesModeGroup(target, lang, filtered_sources, beforeInclude,
  2678. afterInclude, filename_base);
  2679. } else {
  2680. // unity mode is set to an unsupported value
  2681. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2682. " assigned to target " + target->GetName() +
  2683. ". Acceptable values are BATCH and GROUP.");
  2684. this->IssueMessage(MessageType::FATAL_ERROR, e);
  2685. }
  2686. for (auto const& file : unity_files) {
  2687. auto unity = this->GetMakefile()->GetOrCreateSource(file);
  2688. target->AddSource(file, true);
  2689. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2690. unity->SetProperty("UNITY_SOURCE_FILE", file.c_str());
  2691. }
  2692. }
  2693. }
  2694. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2695. cmGeneratorTarget* target,
  2696. const std::string& config,
  2697. const std::string& lang)
  2698. {
  2699. if (!target->IsIPOEnabled(lang, config)) {
  2700. return;
  2701. }
  2702. switch (target->GetType()) {
  2703. case cmStateEnums::EXECUTABLE:
  2704. case cmStateEnums::SHARED_LIBRARY:
  2705. case cmStateEnums::MODULE_LIBRARY:
  2706. break;
  2707. default:
  2708. return;
  2709. }
  2710. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2711. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  2712. if (rawFlagsList == nullptr) {
  2713. return;
  2714. }
  2715. std::vector<std::string> flagsList = cmExpandedList(rawFlagsList);
  2716. for (std::string const& o : flagsList) {
  2717. this->AppendFlagEscape(flags, o);
  2718. }
  2719. }
  2720. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2721. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2722. const std::string& lang)
  2723. {
  2724. // For now, only EXECUTABLE is concerned
  2725. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2726. return;
  2727. }
  2728. const char* PICValue = target->GetLinkPIEProperty(config);
  2729. if (PICValue == nullptr) {
  2730. // POSITION_INDEPENDENT_CODE is not set
  2731. return;
  2732. }
  2733. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2734. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2735. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2736. return;
  2737. }
  2738. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2739. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2740. if (pieFlags.empty()) {
  2741. return;
  2742. }
  2743. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2744. for (const auto& flag : flagsList) {
  2745. this->AppendFlagEscape(flags, flag);
  2746. }
  2747. }
  2748. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2749. std::string const& options_list,
  2750. const char* regex) const
  2751. {
  2752. // Short-circuit if there are no options.
  2753. if (options_list.empty()) {
  2754. return;
  2755. }
  2756. // Expand the list of options.
  2757. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2758. this->AppendCompileOptions(options, options_vec, regex);
  2759. }
  2760. void cmLocalGenerator::AppendCompileOptions(
  2761. std::string& options, const std::vector<std::string>& options_vec,
  2762. const char* regex) const
  2763. {
  2764. if (regex != nullptr) {
  2765. // Filter flags upon specified reges.
  2766. cmsys::RegularExpression r(regex);
  2767. for (std::string const& opt : options_vec) {
  2768. if (r.find(opt)) {
  2769. this->AppendFlagEscape(options, opt);
  2770. }
  2771. }
  2772. } else {
  2773. for (std::string const& opt : options_vec) {
  2774. this->AppendFlagEscape(options, opt);
  2775. }
  2776. }
  2777. }
  2778. void cmLocalGenerator::AppendCompileOptions(
  2779. std::vector<BT<std::string>>& options,
  2780. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2781. {
  2782. if (regex != nullptr) {
  2783. // Filter flags upon specified regular expressions.
  2784. cmsys::RegularExpression r(regex);
  2785. for (BT<std::string> const& opt : options_vec) {
  2786. if (r.find(opt.Value)) {
  2787. std::string flag;
  2788. this->AppendFlagEscape(flag, opt.Value);
  2789. options.emplace_back(std::move(flag), opt.Backtrace);
  2790. }
  2791. }
  2792. } else {
  2793. for (BT<std::string> const& opt : options_vec) {
  2794. std::string flag;
  2795. this->AppendFlagEscape(flag, opt.Value);
  2796. options.emplace_back(std::move(flag), opt.Backtrace);
  2797. }
  2798. }
  2799. }
  2800. void cmLocalGenerator::AppendIncludeDirectories(
  2801. std::vector<std::string>& includes, const std::string& includes_list,
  2802. const cmSourceFile& sourceFile) const
  2803. {
  2804. // Short-circuit if there are no includes.
  2805. if (includes_list.empty()) {
  2806. return;
  2807. }
  2808. // Expand the list of includes.
  2809. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2810. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2811. }
  2812. void cmLocalGenerator::AppendIncludeDirectories(
  2813. std::vector<std::string>& includes,
  2814. const std::vector<std::string>& includes_vec,
  2815. const cmSourceFile& sourceFile) const
  2816. {
  2817. std::unordered_set<std::string> uniqueIncludes;
  2818. for (const std::string& include : includes_vec) {
  2819. if (!cmSystemTools::FileIsFullPath(include)) {
  2820. std::ostringstream e;
  2821. e << "Found relative path while evaluating include directories of "
  2822. "\""
  2823. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2824. << "\"\n";
  2825. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2826. return;
  2827. }
  2828. std::string inc = include;
  2829. if (!cmIsOff(inc)) {
  2830. cmSystemTools::ConvertToUnixSlashes(inc);
  2831. }
  2832. if (uniqueIncludes.insert(inc).second) {
  2833. includes.push_back(std::move(inc));
  2834. }
  2835. }
  2836. }
  2837. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2838. std::string const& defines_list) const
  2839. {
  2840. std::set<BT<std::string>> tmp;
  2841. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2842. for (BT<std::string> const& i : tmp) {
  2843. defines.emplace(i.Value);
  2844. }
  2845. }
  2846. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2847. std::string const& defines_list) const
  2848. {
  2849. // Short-circuit if there are no definitions.
  2850. if (defines_list.empty()) {
  2851. return;
  2852. }
  2853. // Expand the list of definitions.
  2854. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2855. }
  2856. void cmLocalGenerator::AppendDefines(
  2857. std::set<BT<std::string>>& defines,
  2858. const std::vector<BT<std::string>>& defines_vec) const
  2859. {
  2860. for (BT<std::string> const& d : defines_vec) {
  2861. // Skip unsupported definitions.
  2862. if (!this->CheckDefinition(d.Value)) {
  2863. continue;
  2864. }
  2865. defines.insert(d);
  2866. }
  2867. }
  2868. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2869. std::string& definesString,
  2870. const std::string& lang)
  2871. {
  2872. // Lookup the define flag for the current language.
  2873. std::string dflag = "-D";
  2874. if (!lang.empty()) {
  2875. const char* df =
  2876. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  2877. if (df && *df) {
  2878. dflag = df;
  2879. }
  2880. }
  2881. const char* itemSeparator = definesString.empty() ? "" : " ";
  2882. for (std::string const& define : defines) {
  2883. // Append the definition with proper escaping.
  2884. std::string def = dflag;
  2885. if (this->GetState()->UseWatcomWMake()) {
  2886. // The Watcom compiler does its own command line parsing instead
  2887. // of using the windows shell rules. Definitions are one of
  2888. // -DNAME
  2889. // -DNAME=<cpp-token>
  2890. // -DNAME="c-string with spaces and other characters(?@#$)"
  2891. //
  2892. // Watcom will properly parse each of these cases from the
  2893. // command line without any escapes. However we still have to
  2894. // get the '$' and '#' characters through WMake as '$$' and
  2895. // '$#'.
  2896. for (char c : define) {
  2897. if (c == '$' || c == '#') {
  2898. def += '$';
  2899. }
  2900. def += c;
  2901. }
  2902. } else {
  2903. // Make the definition appear properly on the command line. Use
  2904. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2905. std::string::size_type eq = define.find('=');
  2906. def += define.substr(0, eq);
  2907. if (eq != std::string::npos) {
  2908. def += "=";
  2909. def += this->EscapeForShell(define.substr(eq + 1), true);
  2910. }
  2911. }
  2912. definesString += itemSeparator;
  2913. itemSeparator = " ";
  2914. definesString += def;
  2915. }
  2916. }
  2917. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2918. const std::string& lang,
  2919. const char* feature)
  2920. {
  2921. const char* optionList = this->Makefile->GetDefinition(
  2922. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  2923. if (optionList != nullptr) {
  2924. std::vector<std::string> options = cmExpandedList(optionList);
  2925. for (std::string const& o : options) {
  2926. this->AppendFlagEscape(flags, o);
  2927. }
  2928. }
  2929. }
  2930. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2931. const std::string& config)
  2932. {
  2933. std::string featureName = feature;
  2934. // TODO: Define accumulation policy for features (prepend, append,
  2935. // replace). Currently we always replace.
  2936. if (!config.empty()) {
  2937. featureName += "_";
  2938. featureName += cmSystemTools::UpperCase(config);
  2939. }
  2940. cmStateSnapshot snp = this->StateSnapshot;
  2941. while (snp.IsValid()) {
  2942. if (cmProp value = snp.GetDirectory().GetProperty(featureName)) {
  2943. return value->c_str();
  2944. }
  2945. snp = snp.GetBuildsystemDirectoryParent();
  2946. }
  2947. return nullptr;
  2948. }
  2949. std::string cmLocalGenerator::GetProjectName() const
  2950. {
  2951. return this->StateSnapshot.GetProjectName();
  2952. }
  2953. std::string cmLocalGenerator::ConstructComment(
  2954. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2955. {
  2956. // Check for a comment provided with the command.
  2957. if (ccg.GetComment()) {
  2958. return ccg.GetComment();
  2959. }
  2960. // Construct a reasonable default comment if possible.
  2961. if (!ccg.GetOutputs().empty()) {
  2962. std::string comment;
  2963. comment = "Generating ";
  2964. const char* sep = "";
  2965. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2966. for (std::string const& o : ccg.GetOutputs()) {
  2967. comment += sep;
  2968. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2969. sep = ", ";
  2970. }
  2971. return comment;
  2972. }
  2973. // Otherwise use the provided default.
  2974. return default_comment;
  2975. }
  2976. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2977. {
  2978. public:
  2979. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2980. std::string const& dest, bool implib)
  2981. : cmInstallTargetGenerator(
  2982. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2983. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2984. false)
  2985. {
  2986. this->Compute(lg);
  2987. }
  2988. };
  2989. void cmLocalGenerator::GenerateTargetInstallRules(
  2990. std::ostream& os, const std::string& config,
  2991. std::vector<std::string> const& configurationTypes)
  2992. {
  2993. // Convert the old-style install specification from each target to
  2994. // an install generator and run it.
  2995. const auto& tgts = this->GetGeneratorTargets();
  2996. for (const auto& l : tgts) {
  2997. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2998. continue;
  2999. }
  3000. // Include the user-specified pre-install script for this target.
  3001. if (cmProp preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3002. cmInstallScriptGenerator g(*preinstall, false, "", false);
  3003. g.Generate(os, config, configurationTypes);
  3004. }
  3005. // Install this target if a destination is given.
  3006. if (!l->Target->GetInstallPath().empty()) {
  3007. // Compute the full install destination. Note that converting
  3008. // to unix slashes also removes any trailing slash.
  3009. // We also skip over the leading slash given by the user.
  3010. std::string destination = l->Target->GetInstallPath().substr(1);
  3011. cmSystemTools::ConvertToUnixSlashes(destination);
  3012. if (destination.empty()) {
  3013. destination = ".";
  3014. }
  3015. // Generate the proper install generator for this target type.
  3016. switch (l->GetType()) {
  3017. case cmStateEnums::EXECUTABLE:
  3018. case cmStateEnums::STATIC_LIBRARY:
  3019. case cmStateEnums::MODULE_LIBRARY: {
  3020. // Use a target install generator.
  3021. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3022. false);
  3023. g.Generate(os, config, configurationTypes);
  3024. } break;
  3025. case cmStateEnums::SHARED_LIBRARY: {
  3026. #if defined(_WIN32) || defined(__CYGWIN__)
  3027. // Special code to handle DLL. Install the import library
  3028. // to the normal destination and the DLL to the runtime
  3029. // destination.
  3030. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3031. true);
  3032. g1.Generate(os, config, configurationTypes);
  3033. // We also skip over the leading slash given by the user.
  3034. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3035. cmSystemTools::ConvertToUnixSlashes(destination);
  3036. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3037. false);
  3038. g2.Generate(os, config, configurationTypes);
  3039. #else
  3040. // Use a target install generator.
  3041. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3042. false);
  3043. g.Generate(os, config, configurationTypes);
  3044. #endif
  3045. } break;
  3046. default:
  3047. break;
  3048. }
  3049. }
  3050. // Include the user-specified post-install script for this target.
  3051. if (cmProp postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3052. cmInstallScriptGenerator g(*postinstall, false, "", false);
  3053. g.Generate(os, config, configurationTypes);
  3054. }
  3055. }
  3056. }
  3057. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  3058. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3059. std::string::size_type max_len)
  3060. {
  3061. // Replace the beginning of the path portion of the object name with
  3062. // its own md5 sum.
  3063. std::string::size_type pos =
  3064. objName.find('/', objName.size() - max_len + 32);
  3065. if (pos != std::string::npos) {
  3066. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3067. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3068. cm::string_view(objName).substr(pos));
  3069. objName = md5name;
  3070. // The object name is now short enough.
  3071. return true;
  3072. }
  3073. // The object name could not be shortened enough.
  3074. return false;
  3075. }
  3076. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3077. std::string::size_type dir_len,
  3078. std::string::size_type max_total_len)
  3079. {
  3080. // Enforce the maximum file name length if possible.
  3081. std::string::size_type max_obj_len = max_total_len;
  3082. if (dir_len < max_total_len) {
  3083. max_obj_len = max_total_len - dir_len;
  3084. if (objName.size() > max_obj_len) {
  3085. // The current object file name is too long. Try to shorten it.
  3086. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3087. }
  3088. // The object file name is short enough.
  3089. return true;
  3090. }
  3091. // The build directory in which the object will be stored is
  3092. // already too deep.
  3093. return false;
  3094. }
  3095. #endif
  3096. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3097. const std::string& sin, std::string const& dir_max)
  3098. {
  3099. // Look for an existing mapped name for this object file.
  3100. auto it = this->UniqueObjectNamesMap.find(sin);
  3101. // If no entry exists create one.
  3102. if (it == this->UniqueObjectNamesMap.end()) {
  3103. // Start with the original name.
  3104. std::string ssin = sin;
  3105. // Avoid full paths by removing leading slashes.
  3106. ssin.erase(0, ssin.find_first_not_of('/'));
  3107. // Avoid full paths by removing colons.
  3108. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3109. // Avoid relative paths that go up the tree.
  3110. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3111. // Avoid spaces.
  3112. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3113. // Mangle the name if necessary.
  3114. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3115. bool done;
  3116. int cc = 0;
  3117. char rpstr[100];
  3118. sprintf(rpstr, "_p_");
  3119. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3120. std::string sssin = sin;
  3121. do {
  3122. done = true;
  3123. for (it = this->UniqueObjectNamesMap.begin();
  3124. it != this->UniqueObjectNamesMap.end(); ++it) {
  3125. if (it->second == ssin) {
  3126. done = false;
  3127. }
  3128. }
  3129. if (done) {
  3130. break;
  3131. }
  3132. sssin = ssin;
  3133. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3134. sprintf(rpstr, "_p%d_", cc++);
  3135. } while (!done);
  3136. }
  3137. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  3138. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3139. this->ObjectPathMax)) {
  3140. // Warn if this is the first time the path has been seen.
  3141. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3142. std::ostringstream m;
  3143. /* clang-format off */
  3144. m << "The object file directory\n"
  3145. << " " << dir_max << "\n"
  3146. << "has " << dir_max.size() << " characters. "
  3147. << "The maximum full path to an object file is "
  3148. << this->ObjectPathMax << " characters "
  3149. << "(see CMAKE_OBJECT_PATH_MAX). "
  3150. << "Object file\n"
  3151. << " " << ssin << "\n"
  3152. << "cannot be safely placed under this directory. "
  3153. << "The build may not work correctly.";
  3154. /* clang-format on */
  3155. this->IssueMessage(MessageType::WARNING, m.str());
  3156. }
  3157. }
  3158. #else
  3159. (void)dir_max;
  3160. #endif
  3161. // Insert the newly mapped object file name.
  3162. std::map<std::string, std::string>::value_type e(sin, ssin);
  3163. it = this->UniqueObjectNamesMap.insert(e).first;
  3164. }
  3165. // Return the map entry.
  3166. return it->second;
  3167. }
  3168. void cmLocalGenerator::ComputeObjectFilenames(
  3169. std::map<cmSourceFile const*, std::string>& /*unused*/,
  3170. cmGeneratorTarget const* /*unused*/)
  3171. {
  3172. }
  3173. bool cmLocalGenerator::IsWindowsShell() const
  3174. {
  3175. return this->GetState()->UseWindowsShell();
  3176. }
  3177. bool cmLocalGenerator::IsWatcomWMake() const
  3178. {
  3179. return this->GetState()->UseWatcomWMake();
  3180. }
  3181. bool cmLocalGenerator::IsMinGWMake() const
  3182. {
  3183. return this->GetState()->UseMinGWMake();
  3184. }
  3185. bool cmLocalGenerator::IsNMake() const
  3186. {
  3187. return this->GetState()->UseNMake();
  3188. }
  3189. bool cmLocalGenerator::IsNinjaMulti() const
  3190. {
  3191. return this->GetState()->UseNinjaMulti();
  3192. }
  3193. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3194. const cmSourceFile& source, std::string const& dir_max,
  3195. bool* hasSourceExtension, char const* customOutputExtension)
  3196. {
  3197. // Construct the object file name using the full path to the source
  3198. // file which is its only unique identification.
  3199. std::string const& fullPath = source.GetFullPath();
  3200. // Try referencing the source relative to the source tree.
  3201. std::string relFromSource = this->MaybeConvertToRelativePath(
  3202. this->GetCurrentSourceDirectory(), fullPath);
  3203. assert(!relFromSource.empty());
  3204. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3205. bool subSource = relSource && relFromSource[0] != '.';
  3206. // Try referencing the source relative to the binary tree.
  3207. std::string relFromBinary = this->MaybeConvertToRelativePath(
  3208. this->GetCurrentBinaryDirectory(), fullPath);
  3209. assert(!relFromBinary.empty());
  3210. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3211. bool subBinary = relBinary && relFromBinary[0] != '.';
  3212. // Select a nice-looking reference to the source file to construct
  3213. // the object file name.
  3214. std::string objectName;
  3215. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3216. // NOLINTNEXTLINE(bugprone-branch-clone)
  3217. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3218. objectName = relFromSource;
  3219. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3220. relFromBinary.length() < relFromSource.length()) {
  3221. objectName = relFromBinary;
  3222. } else {
  3223. objectName = relFromSource;
  3224. }
  3225. // if it is still a full path check for the try compile case
  3226. // try compile never have in source sources, and should not
  3227. // have conflicting source file names in the same target
  3228. if (cmSystemTools::FileIsFullPath(objectName)) {
  3229. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  3230. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  3231. }
  3232. }
  3233. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  3234. // we don't end up having:
  3235. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  3236. cmProp unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  3237. cmProp psExtension = source.GetProperty("PCH_EXTENSION");
  3238. const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
  3239. if (unitySourceFile || psExtension || isPchObject) {
  3240. if (psExtension) {
  3241. customOutputExtension = psExtension->c_str();
  3242. }
  3243. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  3244. if (var.find(objectName)) {
  3245. objectName.erase(var.start(), var.end() - var.start());
  3246. }
  3247. }
  3248. // Replace the original source file extension with the object file
  3249. // extension.
  3250. bool keptSourceExtension = true;
  3251. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  3252. // Decide whether this language wants to replace the source
  3253. // extension with the object extension. For CMake 2.4
  3254. // compatibility do this by default.
  3255. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  3256. if (!replaceExt) {
  3257. std::string lang = source.GetLanguage();
  3258. if (!lang.empty()) {
  3259. replaceExt = this->Makefile->IsOn(
  3260. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  3261. }
  3262. }
  3263. // Remove the source extension if it is to be replaced.
  3264. if (replaceExt || customOutputExtension) {
  3265. keptSourceExtension = false;
  3266. std::string::size_type dot_pos = objectName.rfind('.');
  3267. if (dot_pos != std::string::npos) {
  3268. objectName = objectName.substr(0, dot_pos);
  3269. }
  3270. }
  3271. // Store the new extension.
  3272. if (customOutputExtension) {
  3273. objectName += customOutputExtension;
  3274. } else {
  3275. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  3276. }
  3277. }
  3278. if (hasSourceExtension) {
  3279. *hasSourceExtension = keptSourceExtension;
  3280. }
  3281. // Convert to a safe name.
  3282. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  3283. }
  3284. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  3285. {
  3286. return source.GetLanguage();
  3287. }
  3288. cmake* cmLocalGenerator::GetCMakeInstance() const
  3289. {
  3290. return this->GlobalGenerator->GetCMakeInstance();
  3291. }
  3292. std::string const& cmLocalGenerator::GetSourceDirectory() const
  3293. {
  3294. return this->GetCMakeInstance()->GetHomeDirectory();
  3295. }
  3296. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  3297. {
  3298. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3299. }
  3300. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  3301. {
  3302. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  3303. }
  3304. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  3305. {
  3306. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  3307. }
  3308. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  3309. std::string const& local_path, std::string const& remote_path) const
  3310. {
  3311. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  3312. local_path, remote_path);
  3313. }
  3314. std::string cmLocalGenerator::GetTargetDirectory(
  3315. const cmGeneratorTarget* /*unused*/) const
  3316. {
  3317. cmSystemTools::Error("GetTargetDirectory"
  3318. " called on cmLocalGenerator");
  3319. return "";
  3320. }
  3321. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3322. {
  3323. // The computed version may change until the project is fully
  3324. // configured.
  3325. if (!this->BackwardsCompatibilityFinal) {
  3326. unsigned int major = 0;
  3327. unsigned int minor = 0;
  3328. unsigned int patch = 0;
  3329. if (const char* value =
  3330. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3331. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  3332. case 2:
  3333. patch = 0;
  3334. break;
  3335. case 1:
  3336. minor = 0;
  3337. patch = 0;
  3338. break;
  3339. default:
  3340. break;
  3341. }
  3342. }
  3343. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3344. this->BackwardsCompatibilityFinal = true;
  3345. }
  3346. return this->BackwardsCompatibility;
  3347. }
  3348. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3349. {
  3350. // Check the policy to decide whether to pay attention to this
  3351. // variable.
  3352. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3353. case cmPolicies::WARN:
  3354. // WARN is just OLD without warning because user code does not
  3355. // always affect whether this check is done.
  3356. case cmPolicies::OLD:
  3357. // Old behavior is to check the variable.
  3358. break;
  3359. case cmPolicies::NEW:
  3360. // New behavior is to ignore the variable.
  3361. case cmPolicies::REQUIRED_IF_USED:
  3362. case cmPolicies::REQUIRED_ALWAYS:
  3363. // This will never be the case because the only way to require
  3364. // the setting is to require the user to specify version policy
  3365. // 2.6 or higher. Once we add that requirement then this whole
  3366. // method can be removed anyway.
  3367. return false;
  3368. }
  3369. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3370. // equal to or lower than the given version.
  3371. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3372. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3373. }
  3374. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3375. cmPolicies::PolicyID id) const
  3376. {
  3377. return this->Makefile->GetPolicyStatus(id);
  3378. }
  3379. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3380. {
  3381. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3382. std::string::size_type pos = define.find_first_of("(=");
  3383. if (pos != std::string::npos) {
  3384. if (define[pos] == '(') {
  3385. std::ostringstream e;
  3386. /* clang-format off */
  3387. e << "WARNING: Function-style preprocessor definitions may not be "
  3388. << "passed on the compiler command line because many compilers "
  3389. << "do not support it.\n"
  3390. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3391. << "Consider defining the macro in a (configured) header file.\n";
  3392. /* clang-format on */
  3393. cmSystemTools::Message(e.str());
  3394. return false;
  3395. }
  3396. }
  3397. // Many compilers do not support # in the value so we disable it.
  3398. if (define.find_first_of('#') != std::string::npos) {
  3399. std::ostringstream e;
  3400. /* clang-format off */
  3401. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3402. << "passed on the compiler command line because many compilers "
  3403. << "do not support it.\n"
  3404. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3405. << "Consider defining the macro in a (configured) header file.\n";
  3406. /* clang-format on */
  3407. cmSystemTools::Message(e.str());
  3408. return false;
  3409. }
  3410. // Assume it is supported.
  3411. return true;
  3412. }
  3413. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3414. const std::string& prop)
  3415. {
  3416. if (cmProp val = target->GetProperty(prop)) {
  3417. mf->AddDefinition(prop, *val);
  3418. }
  3419. }
  3420. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3421. const std::string& targetName,
  3422. const std::string& fname)
  3423. {
  3424. // Find the Info.plist template.
  3425. cmProp in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3426. std::string inFile =
  3427. (in && !in->empty()) ? *in : "MacOSXBundleInfo.plist.in";
  3428. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3429. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3430. if (!inMod.empty()) {
  3431. inFile = inMod;
  3432. }
  3433. }
  3434. if (!cmSystemTools::FileExists(inFile, true)) {
  3435. std::ostringstream e;
  3436. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3437. << "\" could not be found.";
  3438. cmSystemTools::Error(e.str());
  3439. return;
  3440. }
  3441. // Convert target properties to variables in an isolated makefile
  3442. // scope to configure the file. If properties are set they will
  3443. // override user make variables. If not the configuration will fall
  3444. // back to the directory-level values set by the user.
  3445. cmMakefile* mf = this->Makefile;
  3446. cmMakefile::ScopePushPop varScope(mf);
  3447. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3448. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3449. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3450. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3451. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3452. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3453. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3454. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3455. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3456. mf->ConfigureFile(inFile, fname, false, false, false);
  3457. }
  3458. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3459. cmGeneratorTarget* target, const std::string& targetName,
  3460. const std::string& fname)
  3461. {
  3462. // Find the Info.plist template.
  3463. cmProp in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3464. std::string inFile =
  3465. (in && !in->empty()) ? *in : "MacOSXFrameworkInfo.plist.in";
  3466. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3467. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3468. if (!inMod.empty()) {
  3469. inFile = inMod;
  3470. }
  3471. }
  3472. if (!cmSystemTools::FileExists(inFile, true)) {
  3473. std::ostringstream e;
  3474. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3475. << "\" could not be found.";
  3476. cmSystemTools::Error(e.str());
  3477. return;
  3478. }
  3479. // Convert target properties to variables in an isolated makefile
  3480. // scope to configure the file. If properties are set they will
  3481. // override user make variables. If not the configuration will fall
  3482. // back to the directory-level values set by the user.
  3483. cmMakefile* mf = this->Makefile;
  3484. cmMakefile::ScopePushPop varScope(mf);
  3485. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3486. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3487. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3488. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3489. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3490. mf->ConfigureFile(inFile, fname, false, false, false);
  3491. }
  3492. namespace {
  3493. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3494. cmCommandOrigin origin,
  3495. const cmListFileBacktrace& lfbt)
  3496. {
  3497. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3498. // Outputs without generator expressions from the project are already
  3499. // created and marked as generated. Do not mark them again, because
  3500. // other commands might have overwritten the property.
  3501. if (origin == cmCommandOrigin::Generator) {
  3502. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3503. }
  3504. } else {
  3505. lg.GetCMakeInstance()->IssueMessage(
  3506. MessageType::FATAL_ERROR,
  3507. "Generator expressions in custom command outputs are not implemented!",
  3508. lfbt);
  3509. }
  3510. }
  3511. void CreateGeneratedSources(cmLocalGenerator& lg,
  3512. const std::vector<std::string>& outputs,
  3513. cmCommandOrigin origin,
  3514. const cmListFileBacktrace& lfbt)
  3515. {
  3516. for (std::string const& o : outputs) {
  3517. CreateGeneratedSource(lg, o, origin, lfbt);
  3518. }
  3519. }
  3520. cmSourceFile* AddCustomCommand(
  3521. cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  3522. const std::vector<std::string>& outputs,
  3523. const std::vector<std::string>& byproducts,
  3524. const std::vector<std::string>& depends, const std::string& main_dependency,
  3525. const cmImplicitDependsList& implicit_depends,
  3526. const cmCustomCommandLines& commandLines, const char* comment,
  3527. const char* workingDir, bool replace, bool escapeOldStyle,
  3528. bool uses_terminal, bool command_expand_lists, const std::string& depfile,
  3529. const std::string& job_pool, bool stdPipesUTF8)
  3530. {
  3531. cmMakefile* mf = lg.GetMakefile();
  3532. // Choose a source file on which to store the custom command.
  3533. cmSourceFile* file = nullptr;
  3534. if (!commandLines.empty() && !main_dependency.empty()) {
  3535. // The main dependency was specified. Use it unless a different
  3536. // custom command already used it.
  3537. file = mf->GetSource(main_dependency);
  3538. if (file && file->GetCustomCommand() && !replace) {
  3539. // The main dependency already has a custom command.
  3540. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  3541. // The existing custom command is identical. Silently ignore
  3542. // the duplicate.
  3543. return file;
  3544. }
  3545. // The existing custom command is different. We need to
  3546. // generate a rule file for this new command.
  3547. file = nullptr;
  3548. } else if (!file) {
  3549. file = mf->CreateSource(main_dependency);
  3550. }
  3551. }
  3552. // Generate a rule file if the main dependency is not available.
  3553. if (!file) {
  3554. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  3555. // Construct a rule file associated with the first output produced.
  3556. std::string outName = gg->GenerateRuleFile(outputs[0]);
  3557. // Check if the rule file already exists.
  3558. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  3559. if (file && file->GetCustomCommand() && !replace) {
  3560. // The rule file already exists.
  3561. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  3562. lg.GetCMakeInstance()->IssueMessage(
  3563. MessageType::FATAL_ERROR,
  3564. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  3565. "\nwhich already has a custom rule."),
  3566. lfbt);
  3567. }
  3568. return file;
  3569. }
  3570. // Create a cmSourceFile for the rule file.
  3571. if (!file) {
  3572. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  3573. }
  3574. file->SetProperty("__CMAKE_RULE", "1");
  3575. }
  3576. // Attach the custom command to the file.
  3577. if (file) {
  3578. // Construct a complete list of dependencies.
  3579. std::vector<std::string> depends2(depends);
  3580. if (!main_dependency.empty()) {
  3581. depends2.push_back(main_dependency);
  3582. }
  3583. std::unique_ptr<cmCustomCommand> cc = cm::make_unique<cmCustomCommand>(
  3584. outputs, byproducts, depends2, commandLines, lfbt, comment, workingDir,
  3585. stdPipesUTF8);
  3586. cc->SetEscapeOldStyle(escapeOldStyle);
  3587. cc->SetEscapeAllowMakeVars(true);
  3588. cc->SetImplicitDepends(implicit_depends);
  3589. cc->SetUsesTerminal(uses_terminal);
  3590. cc->SetCommandExpandLists(command_expand_lists);
  3591. cc->SetDepfile(depfile);
  3592. cc->SetJobPool(job_pool);
  3593. file->SetCustomCommand(std::move(cc));
  3594. mf->AddSourceOutputs(file, outputs, byproducts);
  3595. }
  3596. return file;
  3597. }
  3598. }
  3599. namespace detail {
  3600. void AddCustomCommandToTarget(cmLocalGenerator& lg,
  3601. const cmListFileBacktrace& lfbt,
  3602. cmCommandOrigin origin, cmTarget* target,
  3603. const std::vector<std::string>& byproducts,
  3604. const std::vector<std::string>& depends,
  3605. const cmCustomCommandLines& commandLines,
  3606. cmCustomCommandType type, const char* comment,
  3607. const char* workingDir, bool escapeOldStyle,
  3608. bool uses_terminal, const std::string& depfile,
  3609. const std::string& job_pool,
  3610. bool command_expand_lists, bool stdPipesUTF8)
  3611. {
  3612. cmMakefile* mf = lg.GetMakefile();
  3613. // Always create the byproduct sources and mark them generated.
  3614. CreateGeneratedSources(lg, byproducts, origin, lfbt);
  3615. // Add the command to the appropriate build step for the target.
  3616. std::vector<std::string> no_output;
  3617. cmCustomCommand cc(no_output, byproducts, depends, commandLines, lfbt,
  3618. comment, workingDir, stdPipesUTF8);
  3619. cc.SetEscapeOldStyle(escapeOldStyle);
  3620. cc.SetEscapeAllowMakeVars(true);
  3621. cc.SetUsesTerminal(uses_terminal);
  3622. cc.SetCommandExpandLists(command_expand_lists);
  3623. cc.SetDepfile(depfile);
  3624. cc.SetJobPool(job_pool);
  3625. switch (type) {
  3626. case cmCustomCommandType::PRE_BUILD:
  3627. target->AddPreBuildCommand(std::move(cc));
  3628. break;
  3629. case cmCustomCommandType::PRE_LINK:
  3630. target->AddPreLinkCommand(std::move(cc));
  3631. break;
  3632. case cmCustomCommandType::POST_BUILD:
  3633. target->AddPostBuildCommand(std::move(cc));
  3634. break;
  3635. }
  3636. mf->AddTargetByproducts(target, byproducts);
  3637. }
  3638. cmSourceFile* AddCustomCommandToOutput(
  3639. cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  3640. cmCommandOrigin origin, const std::vector<std::string>& outputs,
  3641. const std::vector<std::string>& byproducts,
  3642. const std::vector<std::string>& depends, const std::string& main_dependency,
  3643. const cmImplicitDependsList& implicit_depends,
  3644. const cmCustomCommandLines& commandLines, const char* comment,
  3645. const char* workingDir, bool replace, bool escapeOldStyle,
  3646. bool uses_terminal, bool command_expand_lists, const std::string& depfile,
  3647. const std::string& job_pool, bool stdPipesUTF8)
  3648. {
  3649. // Always create the output sources and mark them generated.
  3650. CreateGeneratedSources(lg, outputs, origin, lfbt);
  3651. CreateGeneratedSources(lg, byproducts, origin, lfbt);
  3652. return AddCustomCommand(
  3653. lg, lfbt, outputs, byproducts, depends, main_dependency, implicit_depends,
  3654. commandLines, comment, workingDir, replace, escapeOldStyle, uses_terminal,
  3655. command_expand_lists, depfile, job_pool, stdPipesUTF8);
  3656. }
  3657. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  3658. const cmListFileBacktrace& lfbt,
  3659. const std::string& output,
  3660. const std::vector<std::string>& depends,
  3661. const cmImplicitDependsList& implicit_depends,
  3662. const cmCustomCommandLines& commandLines)
  3663. {
  3664. // Lookup an existing command.
  3665. if (cmSourceFile* sf = lg.GetMakefile()->GetSourceFileWithOutput(output)) {
  3666. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  3667. cc->AppendCommands(commandLines);
  3668. cc->AppendDepends(depends);
  3669. cc->AppendImplicitDepends(implicit_depends);
  3670. return;
  3671. }
  3672. }
  3673. // No existing command found.
  3674. lg.GetCMakeInstance()->IssueMessage(
  3675. MessageType::FATAL_ERROR,
  3676. cmStrCat("Attempt to append to output\n ", output,
  3677. "\nwhich is not already a custom command output."),
  3678. lfbt);
  3679. }
  3680. void AddUtilityCommand(cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  3681. cmCommandOrigin origin, cmTarget* target,
  3682. const cmUtilityOutput& force, const char* workingDir,
  3683. const std::vector<std::string>& byproducts,
  3684. const std::vector<std::string>& depends,
  3685. const cmCustomCommandLines& commandLines,
  3686. bool escapeOldStyle, const char* comment,
  3687. bool uses_terminal, bool command_expand_lists,
  3688. const std::string& job_pool, bool stdPipesUTF8)
  3689. {
  3690. // Always create the byproduct sources and mark them generated.
  3691. CreateGeneratedSource(lg, force.Name, origin, lfbt);
  3692. CreateGeneratedSources(lg, byproducts, origin, lfbt);
  3693. // Use an empty comment to avoid generation of default comment.
  3694. if (!comment) {
  3695. comment = "";
  3696. }
  3697. std::string no_main_dependency;
  3698. cmImplicitDependsList no_implicit_depends;
  3699. cmSourceFile* rule = AddCustomCommand(
  3700. lg, lfbt, { force.Name }, byproducts, depends, no_main_dependency,
  3701. no_implicit_depends, commandLines, comment, workingDir,
  3702. /*replace=*/false, escapeOldStyle, uses_terminal, command_expand_lists,
  3703. /*depfile=*/"", job_pool, stdPipesUTF8);
  3704. if (rule) {
  3705. lg.GetMakefile()->AddTargetByproducts(target, byproducts);
  3706. }
  3707. if (!force.NameCMP0049.empty()) {
  3708. target->AddSource(force.NameCMP0049);
  3709. }
  3710. }
  3711. }