cmLocalGenerator.cxx 164 KB

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