cmLocalGenerator.cxx 165 KB

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