cmLocalGenerator.cxx 144 KB

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