cmLocalGenerator.cxx 184 KB

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