cmLocalGenerator.cxx 158 KB

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