cmLocalGenerator.cxx 178 KB

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