cmLocalGenerator.cxx 160 KB

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