cmLocalGenerator.cxx 167 KB

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