cmLocalGenerator.cxx 160 KB

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