cmLocalGenerator.cxx 149 KB

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