cmLocalGenerator.cxx 158 KB

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