cmLocalGenerator.cxx 175 KB

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