cmLocalGenerator.cxx 180 KB

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