cmLocalGenerator.cxx 164 KB

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