cmLocalGenerator.cxx 170 KB

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