cmMakefile.cxx 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855
  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 "cmConfigure.h" // IWYU pragma: keep
  4. #include "cmMakefile.h"
  5. #include <algorithm>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <sstream>
  12. #include <utility>
  13. #include <cm/iterator>
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/type_traits> // IWYU pragma: keep
  17. #include <cm/vector>
  18. #include <cmext/algorithm>
  19. #include <cmext/string_view>
  20. #ifndef CMAKE_BOOTSTRAP
  21. # include <cm3p/json/value.h>
  22. # include <cm3p/json/writer.h>
  23. #endif
  24. #include "cmsys/FStream.hxx"
  25. #include "cmsys/RegularExpression.hxx"
  26. #include "cmCommandArgumentParserHelper.h"
  27. #include "cmCustomCommand.h"
  28. #include "cmCustomCommandLines.h"
  29. #include "cmCustomCommandTypes.h"
  30. #include "cmExecutionStatus.h"
  31. #include "cmExpandedCommandArgument.h" // IWYU pragma: keep
  32. #include "cmExportBuildFileGenerator.h"
  33. #include "cmFileLockPool.h"
  34. #include "cmFunctionBlocker.h"
  35. #include "cmGeneratedFileStream.h"
  36. #include "cmGeneratorExpression.h"
  37. #include "cmGeneratorExpressionEvaluationFile.h"
  38. #include "cmGlobalGenerator.h"
  39. #include "cmInstallGenerator.h" // IWYU pragma: keep
  40. #include "cmInstallSubdirectoryGenerator.h"
  41. #include "cmList.h"
  42. #include "cmListFileCache.h"
  43. #include "cmLocalGenerator.h"
  44. #include "cmMessageType.h"
  45. #include "cmRange.h"
  46. #include "cmSourceFile.h"
  47. #include "cmSourceFileLocation.h"
  48. #include "cmState.h"
  49. #include "cmStateDirectory.h"
  50. #include "cmStateTypes.h"
  51. #include "cmStringAlgorithms.h"
  52. #include "cmSystemTools.h"
  53. #include "cmTarget.h"
  54. #include "cmTargetLinkLibraryType.h"
  55. #include "cmTest.h"
  56. #include "cmTestGenerator.h" // IWYU pragma: keep
  57. #include "cmVersion.h"
  58. #include "cmWorkingDirectory.h"
  59. #include "cmake.h"
  60. #ifndef CMAKE_BOOTSTRAP
  61. # include "cmMakefileProfilingData.h"
  62. # include "cmVariableWatch.h"
  63. #endif
  64. #ifdef CMake_ENABLE_DEBUGGER
  65. # include "cmDebuggerAdapter.h"
  66. #endif
  67. #ifndef __has_feature
  68. # define __has_feature(x) 0
  69. #endif
  70. // Select a recursion limit that fits within the stack size.
  71. // See stack size flags in '../CompileFlags.cmake'.
  72. #ifndef CMake_DEFAULT_RECURSION_LIMIT
  73. # if __has_feature(address_sanitizer)
  74. # define CMake_DEFAULT_RECURSION_LIMIT 400
  75. # elif defined(_MSC_VER) && defined(_DEBUG)
  76. # define CMake_DEFAULT_RECURSION_LIMIT 600
  77. # elif defined(__ibmxl__) && defined(__linux)
  78. # define CMake_DEFAULT_RECURSION_LIMIT 600
  79. # else
  80. # define CMake_DEFAULT_RECURSION_LIMIT 1000
  81. # endif
  82. #endif
  83. class cmMessenger;
  84. cmDirectoryId::cmDirectoryId(std::string s)
  85. : String(std::move(s))
  86. {
  87. }
  88. // default is not to be building executables
  89. cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
  90. cmStateSnapshot const& snapshot)
  91. : GlobalGenerator(globalGenerator)
  92. , StateSnapshot(snapshot)
  93. {
  94. this->IsSourceFileTryCompile = false;
  95. this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
  96. this->SuppressSideEffects = false;
  97. // Setup the default include complaint regular expression (match nothing).
  98. this->ComplainFileRegularExpression = "^$";
  99. this->DefineFlags = " ";
  100. this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
  101. this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  102. this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
  103. this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
  104. this->StateSnapshot =
  105. this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  106. this->StateSnapshot);
  107. // Enter a policy level for this directory.
  108. this->PushPolicy();
  109. // push empty loop block
  110. this->PushLoopBlockBarrier();
  111. // By default the check is not done. It is enabled by
  112. // cmListFileCache in the top level if necessary.
  113. this->CheckCMP0000 = false;
  114. #if !defined(CMAKE_BOOTSTRAP)
  115. this->AddSourceGroup("", "^.*$");
  116. this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
  117. this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  118. this->AddSourceGroup("Precompile Header File", CM_PCH_REGEX);
  119. this->AddSourceGroup("CMake Rules", "\\.rule$");
  120. this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
  121. this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
  122. this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
  123. this->SourceGroups.emplace_back("Object Libraries", "^MATCH_NO_SOURCES$");
  124. #endif
  125. }
  126. cmMakefile::~cmMakefile() = default;
  127. cmDirectoryId cmMakefile::GetDirectoryId() const
  128. {
  129. // Use the instance pointer value to uniquely identify this directory.
  130. // If we ever need to expose this to CMake language code we should
  131. // add a read-only property in cmMakefile::GetProperty.
  132. char buf[32];
  133. snprintf(buf, sizeof(buf), "(%p)",
  134. static_cast<void const*>(this)); // cast avoids format warning
  135. return std::string(buf);
  136. }
  137. void cmMakefile::IssueMessage(MessageType t, std::string const& text) const
  138. {
  139. if (!this->ExecutionStatusStack.empty()) {
  140. if ((t == MessageType::FATAL_ERROR) ||
  141. (t == MessageType::INTERNAL_ERROR)) {
  142. this->ExecutionStatusStack.back()->SetNestedError();
  143. }
  144. }
  145. this->GetCMakeInstance()->IssueMessage(t, text, this->Backtrace);
  146. }
  147. Message::LogLevel cmMakefile::GetCurrentLogLevel() const
  148. {
  149. const cmake* cmakeInstance = this->GetCMakeInstance();
  150. const Message::LogLevel logLevelCliOrDefault = cmakeInstance->GetLogLevel();
  151. assert("Expected a valid log level here" &&
  152. logLevelCliOrDefault != Message::LogLevel::LOG_UNDEFINED);
  153. Message::LogLevel result = logLevelCliOrDefault;
  154. // If the log-level was set via the command line option, it takes precedence
  155. // over the CMAKE_MESSAGE_LOG_LEVEL variable.
  156. if (!cmakeInstance->WasLogLevelSetViaCLI()) {
  157. const Message::LogLevel logLevelFromVar = cmake::StringToLogLevel(
  158. this->GetSafeDefinition("CMAKE_MESSAGE_LOG_LEVEL"));
  159. if (logLevelFromVar != Message::LogLevel::LOG_UNDEFINED) {
  160. result = logLevelFromVar;
  161. }
  162. }
  163. return result;
  164. }
  165. bool cmMakefile::CheckCMP0037(std::string const& targetName,
  166. cmStateEnums::TargetType targetType) const
  167. {
  168. MessageType messageType = MessageType::AUTHOR_WARNING;
  169. std::ostringstream e;
  170. bool issueMessage = false;
  171. switch (this->GetPolicyStatus(cmPolicies::CMP0037)) {
  172. case cmPolicies::WARN:
  173. if (targetType != cmStateEnums::INTERFACE_LIBRARY) {
  174. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  175. issueMessage = true;
  176. }
  177. CM_FALLTHROUGH;
  178. case cmPolicies::OLD:
  179. break;
  180. case cmPolicies::NEW:
  181. case cmPolicies::REQUIRED_IF_USED:
  182. case cmPolicies::REQUIRED_ALWAYS:
  183. issueMessage = true;
  184. messageType = MessageType::FATAL_ERROR;
  185. break;
  186. }
  187. if (issueMessage) {
  188. e << "The target name \"" << targetName
  189. << "\" is reserved or not valid for certain "
  190. "CMake features, such as generator expressions, and may result "
  191. "in undefined behavior.";
  192. this->IssueMessage(messageType, e.str());
  193. if (messageType == MessageType::FATAL_ERROR) {
  194. return false;
  195. }
  196. }
  197. return true;
  198. }
  199. void cmMakefile::MaybeWarnCMP0074(std::string const& rootVar, cmValue rootDef,
  200. cm::optional<std::string> const& rootEnv)
  201. {
  202. // Warn if a <PackageName>_ROOT variable we may use is set.
  203. if ((rootDef || rootEnv) && this->WarnedCMP0074.insert(rootVar).second) {
  204. std::ostringstream w;
  205. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0074) << "\n";
  206. if (rootDef) {
  207. w << "CMake variable " << rootVar << " is set to:\n"
  208. << " " << *rootDef << "\n";
  209. }
  210. if (rootEnv) {
  211. w << "Environment variable " << rootVar << " is set to:\n"
  212. << " " << *rootEnv << "\n";
  213. }
  214. w << "For compatibility, CMake is ignoring the variable.";
  215. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  216. }
  217. }
  218. void cmMakefile::MaybeWarnCMP0144(std::string const& rootVAR, cmValue rootDEF,
  219. cm::optional<std::string> const& rootENV)
  220. {
  221. // Warn if a <PACKAGENAME>_ROOT variable we may use is set.
  222. if ((rootDEF || rootENV) && this->WarnedCMP0144.insert(rootVAR).second) {
  223. std::ostringstream w;
  224. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0144) << "\n";
  225. if (rootDEF) {
  226. w << "CMake variable " << rootVAR << " is set to:\n"
  227. << " " << *rootDEF << "\n";
  228. }
  229. if (rootENV) {
  230. w << "Environment variable " << rootVAR << " is set to:\n"
  231. << " " << *rootENV << "\n";
  232. }
  233. w << "For compatibility, find_package is ignoring the variable, but "
  234. "code in a .cmake module might still use it.";
  235. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  236. }
  237. }
  238. cmBTStringRange cmMakefile::GetIncludeDirectoriesEntries() const
  239. {
  240. return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
  241. }
  242. cmBTStringRange cmMakefile::GetCompileOptionsEntries() const
  243. {
  244. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
  245. }
  246. cmBTStringRange cmMakefile::GetCompileDefinitionsEntries() const
  247. {
  248. return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
  249. }
  250. cmBTStringRange cmMakefile::GetLinkOptionsEntries() const
  251. {
  252. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
  253. }
  254. cmBTStringRange cmMakefile::GetLinkDirectoriesEntries() const
  255. {
  256. return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
  257. }
  258. cmListFileBacktrace cmMakefile::GetBacktrace() const
  259. {
  260. return this->Backtrace;
  261. }
  262. cmFindPackageStack cmMakefile::GetFindPackageStack() const
  263. {
  264. return this->FindPackageStack;
  265. }
  266. void cmMakefile::PrintCommandTrace(cmListFileFunction const& lff,
  267. cmListFileBacktrace const& bt,
  268. CommandMissingFromStack missing) const
  269. {
  270. // Check if current file in the list of requested to trace...
  271. std::vector<std::string> const& trace_only_this_files =
  272. this->GetCMakeInstance()->GetTraceSources();
  273. std::string const& full_path = bt.Top().FilePath;
  274. std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
  275. bool trace = trace_only_this_files.empty();
  276. if (!trace) {
  277. for (std::string const& file : trace_only_this_files) {
  278. std::string::size_type const pos = full_path.rfind(file);
  279. trace = (pos != std::string::npos) &&
  280. ((pos + file.size()) == full_path.size()) &&
  281. (only_filename == cmSystemTools::GetFilenameName(file));
  282. if (trace) {
  283. break;
  284. }
  285. }
  286. // Do nothing if current file wasn't requested for trace...
  287. if (!trace) {
  288. return;
  289. }
  290. }
  291. std::ostringstream msg;
  292. std::vector<std::string> args;
  293. std::string temp;
  294. bool expand = this->GetCMakeInstance()->GetTraceExpand();
  295. args.reserve(lff.Arguments().size());
  296. for (cmListFileArgument const& arg : lff.Arguments()) {
  297. if (expand && arg.Delim != cmListFileArgument::Bracket) {
  298. temp = arg.Value;
  299. this->ExpandVariablesInString(temp);
  300. args.push_back(temp);
  301. } else {
  302. args.push_back(arg.Value);
  303. }
  304. }
  305. cm::optional<std::string> const& deferId = bt.Top().DeferId;
  306. switch (this->GetCMakeInstance()->GetTraceFormat()) {
  307. case cmake::TraceFormat::JSONv1: {
  308. #ifndef CMAKE_BOOTSTRAP
  309. Json::Value val;
  310. Json::StreamWriterBuilder builder;
  311. builder["indentation"] = "";
  312. val["file"] = full_path;
  313. val["line"] = static_cast<Json::Value::Int64>(lff.Line());
  314. if (lff.Line() != lff.LineEnd()) {
  315. val["line_end"] = static_cast<Json::Value::Int64>(lff.LineEnd());
  316. }
  317. if (deferId) {
  318. val["defer"] = *deferId;
  319. }
  320. val["cmd"] = lff.OriginalName();
  321. val["args"] = Json::Value(Json::arrayValue);
  322. for (std::string const& arg : args) {
  323. val["args"].append(arg);
  324. }
  325. val["time"] = cmSystemTools::GetTime();
  326. val["frame"] = int(missing == CommandMissingFromStack::Yes) +
  327. static_cast<Json::Value::UInt64>(this->ExecutionStatusStack.size());
  328. val["global_frame"] = int(missing == CommandMissingFromStack::Yes) +
  329. static_cast<Json::Value::UInt64>(this->RecursionDepth);
  330. msg << Json::writeString(builder, val);
  331. #endif
  332. break;
  333. }
  334. case cmake::TraceFormat::Human:
  335. msg << full_path << "(" << lff.Line() << "):";
  336. if (deferId) {
  337. msg << "DEFERRED:" << *deferId << ":";
  338. }
  339. msg << " " << lff.OriginalName() << "(";
  340. for (std::string const& arg : args) {
  341. msg << arg << " ";
  342. }
  343. msg << ")";
  344. break;
  345. case cmake::TraceFormat::Undefined:
  346. msg << "INTERNAL ERROR: Trace format is Undefined";
  347. break;
  348. }
  349. auto& f = this->GetCMakeInstance()->GetTraceFile();
  350. if (f) {
  351. f << msg.str() << '\n';
  352. } else {
  353. cmSystemTools::Message(msg.str());
  354. }
  355. }
  356. // Helper class to make sure the call stack is valid.
  357. class cmMakefileCall
  358. {
  359. public:
  360. cmMakefileCall(cmMakefile* mf, cmListFileFunction const& lff,
  361. cm::optional<std::string> deferId, cmExecutionStatus& status)
  362. : Makefile(mf)
  363. {
  364. cmListFileContext const& lfc = cmListFileContext::FromListFileFunction(
  365. lff, this->Makefile->StateSnapshot.GetExecutionListFile(),
  366. std::move(deferId));
  367. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  368. ++this->Makefile->RecursionDepth;
  369. this->Makefile->ExecutionStatusStack.push_back(&status);
  370. #if !defined(CMAKE_BOOTSTRAP)
  371. this->ProfilingDataRAII =
  372. this->Makefile->GetCMakeInstance()->CreateProfilingEntry(
  373. "script", lff.LowerCaseName(), [&lff, &lfc]() -> Json::Value {
  374. Json::Value argsValue = Json::objectValue;
  375. if (!lff.Arguments().empty()) {
  376. std::string args;
  377. for (auto const& a : lff.Arguments()) {
  378. args = cmStrCat(args, args.empty() ? "" : " ", a.Value);
  379. }
  380. argsValue["functionArgs"] = args;
  381. }
  382. argsValue["location"] =
  383. cmStrCat(lfc.FilePath, ':', std::to_string(lfc.Line));
  384. return argsValue;
  385. });
  386. #endif
  387. #ifdef CMake_ENABLE_DEBUGGER
  388. if (this->Makefile->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  389. this->Makefile->GetCMakeInstance()
  390. ->GetDebugAdapter()
  391. ->OnBeginFunctionCall(mf, lfc.FilePath, lff);
  392. }
  393. #endif
  394. }
  395. ~cmMakefileCall()
  396. {
  397. #if !defined(CMAKE_BOOTSTRAP)
  398. this->ProfilingDataRAII.reset();
  399. #endif
  400. this->Makefile->ExecutionStatusStack.pop_back();
  401. --this->Makefile->RecursionDepth;
  402. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  403. #ifdef CMake_ENABLE_DEBUGGER
  404. if (this->Makefile->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  405. this->Makefile->GetCMakeInstance()
  406. ->GetDebugAdapter()
  407. ->OnEndFunctionCall();
  408. }
  409. #endif
  410. }
  411. cmMakefileCall(const cmMakefileCall&) = delete;
  412. cmMakefileCall& operator=(const cmMakefileCall&) = delete;
  413. private:
  414. cmMakefile* Makefile;
  415. #if !defined(CMAKE_BOOTSTRAP)
  416. cm::optional<cmMakefileProfilingData::RAII> ProfilingDataRAII;
  417. #endif
  418. };
  419. void cmMakefile::OnExecuteCommand(std::function<void()> callback)
  420. {
  421. this->ExecuteCommandCallback = std::move(callback);
  422. }
  423. bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
  424. cmExecutionStatus& status,
  425. cm::optional<std::string> deferId)
  426. {
  427. bool result = true;
  428. // quick return if blocked
  429. if (this->IsFunctionBlocked(lff, status)) {
  430. // No error.
  431. return result;
  432. }
  433. if (this->ExecuteCommandCallback) {
  434. this->ExecuteCommandCallback();
  435. }
  436. // Place this call on the call stack.
  437. cmMakefileCall stack_manager(this, lff, std::move(deferId), status);
  438. static_cast<void>(stack_manager);
  439. // Check for maximum recursion depth.
  440. size_t depthLimit = this->GetRecursionDepthLimit();
  441. if (this->RecursionDepth > depthLimit) {
  442. std::ostringstream e;
  443. e << "Maximum recursion depth of " << depthLimit << " exceeded";
  444. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  445. cmSystemTools::SetFatalErrorOccurred();
  446. return false;
  447. }
  448. // Lookup the command prototype.
  449. if (cmState::Command command =
  450. this->GetState()->GetCommandByExactName(lff.LowerCaseName())) {
  451. // Decide whether to invoke the command.
  452. if (!cmSystemTools::GetFatalErrorOccurred()) {
  453. // if trace is enabled, print out invoke information
  454. if (this->GetCMakeInstance()->GetTrace()) {
  455. this->PrintCommandTrace(lff, this->Backtrace);
  456. }
  457. // Try invoking the command.
  458. bool invokeSucceeded = command(lff.Arguments(), status);
  459. bool hadNestedError = status.GetNestedError();
  460. if (!invokeSucceeded || hadNestedError) {
  461. if (!hadNestedError) {
  462. // The command invocation requested that we report an error.
  463. std::string const error =
  464. cmStrCat(lff.OriginalName(), ' ', status.GetError());
  465. this->IssueMessage(MessageType::FATAL_ERROR, error);
  466. }
  467. result = false;
  468. if (this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE) {
  469. cmSystemTools::SetFatalErrorOccurred();
  470. }
  471. }
  472. if (this->GetCMakeInstance()->HasScriptModeExitCode() &&
  473. this->GetCMakeInstance()->GetWorkingMode() == cmake::SCRIPT_MODE) {
  474. // pass-through the exit code from inner cmake_language(EXIT) ,
  475. // possibly from include() or similar command...
  476. status.SetExitCode(this->GetCMakeInstance()->GetScriptModeExitCode());
  477. }
  478. }
  479. } else {
  480. if (!cmSystemTools::GetFatalErrorOccurred()) {
  481. std::string error =
  482. cmStrCat("Unknown CMake command \"", lff.OriginalName(), "\".");
  483. this->IssueMessage(MessageType::FATAL_ERROR, error);
  484. result = false;
  485. cmSystemTools::SetFatalErrorOccurred();
  486. }
  487. }
  488. return result;
  489. }
  490. bool cmMakefile::IsImportedTargetGlobalScope() const
  491. {
  492. return this->CurrentImportedTargetScope == ImportedTargetScope::Global;
  493. }
  494. class cmMakefile::IncludeScope
  495. {
  496. public:
  497. IncludeScope(cmMakefile* mf, std::string const& filenametoread,
  498. bool noPolicyScope);
  499. ~IncludeScope();
  500. void Quiet() { this->ReportError = false; }
  501. IncludeScope(const IncludeScope&) = delete;
  502. IncludeScope& operator=(const IncludeScope&) = delete;
  503. private:
  504. cmMakefile* Makefile;
  505. bool NoPolicyScope;
  506. bool CheckCMP0011 = false;
  507. bool ReportError = true;
  508. void EnforceCMP0011();
  509. };
  510. cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
  511. std::string const& filenametoread,
  512. bool noPolicyScope)
  513. : Makefile(mf)
  514. , NoPolicyScope(noPolicyScope)
  515. {
  516. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
  517. cmListFileContext::FromListFilePath(filenametoread));
  518. this->Makefile->PushFunctionBlockerBarrier();
  519. this->Makefile->StateSnapshot =
  520. this->Makefile->GetState()->CreateIncludeFileSnapshot(
  521. this->Makefile->StateSnapshot, filenametoread);
  522. if (!this->NoPolicyScope) {
  523. // Check CMP0011 to determine the policy scope type.
  524. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  525. case cmPolicies::WARN:
  526. // We need to push a scope to detect whether the script sets
  527. // any policies that would affect the includer and therefore
  528. // requires a warning. We use a weak scope to simulate OLD
  529. // behavior by allowing policy changes to affect the includer.
  530. this->Makefile->PushPolicy(true);
  531. this->CheckCMP0011 = true;
  532. break;
  533. case cmPolicies::OLD:
  534. // OLD behavior is to not push a scope at all.
  535. this->NoPolicyScope = true;
  536. break;
  537. case cmPolicies::REQUIRED_IF_USED:
  538. case cmPolicies::REQUIRED_ALWAYS:
  539. // We should never make this policy required, but we handle it
  540. // here just in case.
  541. this->CheckCMP0011 = true;
  542. CM_FALLTHROUGH;
  543. case cmPolicies::NEW:
  544. // NEW behavior is to push a (strong) scope.
  545. this->Makefile->PushPolicy();
  546. break;
  547. }
  548. }
  549. }
  550. cmMakefile::IncludeScope::~IncludeScope()
  551. {
  552. if (!this->NoPolicyScope) {
  553. // If we need to enforce policy CMP0011 then the top entry is the
  554. // one we pushed above. If the entry is empty, then the included
  555. // script did not set any policies that might affect the includer so
  556. // we do not need to enforce the policy.
  557. if (this->CheckCMP0011 &&
  558. !this->Makefile->StateSnapshot.HasDefinedPolicyCMP0011()) {
  559. this->CheckCMP0011 = false;
  560. }
  561. // Pop the scope we pushed for the script.
  562. this->Makefile->PopPolicy();
  563. // We enforce the policy after the script's policy stack entry has
  564. // been removed.
  565. if (this->CheckCMP0011) {
  566. this->EnforceCMP0011();
  567. }
  568. }
  569. this->Makefile->PopSnapshot(this->ReportError);
  570. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  571. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  572. }
  573. void cmMakefile::IncludeScope::EnforceCMP0011()
  574. {
  575. // We check the setting of this policy again because the included
  576. // script might actually set this policy for its includer.
  577. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  578. case cmPolicies::WARN:
  579. // Warn because the user did not set this policy.
  580. {
  581. std::ostringstream w;
  582. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
  583. << "The included script\n "
  584. << this->Makefile->GetBacktrace().Top().FilePath << "\n"
  585. << "affects policy settings. "
  586. << "CMake is implying the NO_POLICY_SCOPE option for compatibility, "
  587. << "so the effects are applied to the including context.";
  588. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  589. }
  590. break;
  591. case cmPolicies::REQUIRED_IF_USED:
  592. case cmPolicies::REQUIRED_ALWAYS: {
  593. std::ostringstream e;
  594. /* clang-format off */
  595. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
  596. << "The included script\n "
  597. << this->Makefile->GetBacktrace().Top().FilePath << "\n"
  598. << "affects policy settings, so it requires this policy to be set.";
  599. /* clang-format on */
  600. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  601. } break;
  602. case cmPolicies::OLD:
  603. case cmPolicies::NEW:
  604. // The script set this policy. We assume the purpose of the
  605. // script is to initialize policies for its includer, and since
  606. // the policy is now set for later scripts, we do not warn.
  607. break;
  608. }
  609. }
  610. bool cmMakefile::ReadDependentFile(const std::string& filename,
  611. bool noPolicyScope)
  612. {
  613. if (cmValue def = this->GetDefinition("CMAKE_CURRENT_LIST_FILE")) {
  614. this->AddDefinition("CMAKE_PARENT_LIST_FILE", *def);
  615. }
  616. std::string filenametoread = cmSystemTools::CollapseFullPath(
  617. filename, this->GetCurrentSourceDirectory());
  618. IncludeScope incScope(this, filenametoread, noPolicyScope);
  619. #ifdef CMake_ENABLE_DEBUGGER
  620. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  621. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  622. this, filenametoread);
  623. }
  624. #endif
  625. cmListFile listFile;
  626. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  627. this->Backtrace)) {
  628. #ifdef CMake_ENABLE_DEBUGGER
  629. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  630. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  631. }
  632. #endif
  633. return false;
  634. }
  635. #ifdef CMake_ENABLE_DEBUGGER
  636. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  637. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  638. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  639. filenametoread, listFile.Functions);
  640. }
  641. #endif
  642. this->RunListFile(listFile, filenametoread);
  643. if (cmSystemTools::GetFatalErrorOccurred()) {
  644. incScope.Quiet();
  645. }
  646. return true;
  647. }
  648. class cmMakefile::ListFileScope
  649. {
  650. public:
  651. ListFileScope(cmMakefile* mf, std::string const& filenametoread)
  652. : Makefile(mf)
  653. {
  654. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
  655. cmListFileContext::FromListFilePath(filenametoread));
  656. this->Makefile->StateSnapshot =
  657. this->Makefile->GetState()->CreateInlineListFileSnapshot(
  658. this->Makefile->StateSnapshot, filenametoread);
  659. assert(this->Makefile->StateSnapshot.IsValid());
  660. this->Makefile->PushFunctionBlockerBarrier();
  661. }
  662. ~ListFileScope()
  663. {
  664. this->Makefile->PopSnapshot(this->ReportError);
  665. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  666. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  667. }
  668. void Quiet() { this->ReportError = false; }
  669. ListFileScope(const ListFileScope&) = delete;
  670. ListFileScope& operator=(const ListFileScope&) = delete;
  671. private:
  672. cmMakefile* Makefile;
  673. bool ReportError = true;
  674. };
  675. class cmMakefile::DeferScope
  676. {
  677. public:
  678. DeferScope(cmMakefile* mf, std::string const& deferredInFile)
  679. : Makefile(mf)
  680. {
  681. cmListFileContext lfc;
  682. lfc.Line = cmListFileContext::DeferPlaceholderLine;
  683. lfc.FilePath = deferredInFile;
  684. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  685. this->Makefile->DeferRunning = true;
  686. }
  687. ~DeferScope()
  688. {
  689. this->Makefile->DeferRunning = false;
  690. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  691. }
  692. DeferScope(const DeferScope&) = delete;
  693. DeferScope& operator=(const DeferScope&) = delete;
  694. private:
  695. cmMakefile* Makefile;
  696. };
  697. class cmMakefile::DeferCallScope
  698. {
  699. public:
  700. DeferCallScope(cmMakefile* mf, std::string const& deferredFromFile)
  701. : Makefile(mf)
  702. {
  703. this->Makefile->StateSnapshot =
  704. this->Makefile->GetState()->CreateDeferCallSnapshot(
  705. this->Makefile->StateSnapshot, deferredFromFile);
  706. assert(this->Makefile->StateSnapshot.IsValid());
  707. }
  708. ~DeferCallScope() { this->Makefile->PopSnapshot(); }
  709. DeferCallScope(const DeferCallScope&) = delete;
  710. DeferCallScope& operator=(const DeferCallScope&) = delete;
  711. private:
  712. cmMakefile* Makefile;
  713. };
  714. bool cmMakefile::ReadListFile(const std::string& filename)
  715. {
  716. std::string filenametoread = cmSystemTools::CollapseFullPath(
  717. filename, this->GetCurrentSourceDirectory());
  718. ListFileScope scope(this, filenametoread);
  719. #ifdef CMake_ENABLE_DEBUGGER
  720. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  721. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  722. this, filenametoread);
  723. }
  724. #endif
  725. cmListFile listFile;
  726. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  727. this->Backtrace)) {
  728. #ifdef CMake_ENABLE_DEBUGGER
  729. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  730. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  731. }
  732. #endif
  733. return false;
  734. }
  735. #ifdef CMake_ENABLE_DEBUGGER
  736. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  737. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  738. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  739. filenametoread, listFile.Functions);
  740. }
  741. #endif
  742. this->RunListFile(listFile, filenametoread);
  743. if (cmSystemTools::GetFatalErrorOccurred()) {
  744. scope.Quiet();
  745. }
  746. return true;
  747. }
  748. bool cmMakefile::ReadListFileAsString(const std::string& content,
  749. const std::string& virtualFileName)
  750. {
  751. std::string filenametoread = cmSystemTools::CollapseFullPath(
  752. virtualFileName, this->GetCurrentSourceDirectory());
  753. ListFileScope scope(this, filenametoread);
  754. cmListFile listFile;
  755. if (!listFile.ParseString(content.c_str(), virtualFileName.c_str(),
  756. this->GetMessenger(), this->Backtrace)) {
  757. return false;
  758. }
  759. #ifdef CMake_ENABLE_DEBUGGER
  760. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  761. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  762. filenametoread, listFile.Functions);
  763. }
  764. #endif
  765. this->RunListFile(listFile, filenametoread);
  766. if (cmSystemTools::GetFatalErrorOccurred()) {
  767. scope.Quiet();
  768. }
  769. return true;
  770. }
  771. void cmMakefile::RunListFile(cmListFile const& listFile,
  772. std::string const& filenametoread,
  773. DeferCommands* defer)
  774. {
  775. // add this list file to the list of dependencies
  776. this->ListFiles.push_back(filenametoread);
  777. std::string currentParentFile =
  778. this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
  779. std::string currentFile = this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");
  780. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread);
  781. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  782. cmSystemTools::GetFilenamePath(filenametoread));
  783. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  784. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  785. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  786. // Run the parsed commands.
  787. const size_t numberFunctions = listFile.Functions.size();
  788. for (size_t i = 0; i < numberFunctions; ++i) {
  789. cmExecutionStatus status(*this);
  790. this->ExecuteCommand(listFile.Functions[i], status);
  791. if (cmSystemTools::GetFatalErrorOccurred()) {
  792. break;
  793. }
  794. if (status.HasExitCode()) {
  795. // cmake_language EXIT was requested, early break.
  796. this->GetCMakeInstance()->SetScriptModeExitCode(status.GetExitCode());
  797. break;
  798. }
  799. if (status.GetReturnInvoked()) {
  800. this->RaiseScope(status.GetReturnVariables());
  801. // Exit early due to return command.
  802. break;
  803. }
  804. }
  805. // Run any deferred commands.
  806. if (defer) {
  807. // Add a backtrace level indicating calls are deferred.
  808. DeferScope scope(this, filenametoread);
  809. // Iterate by index in case one deferred call schedules another.
  810. // NOLINTNEXTLINE(modernize-loop-convert)
  811. for (size_t i = 0; i < defer->Commands.size(); ++i) {
  812. DeferCommand& d = defer->Commands[i];
  813. if (d.Id.empty()) {
  814. // Canceled.
  815. continue;
  816. }
  817. // Mark as executed.
  818. std::string id = std::move(d.Id);
  819. // The deferred call may have come from another file.
  820. DeferCallScope callScope(this, d.FilePath);
  821. cmExecutionStatus status(*this);
  822. this->ExecuteCommand(d.Command, status, std::move(id));
  823. if (cmSystemTools::GetFatalErrorOccurred()) {
  824. break;
  825. }
  826. }
  827. }
  828. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile);
  829. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile);
  830. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  831. cmSystemTools::GetFilenamePath(currentFile));
  832. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  833. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  834. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  835. }
  836. void cmMakefile::EnforceDirectoryLevelRules() const
  837. {
  838. // Diagnose a violation of CMP0000 if necessary.
  839. if (this->CheckCMP0000) {
  840. std::ostringstream msg;
  841. msg << "No cmake_minimum_required command is present. "
  842. << "A line of code such as\n"
  843. << " cmake_minimum_required(VERSION " << cmVersion::GetMajorVersion()
  844. << "." << cmVersion::GetMinorVersion() << ")\n"
  845. << "should be added at the top of the file. "
  846. << "The version specified may be lower if you wish to "
  847. << "support older CMake versions for this project. "
  848. << "For more information run "
  849. << "\"cmake --help-policy CMP0000\".";
  850. switch (this->GetPolicyStatus(cmPolicies::CMP0000)) {
  851. case cmPolicies::WARN:
  852. // Warn because the user did not provide a minimum required
  853. // version.
  854. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  855. msg.str(), this->Backtrace);
  856. CM_FALLTHROUGH;
  857. case cmPolicies::OLD:
  858. // OLD behavior is to use policy version 2.4 set in
  859. // cmListFileCache.
  860. break;
  861. case cmPolicies::REQUIRED_IF_USED:
  862. case cmPolicies::REQUIRED_ALWAYS:
  863. case cmPolicies::NEW:
  864. // NEW behavior is to issue an error.
  865. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  866. msg.str(), this->Backtrace);
  867. cmSystemTools::SetFatalErrorOccurred();
  868. break;
  869. }
  870. }
  871. }
  872. void cmMakefile::AddEvaluationFile(
  873. const std::string& inputFile, const std::string& targetName,
  874. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  875. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  876. const std::string& newLineCharacter, mode_t permissions, bool inputIsContent)
  877. {
  878. this->EvaluationFiles.push_back(
  879. cm::make_unique<cmGeneratorExpressionEvaluationFile>(
  880. inputFile, targetName, std::move(outputName), std::move(condition),
  881. inputIsContent, newLineCharacter, permissions,
  882. this->GetPolicyStatus(cmPolicies::CMP0070)));
  883. }
  884. const std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>>&
  885. cmMakefile::GetEvaluationFiles() const
  886. {
  887. return this->EvaluationFiles;
  888. }
  889. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const&
  890. cmMakefile::GetExportBuildFileGenerators() const
  891. {
  892. return this->ExportBuildFileGenerators;
  893. }
  894. void cmMakefile::RemoveExportBuildFileGeneratorCMP0024(
  895. cmExportBuildFileGenerator* gen)
  896. {
  897. auto it =
  898. std::find_if(this->ExportBuildFileGenerators.begin(),
  899. this->ExportBuildFileGenerators.end(),
  900. [gen](std::unique_ptr<cmExportBuildFileGenerator> const& p) {
  901. return p.get() == gen;
  902. });
  903. if (it != this->ExportBuildFileGenerators.end()) {
  904. this->ExportBuildFileGenerators.erase(it);
  905. }
  906. }
  907. void cmMakefile::AddExportBuildFileGenerator(
  908. std::unique_ptr<cmExportBuildFileGenerator> gen)
  909. {
  910. this->ExportBuildFileGenerators.emplace_back(std::move(gen));
  911. }
  912. namespace {
  913. struct file_not_persistent
  914. {
  915. bool operator()(const std::string& path) const
  916. {
  917. return !(path.find("CMakeTmp") == std::string::npos &&
  918. cmSystemTools::FileExists(path));
  919. }
  920. };
  921. }
  922. void cmMakefile::AddGeneratorAction(GeneratorAction&& action)
  923. {
  924. assert(!this->GeneratorActionsInvoked);
  925. this->GeneratorActions.emplace_back(std::move(action), this->Backtrace);
  926. }
  927. void cmMakefile::GeneratorAction::operator()(cmLocalGenerator& lg,
  928. const cmListFileBacktrace& lfbt)
  929. {
  930. if (cc) {
  931. CCAction(lg, lfbt, std::move(cc));
  932. } else {
  933. assert(Action);
  934. Action(lg, lfbt);
  935. }
  936. }
  937. void cmMakefile::DoGenerate(cmLocalGenerator& lg)
  938. {
  939. // do all the variable expansions here
  940. this->ExpandVariablesCMP0019();
  941. // give all the commands a chance to do something
  942. // after the file has been parsed before generation
  943. for (auto& action : this->GeneratorActions) {
  944. action.Value(lg, action.Backtrace);
  945. }
  946. this->GeneratorActionsInvoked = true;
  947. // go through all configured files and see which ones still exist.
  948. // we don't want cmake to re-run if a configured file is created and deleted
  949. // during processing as that would make it a transient file that can't
  950. // influence the build process
  951. cm::erase_if(this->OutputFiles, file_not_persistent());
  952. // if a configured file is used as input for another configured file,
  953. // and then deleted it will show up in the input list files so we
  954. // need to scan those too
  955. cm::erase_if(this->ListFiles, file_not_persistent());
  956. }
  957. // Generate the output file
  958. void cmMakefile::Generate(cmLocalGenerator& lg)
  959. {
  960. this->DoGenerate(lg);
  961. cmValue oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
  962. if (oldValue &&
  963. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, *oldValue,
  964. "2.4")) {
  965. this->GetCMakeInstance()->IssueMessage(
  966. MessageType::FATAL_ERROR,
  967. "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
  968. "than 2.4. This version of CMake only supports backwards compatibility "
  969. "with CMake 2.4 or later. For compatibility with older versions please "
  970. "use any CMake 2.8.x release or lower.",
  971. this->Backtrace);
  972. }
  973. }
  974. namespace {
  975. // There are still too many implicit backtraces through cmMakefile. As a
  976. // workaround we reset the backtrace temporarily.
  977. struct BacktraceGuard
  978. {
  979. BacktraceGuard(cmListFileBacktrace& lfbt, cmListFileBacktrace current)
  980. : Backtrace(lfbt)
  981. , Previous(lfbt)
  982. {
  983. this->Backtrace = std::move(current);
  984. }
  985. ~BacktraceGuard() { this->Backtrace = std::move(this->Previous); }
  986. private:
  987. cmListFileBacktrace& Backtrace;
  988. cmListFileBacktrace Previous;
  989. };
  990. }
  991. bool cmMakefile::ValidateCustomCommand(
  992. const cmCustomCommandLines& commandLines) const
  993. {
  994. // TODO: More strict?
  995. for (cmCustomCommandLine const& cl : commandLines) {
  996. if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') {
  997. std::ostringstream e;
  998. e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
  999. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1000. return false;
  1001. }
  1002. }
  1003. return true;
  1004. }
  1005. cmTarget* cmMakefile::GetCustomCommandTarget(
  1006. const std::string& target, cmObjectLibraryCommands objLibCommands,
  1007. const cmListFileBacktrace& lfbt) const
  1008. {
  1009. auto realTarget = target;
  1010. auto ai = this->AliasTargets.find(target);
  1011. if (ai != this->AliasTargets.end()) {
  1012. realTarget = ai->second;
  1013. }
  1014. // Find the target to which to add the custom command.
  1015. auto ti = this->Targets.find(realTarget);
  1016. if (ti == this->Targets.end()) {
  1017. MessageType messageType = MessageType::AUTHOR_WARNING;
  1018. bool issueMessage = false;
  1019. std::ostringstream e;
  1020. switch (this->GetPolicyStatus(cmPolicies::CMP0040)) {
  1021. case cmPolicies::WARN:
  1022. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
  1023. issueMessage = true;
  1024. CM_FALLTHROUGH;
  1025. case cmPolicies::OLD:
  1026. break;
  1027. case cmPolicies::NEW:
  1028. case cmPolicies::REQUIRED_IF_USED:
  1029. case cmPolicies::REQUIRED_ALWAYS:
  1030. issueMessage = true;
  1031. messageType = MessageType::FATAL_ERROR;
  1032. break;
  1033. }
  1034. if (issueMessage) {
  1035. if (cmTarget const* t = this->FindTargetToUse(target)) {
  1036. if (t->IsImported()) {
  1037. e << "TARGET '" << target
  1038. << "' is IMPORTED and does not build here.";
  1039. } else {
  1040. e << "TARGET '" << target << "' was not created in this directory.";
  1041. }
  1042. } else {
  1043. e << "No TARGET '" << target
  1044. << "' has been created in this directory.";
  1045. }
  1046. this->GetCMakeInstance()->IssueMessage(messageType, e.str(), lfbt);
  1047. }
  1048. return nullptr;
  1049. }
  1050. cmTarget* t = &ti->second;
  1051. if (objLibCommands == cmObjectLibraryCommands::Reject &&
  1052. t->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1053. std::ostringstream e;
  1054. e << "Target \"" << target
  1055. << "\" is an OBJECT library "
  1056. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  1057. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1058. lfbt);
  1059. return nullptr;
  1060. }
  1061. if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1062. std::ostringstream e;
  1063. e << "Target \"" << target
  1064. << "\" is an INTERFACE library "
  1065. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  1066. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1067. lfbt);
  1068. return nullptr;
  1069. }
  1070. return t;
  1071. }
  1072. cmTarget* cmMakefile::AddCustomCommandToTarget(
  1073. const std::string& target, cmCustomCommandType type,
  1074. std::unique_ptr<cmCustomCommand> cc)
  1075. {
  1076. const auto& byproducts = cc->GetByproducts();
  1077. const auto& commandLines = cc->GetCommandLines();
  1078. cmTarget* t = this->GetCustomCommandTarget(
  1079. target, cmObjectLibraryCommands::Reject, this->Backtrace);
  1080. // Validate custom commands.
  1081. if (!t || !this->ValidateCustomCommand(commandLines)) {
  1082. return t;
  1083. }
  1084. // Always create the byproduct sources and mark them generated.
  1085. this->CreateGeneratedOutputs(byproducts);
  1086. cc->RecordPolicyValues(this->GetStateSnapshot());
  1087. // Dispatch command creation to allow generator expressions in outputs.
  1088. this->AddGeneratorAction(
  1089. std::move(cc),
  1090. [this, t, type](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1091. std::unique_ptr<cmCustomCommand> tcc) {
  1092. BacktraceGuard guard(this->Backtrace, lfbt);
  1093. tcc->SetBacktrace(lfbt);
  1094. detail::AddCustomCommandToTarget(lg, cmCommandOrigin::Project, t, type,
  1095. std::move(tcc));
  1096. });
  1097. return t;
  1098. }
  1099. void cmMakefile::AddCustomCommandToOutput(
  1100. std::unique_ptr<cmCustomCommand> cc, const CommandSourceCallback& callback,
  1101. bool replace)
  1102. {
  1103. const auto& outputs = cc->GetOutputs();
  1104. const auto& byproducts = cc->GetByproducts();
  1105. const auto& commandLines = cc->GetCommandLines();
  1106. // Make sure there is at least one output.
  1107. if (outputs.empty()) {
  1108. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  1109. return;
  1110. }
  1111. // Validate custom commands.
  1112. if (!this->ValidateCustomCommand(commandLines)) {
  1113. return;
  1114. }
  1115. // Always create the output sources and mark them generated.
  1116. this->CreateGeneratedOutputs(outputs);
  1117. this->CreateGeneratedOutputs(byproducts);
  1118. cc->RecordPolicyValues(this->GetStateSnapshot());
  1119. // Dispatch command creation to allow generator expressions in outputs.
  1120. this->AddGeneratorAction(
  1121. std::move(cc),
  1122. [this, replace, callback](cmLocalGenerator& lg,
  1123. const cmListFileBacktrace& lfbt,
  1124. std::unique_ptr<cmCustomCommand> tcc) {
  1125. BacktraceGuard guard(this->Backtrace, lfbt);
  1126. tcc->SetBacktrace(lfbt);
  1127. cmSourceFile* sf = detail::AddCustomCommandToOutput(
  1128. lg, cmCommandOrigin::Project, std::move(tcc), replace);
  1129. if (callback && sf) {
  1130. callback(sf);
  1131. }
  1132. });
  1133. }
  1134. void cmMakefile::AddCustomCommandOldStyle(
  1135. const std::string& target, const std::vector<std::string>& outputs,
  1136. const std::vector<std::string>& depends, const std::string& source,
  1137. const cmCustomCommandLines& commandLines, const char* comment)
  1138. {
  1139. auto cc = cm::make_unique<cmCustomCommand>();
  1140. cc->SetDepends(depends);
  1141. cc->SetCommandLines(commandLines);
  1142. cc->SetComment(comment);
  1143. // Translate the old-style signature to one of the new-style
  1144. // signatures.
  1145. if (source == target) {
  1146. // In the old-style signature if the source and target were the
  1147. // same then it added a post-build rule to the target. Preserve
  1148. // this behavior.
  1149. this->AddCustomCommandToTarget(target, cmCustomCommandType::POST_BUILD,
  1150. std::move(cc));
  1151. return;
  1152. }
  1153. auto ti = this->Targets.find(target);
  1154. cmTarget* t = ti != this->Targets.end() ? &ti->second : nullptr;
  1155. auto addRuleFileToTarget = [=](cmSourceFile* sf) {
  1156. // If the rule was added to the source (and not a .rule file),
  1157. // then add the source to the target to make sure the rule is
  1158. // included.
  1159. if (!sf->GetPropertyAsBool("__CMAKE_RULE")) {
  1160. if (t) {
  1161. t->AddSource(sf->ResolveFullPath());
  1162. } else {
  1163. cmSystemTools::Error("Attempt to add a custom rule to a target "
  1164. "that does not exist yet for target " +
  1165. target);
  1166. }
  1167. }
  1168. };
  1169. // Each output must get its own copy of this rule.
  1170. cmsys::RegularExpression sourceFiles(
  1171. "\\.(C|M|c|c\\+\\+|cc|cpp|cxx|mpp|ixx|cppm|ccm|cxxm|c\\+\\+m|cu|m|mm|"
  1172. "rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
  1173. "hm|hpp|hxx|in|txx|inl)$");
  1174. // Choose whether to use a main dependency.
  1175. if (sourceFiles.find(source)) {
  1176. // The source looks like a real file. Use it as the main dependency.
  1177. for (std::string const& output : outputs) {
  1178. auto cc1 = cm::make_unique<cmCustomCommand>(*cc);
  1179. cc1->SetOutputs(output);
  1180. cc1->SetMainDependency(source);
  1181. this->AddCustomCommandToOutput(std::move(cc1), addRuleFileToTarget);
  1182. }
  1183. } else {
  1184. cc->AppendDepends({ source });
  1185. // The source may not be a real file. Do not use a main dependency.
  1186. for (std::string const& output : outputs) {
  1187. auto cc1 = cm::make_unique<cmCustomCommand>(*cc);
  1188. cc1->SetOutputs(output);
  1189. this->AddCustomCommandToOutput(std::move(cc1), addRuleFileToTarget);
  1190. }
  1191. }
  1192. }
  1193. void cmMakefile::AppendCustomCommandToOutput(
  1194. const std::string& output, const std::vector<std::string>& depends,
  1195. const cmImplicitDependsList& implicit_depends,
  1196. const cmCustomCommandLines& commandLines)
  1197. {
  1198. // Validate custom commands.
  1199. if (this->ValidateCustomCommand(commandLines)) {
  1200. // Dispatch command creation to allow generator expressions in outputs.
  1201. this->AddGeneratorAction(
  1202. [this, output, depends, implicit_depends,
  1203. commandLines](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt) {
  1204. BacktraceGuard guard(this->Backtrace, lfbt);
  1205. detail::AppendCustomCommandToOutput(lg, lfbt, output, depends,
  1206. implicit_depends, commandLines);
  1207. });
  1208. }
  1209. }
  1210. cmTarget* cmMakefile::AddUtilityCommand(const std::string& utilityName,
  1211. bool excludeFromAll,
  1212. std::unique_ptr<cmCustomCommand> cc)
  1213. {
  1214. const auto& depends = cc->GetDepends();
  1215. const auto& byproducts = cc->GetByproducts();
  1216. const auto& commandLines = cc->GetCommandLines();
  1217. cmTarget* target = this->AddNewUtilityTarget(utilityName, excludeFromAll);
  1218. // Validate custom commands.
  1219. if ((commandLines.empty() && depends.empty()) ||
  1220. !this->ValidateCustomCommand(commandLines)) {
  1221. return target;
  1222. }
  1223. // Always create the byproduct sources and mark them generated.
  1224. this->CreateGeneratedOutputs(byproducts);
  1225. cc->RecordPolicyValues(this->GetStateSnapshot());
  1226. // Dispatch command creation to allow generator expressions in outputs.
  1227. this->AddGeneratorAction(
  1228. std::move(cc),
  1229. [this, target](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1230. std::unique_ptr<cmCustomCommand> tcc) {
  1231. BacktraceGuard guard(this->Backtrace, lfbt);
  1232. tcc->SetBacktrace(lfbt);
  1233. detail::AddUtilityCommand(lg, cmCommandOrigin::Project, target,
  1234. std::move(tcc));
  1235. });
  1236. return target;
  1237. }
  1238. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1239. {
  1240. // remove any \n\r
  1241. std::string::size_type initSize = dflags.size();
  1242. dflags += ' ';
  1243. dflags += flag;
  1244. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1245. std::replace(flagStart, dflags.end(), '\n', ' ');
  1246. std::replace(flagStart, dflags.end(), '\r', ' ');
  1247. }
  1248. void cmMakefile::AddDefineFlag(std::string const& flag)
  1249. {
  1250. if (flag.empty()) {
  1251. return;
  1252. }
  1253. // Update the string used for the old DEFINITIONS property.
  1254. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1255. // If this is really a definition, update COMPILE_DEFINITIONS.
  1256. if (this->ParseDefineFlag(flag, false)) {
  1257. return;
  1258. }
  1259. // Add this flag that does not look like a definition.
  1260. s_AddDefineFlag(flag, this->DefineFlags);
  1261. }
  1262. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1263. {
  1264. std::string::size_type const len = flag.length();
  1265. // Remove all instances of the flag that are surrounded by
  1266. // whitespace or the beginning/end of the string.
  1267. for (std::string::size_type lpos = dflags.find(flag, 0);
  1268. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1269. std::string::size_type rpos = lpos + len;
  1270. if ((lpos <= 0 || cmIsSpace(dflags[lpos - 1])) &&
  1271. (rpos >= dflags.size() || cmIsSpace(dflags[rpos]))) {
  1272. dflags.erase(lpos, len);
  1273. } else {
  1274. ++lpos;
  1275. }
  1276. }
  1277. }
  1278. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1279. {
  1280. // Check the length of the flag to remove.
  1281. if (flag.empty()) {
  1282. return;
  1283. }
  1284. // Update the string used for the old DEFINITIONS property.
  1285. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1286. // If this is really a definition, update COMPILE_DEFINITIONS.
  1287. if (this->ParseDefineFlag(flag, true)) {
  1288. return;
  1289. }
  1290. // Remove this flag that does not look like a definition.
  1291. s_RemoveDefineFlag(flag, this->DefineFlags);
  1292. }
  1293. void cmMakefile::AddCompileDefinition(std::string const& option)
  1294. {
  1295. this->AppendProperty("COMPILE_DEFINITIONS", option);
  1296. }
  1297. void cmMakefile::AddCompileOption(std::string const& option)
  1298. {
  1299. this->AppendProperty("COMPILE_OPTIONS", option);
  1300. }
  1301. void cmMakefile::AddLinkOption(std::string const& option)
  1302. {
  1303. this->AppendProperty("LINK_OPTIONS", option);
  1304. }
  1305. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1306. {
  1307. if (before) {
  1308. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
  1309. BT<std::string>(directory, this->Backtrace));
  1310. } else {
  1311. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
  1312. BT<std::string>(directory, this->Backtrace));
  1313. }
  1314. }
  1315. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1316. {
  1317. // Create a regular expression to match valid definitions.
  1318. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1319. // Make sure the definition matches.
  1320. if (!valid.find(def)) {
  1321. return false;
  1322. }
  1323. // Definitions with non-trivial values require a policy check.
  1324. static cmsys::RegularExpression trivial(
  1325. "^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
  1326. if (!trivial.find(def)) {
  1327. // This definition has a non-trivial value.
  1328. switch (this->GetPolicyStatus(cmPolicies::CMP0005)) {
  1329. case cmPolicies::WARN:
  1330. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1331. cmPolicies::GetPolicyWarning(cmPolicies::CMP0005));
  1332. CM_FALLTHROUGH;
  1333. case cmPolicies::OLD:
  1334. // OLD behavior is to not escape the value. We should not
  1335. // convert the definition to use the property.
  1336. return false;
  1337. case cmPolicies::REQUIRED_IF_USED:
  1338. case cmPolicies::REQUIRED_ALWAYS:
  1339. this->IssueMessage(
  1340. MessageType::FATAL_ERROR,
  1341. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005));
  1342. return false;
  1343. case cmPolicies::NEW:
  1344. // NEW behavior is to escape the value. Proceed to convert it
  1345. // to an entry in the property.
  1346. break;
  1347. }
  1348. }
  1349. // Get the definition part after the flag.
  1350. const char* define = def.c_str() + 2;
  1351. if (remove) {
  1352. if (cmValue cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1353. // Expand the list.
  1354. cmList defs{ *cdefs };
  1355. // Recompose the list without the definition.
  1356. defs.remove_items({ define });
  1357. // Store the new list.
  1358. this->SetProperty("COMPILE_DEFINITIONS", defs.to_string());
  1359. }
  1360. } else {
  1361. // Append the definition to the directory property.
  1362. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1363. }
  1364. return true;
  1365. }
  1366. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1367. {
  1368. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1369. // define flags
  1370. this->DefineFlags = parent->DefineFlags;
  1371. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1372. // Include transform property. There is no per-config version.
  1373. {
  1374. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1375. this->SetProperty(prop, parent->GetProperty(prop));
  1376. }
  1377. // compile definitions property and per-config versions
  1378. cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
  1379. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1380. this->SetProperty("COMPILE_DEFINITIONS",
  1381. parent->GetProperty("COMPILE_DEFINITIONS"));
  1382. std::vector<std::string> configs =
  1383. this->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  1384. for (std::string const& config : configs) {
  1385. std::string defPropName =
  1386. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  1387. cmValue prop = parent->GetProperty(defPropName);
  1388. this->SetProperty(defPropName, prop);
  1389. }
  1390. }
  1391. // labels
  1392. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1393. // link libraries
  1394. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1395. // the initial project name
  1396. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1397. // Copy include regular expressions.
  1398. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1399. // Imported targets.
  1400. this->ImportedTargets = parent->ImportedTargets;
  1401. // Non-global Alias targets.
  1402. this->AliasTargets = parent->AliasTargets;
  1403. // Recursion depth.
  1404. this->RecursionDepth = parent->RecursionDepth;
  1405. }
  1406. void cmMakefile::AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g)
  1407. {
  1408. if (g) {
  1409. this->InstallGenerators.push_back(std::move(g));
  1410. }
  1411. }
  1412. void cmMakefile::AddTestGenerator(std::unique_ptr<cmTestGenerator> g)
  1413. {
  1414. if (g) {
  1415. this->TestGenerators.push_back(std::move(g));
  1416. }
  1417. }
  1418. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1419. const cmPolicies::PolicyMap& pm)
  1420. {
  1421. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1422. this->StateSnapshot, fileName);
  1423. assert(this->StateSnapshot.IsValid());
  1424. this->PushLoopBlockBarrier();
  1425. #if !defined(CMAKE_BOOTSTRAP)
  1426. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1427. #endif
  1428. this->PushFunctionBlockerBarrier();
  1429. this->PushPolicy(true, pm);
  1430. }
  1431. void cmMakefile::PopFunctionScope(bool reportError)
  1432. {
  1433. this->PopPolicy();
  1434. this->PopSnapshot(reportError);
  1435. this->PopFunctionBlockerBarrier(reportError);
  1436. #if !defined(CMAKE_BOOTSTRAP)
  1437. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1438. #endif
  1439. this->PopLoopBlockBarrier();
  1440. }
  1441. void cmMakefile::PushMacroScope(std::string const& fileName,
  1442. const cmPolicies::PolicyMap& pm)
  1443. {
  1444. this->StateSnapshot =
  1445. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1446. assert(this->StateSnapshot.IsValid());
  1447. this->PushFunctionBlockerBarrier();
  1448. this->PushPolicy(true, pm);
  1449. }
  1450. void cmMakefile::PopMacroScope(bool reportError)
  1451. {
  1452. this->PopPolicy();
  1453. this->PopSnapshot(reportError);
  1454. this->PopFunctionBlockerBarrier(reportError);
  1455. }
  1456. bool cmMakefile::IsRootMakefile() const
  1457. {
  1458. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1459. }
  1460. class cmMakefile::BuildsystemFileScope
  1461. {
  1462. public:
  1463. BuildsystemFileScope(cmMakefile* mf)
  1464. : Makefile(mf)
  1465. {
  1466. std::string currentStart =
  1467. cmStrCat(this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource(),
  1468. "/CMakeLists.txt");
  1469. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1470. this->Makefile->StateSnapshot =
  1471. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1472. this->Makefile->StateSnapshot);
  1473. this->Makefile->PushFunctionBlockerBarrier();
  1474. this->GG = mf->GetGlobalGenerator();
  1475. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1476. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1477. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1478. this->GG->SetCurrentMakefile(mf);
  1479. #if !defined(CMAKE_BOOTSTRAP)
  1480. this->GG->GetFileLockPool().PushFileScope();
  1481. #endif
  1482. }
  1483. ~BuildsystemFileScope()
  1484. {
  1485. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1486. this->Makefile->PopSnapshot(this->ReportError);
  1487. #if !defined(CMAKE_BOOTSTRAP)
  1488. this->GG->GetFileLockPool().PopFileScope();
  1489. #endif
  1490. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1491. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1492. }
  1493. void Quiet() { this->ReportError = false; }
  1494. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1495. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1496. private:
  1497. cmMakefile* Makefile;
  1498. cmGlobalGenerator* GG;
  1499. cmMakefile* CurrentMakefile;
  1500. cmStateSnapshot Snapshot;
  1501. bool ReportError = true;
  1502. };
  1503. void cmMakefile::Configure()
  1504. {
  1505. std::string currentStart = cmStrCat(
  1506. this->StateSnapshot.GetDirectory().GetCurrentSource(), "/CMakeLists.txt");
  1507. // Add the bottom of all backtraces within this directory.
  1508. // We will never pop this scope because it should be available
  1509. // for messages during the generate step too.
  1510. this->Backtrace =
  1511. this->Backtrace.Push(cmListFileContext::FromListFilePath(currentStart));
  1512. BuildsystemFileScope scope(this);
  1513. // make sure the CMakeFiles dir is there
  1514. std::string filesDir = cmStrCat(
  1515. this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles");
  1516. cmSystemTools::MakeDirectory(filesDir);
  1517. assert(cmSystemTools::FileExists(currentStart, true));
  1518. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart);
  1519. #ifdef CMake_ENABLE_DEBUGGER
  1520. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1521. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  1522. this, currentStart);
  1523. }
  1524. #endif
  1525. cmListFile listFile;
  1526. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1527. this->Backtrace)) {
  1528. #ifdef CMake_ENABLE_DEBUGGER
  1529. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1530. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1531. }
  1532. #endif
  1533. return;
  1534. }
  1535. #ifdef CMake_ENABLE_DEBUGGER
  1536. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1537. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1538. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  1539. currentStart, listFile.Functions);
  1540. }
  1541. #endif
  1542. if (this->IsRootMakefile()) {
  1543. bool hasVersion = false;
  1544. // search for the right policy command
  1545. for (cmListFileFunction const& func : listFile.Functions) {
  1546. if (func.LowerCaseName() == "cmake_minimum_required"_s) {
  1547. hasVersion = true;
  1548. break;
  1549. }
  1550. }
  1551. // if no policy command is found this is an error if they use any
  1552. // non advanced functions or a lot of functions
  1553. if (!hasVersion) {
  1554. bool isProblem = true;
  1555. if (listFile.Functions.size() < 30) {
  1556. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1557. // these commands must have backwards compatibility forever and
  1558. // and that is a lot longer than your tiny mind can comprehend mortal
  1559. std::set<std::string> allowedCommands;
  1560. allowedCommands.insert("project");
  1561. allowedCommands.insert("set");
  1562. allowedCommands.insert("if");
  1563. allowedCommands.insert("endif");
  1564. allowedCommands.insert("else");
  1565. allowedCommands.insert("elseif");
  1566. allowedCommands.insert("add_executable");
  1567. allowedCommands.insert("add_library");
  1568. allowedCommands.insert("target_link_libraries");
  1569. allowedCommands.insert("option");
  1570. allowedCommands.insert("message");
  1571. isProblem = false;
  1572. for (cmListFileFunction const& func : listFile.Functions) {
  1573. if (!cm::contains(allowedCommands, func.LowerCaseName())) {
  1574. isProblem = true;
  1575. break;
  1576. }
  1577. }
  1578. }
  1579. if (isProblem) {
  1580. // Tell the top level cmMakefile to diagnose
  1581. // this violation of CMP0000.
  1582. this->SetCheckCMP0000(true);
  1583. // Implicitly set the version for the user.
  1584. cmPolicies::ApplyPolicyVersion(this, 2, 4, 0,
  1585. cmPolicies::WarnCompat::Off);
  1586. }
  1587. }
  1588. bool hasProject = false;
  1589. // search for a project command
  1590. for (cmListFileFunction const& func : listFile.Functions) {
  1591. if (func.LowerCaseName() == "project"_s) {
  1592. hasProject = true;
  1593. break;
  1594. }
  1595. }
  1596. // if no project command is found, add one
  1597. if (!hasProject) {
  1598. this->GetCMakeInstance()->IssueMessage(
  1599. MessageType::AUTHOR_WARNING,
  1600. "No project() command is present. The top-level CMakeLists.txt "
  1601. "file must contain a literal, direct call to the project() command. "
  1602. "Add a line of code such as\n"
  1603. " project(ProjectName)\n"
  1604. "near the top of the file, but after cmake_minimum_required().\n"
  1605. "CMake is pretending there is a \"project(Project)\" command on "
  1606. "the first line.",
  1607. this->Backtrace);
  1608. cmListFileFunction project{ "project",
  1609. 0,
  1610. 0,
  1611. { { "Project", cmListFileArgument::Unquoted,
  1612. 0 },
  1613. { "__CMAKE_INJECTED_PROJECT_COMMAND__",
  1614. cmListFileArgument::Unquoted, 0 } } };
  1615. listFile.Functions.insert(listFile.Functions.begin(), project);
  1616. }
  1617. }
  1618. this->Defer = cm::make_unique<DeferCommands>();
  1619. this->RunListFile(listFile, currentStart, this->Defer.get());
  1620. this->Defer.reset();
  1621. if (cmSystemTools::GetFatalErrorOccurred()) {
  1622. scope.Quiet();
  1623. }
  1624. // at the end handle any old style subdirs
  1625. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1626. // for each subdir recurse
  1627. auto sdi = subdirs.begin();
  1628. for (; sdi != subdirs.end(); ++sdi) {
  1629. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1630. this->ConfigureSubDirectory(*sdi);
  1631. }
  1632. this->AddCMakeDependFilesFromUser();
  1633. }
  1634. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1635. {
  1636. mf->InitializeFromParent(this);
  1637. std::string currentStart = mf->GetCurrentSourceDirectory();
  1638. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1639. std::string msg = cmStrCat(" Entering ", currentStart);
  1640. cmSystemTools::Message(msg);
  1641. }
  1642. std::string const currentStartFile =
  1643. cmStrCat(currentStart, "/CMakeLists.txt");
  1644. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1645. // The file is missing. Check policy CMP0014.
  1646. std::ostringstream e;
  1647. /* clang-format off */
  1648. e << "The source directory\n"
  1649. << " " << currentStart << "\n"
  1650. << "does not contain a CMakeLists.txt file.";
  1651. /* clang-format on */
  1652. switch (this->GetPolicyStatus(cmPolicies::CMP0014)) {
  1653. case cmPolicies::WARN:
  1654. // Print the warning.
  1655. /* clang-format off */
  1656. e << "\n"
  1657. << "CMake does not support this case but it used "
  1658. << "to work accidentally and is being allowed for "
  1659. << "compatibility."
  1660. << "\n"
  1661. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
  1662. /* clang-format on */
  1663. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1664. CM_FALLTHROUGH;
  1665. case cmPolicies::OLD:
  1666. // OLD behavior does not warn.
  1667. break;
  1668. case cmPolicies::REQUIRED_IF_USED:
  1669. case cmPolicies::REQUIRED_ALWAYS:
  1670. e << "\n" << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
  1671. CM_FALLTHROUGH;
  1672. case cmPolicies::NEW:
  1673. // NEW behavior prints the error.
  1674. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1675. break;
  1676. }
  1677. return;
  1678. }
  1679. // finally configure the subdir
  1680. mf->Configure();
  1681. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1682. std::string msg =
  1683. cmStrCat(" Returning to ", this->GetCurrentSourceDirectory());
  1684. cmSystemTools::Message(msg);
  1685. }
  1686. }
  1687. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1688. const std::string& binPath,
  1689. bool excludeFromAll, bool immediate,
  1690. bool system)
  1691. {
  1692. if (this->DeferRunning) {
  1693. this->IssueMessage(
  1694. MessageType::FATAL_ERROR,
  1695. "Subdirectories may not be created during deferred execution.");
  1696. return;
  1697. }
  1698. // Make sure the binary directory is unique.
  1699. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1700. return;
  1701. }
  1702. cmStateSnapshot newSnapshot =
  1703. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1704. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1705. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1706. cmSystemTools::MakeDirectory(binPath);
  1707. auto subMfu =
  1708. cm::make_unique<cmMakefile>(this->GlobalGenerator, newSnapshot);
  1709. auto* subMf = subMfu.get();
  1710. this->GetGlobalGenerator()->AddMakefile(std::move(subMfu));
  1711. if (excludeFromAll) {
  1712. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1713. }
  1714. if (system) {
  1715. subMf->SetProperty("SYSTEM", "TRUE");
  1716. }
  1717. if (immediate) {
  1718. this->ConfigureSubDirectory(subMf);
  1719. } else {
  1720. this->UnConfiguredDirectories.push_back(subMf);
  1721. }
  1722. this->AddInstallGenerator(cm::make_unique<cmInstallSubdirectoryGenerator>(
  1723. subMf, binPath, this->GetBacktrace()));
  1724. }
  1725. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1726. {
  1727. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1728. }
  1729. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1730. {
  1731. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1732. }
  1733. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1734. {
  1735. std::vector<cmTarget*> tgts;
  1736. tgts.reserve(this->ImportedTargets.size());
  1737. for (auto const& impTarget : this->ImportedTargets) {
  1738. tgts.push_back(impTarget.second);
  1739. }
  1740. return tgts;
  1741. }
  1742. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1743. bool before)
  1744. {
  1745. if (incs.empty()) {
  1746. return;
  1747. }
  1748. std::string entryString = cmList::to_string(incs);
  1749. if (before) {
  1750. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1751. BT<std::string>(entryString, this->Backtrace));
  1752. } else {
  1753. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1754. BT<std::string>(entryString, this->Backtrace));
  1755. }
  1756. // Property on each target:
  1757. for (auto& target : this->Targets) {
  1758. cmTarget& t = target.second;
  1759. t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
  1760. }
  1761. }
  1762. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1763. {
  1764. if (incs.empty()) {
  1765. return;
  1766. }
  1767. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1768. for (auto& target : this->Targets) {
  1769. cmTarget& t = target.second;
  1770. t.AddSystemIncludeDirectories(incs);
  1771. }
  1772. }
  1773. void cmMakefile::AddDefinition(const std::string& name, cm::string_view value)
  1774. {
  1775. this->StateSnapshot.SetDefinition(name, value);
  1776. #ifndef CMAKE_BOOTSTRAP
  1777. cmVariableWatch* vv = this->GetVariableWatch();
  1778. if (vv) {
  1779. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1780. value.data(), this);
  1781. }
  1782. #endif
  1783. }
  1784. void cmMakefile::AddDefinitionBool(const std::string& name, bool value)
  1785. {
  1786. this->AddDefinition(name, value ? "ON" : "OFF");
  1787. }
  1788. void cmMakefile::AddCacheDefinition(const std::string& name, cmValue value,
  1789. cmValue doc,
  1790. cmStateEnums::CacheEntryType type,
  1791. bool force)
  1792. {
  1793. cmValue existingValue = this->GetState()->GetInitializedCacheValue(name);
  1794. // must be outside the following if() to keep it alive long enough
  1795. std::string nvalue;
  1796. if (existingValue &&
  1797. (this->GetState()->GetCacheEntryType(name) ==
  1798. cmStateEnums::UNINITIALIZED)) {
  1799. // if this is not a force, then use the value from the cache
  1800. // if it is a force, then use the value being passed in
  1801. if (!force) {
  1802. value = existingValue;
  1803. }
  1804. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1805. cmList files(value);
  1806. for (auto& file : files) {
  1807. if (!cmIsOff(file)) {
  1808. file = cmSystemTools::CollapseFullPath(file);
  1809. }
  1810. }
  1811. nvalue = files.to_string();
  1812. value = cmValue{ nvalue };
  1813. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1814. value = this->GetState()->GetInitializedCacheValue(name);
  1815. }
  1816. }
  1817. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1818. switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
  1819. case cmPolicies::WARN:
  1820. if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
  1821. this->IsNormalDefinitionSet(name)) {
  1822. this->IssueMessage(
  1823. MessageType::AUTHOR_WARNING,
  1824. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0126),
  1825. "\nFor compatibility with older versions of CMake, normal "
  1826. "variable \"",
  1827. name, "\" will be removed from the current scope."));
  1828. }
  1829. CM_FALLTHROUGH;
  1830. case cmPolicies::OLD:
  1831. // if there was a definition then remove it
  1832. this->StateSnapshot.RemoveDefinition(name);
  1833. break;
  1834. case cmPolicies::NEW:
  1835. case cmPolicies::REQUIRED_IF_USED:
  1836. case cmPolicies::REQUIRED_ALWAYS:
  1837. break;
  1838. }
  1839. }
  1840. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1841. {
  1842. this->StateSnapshot.GetDefinition(var);
  1843. }
  1844. bool cmMakefile::VariableInitialized(const std::string& var) const
  1845. {
  1846. return this->StateSnapshot.IsInitialized(var);
  1847. }
  1848. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1849. const char* sourceFilename) const
  1850. {
  1851. // check to see if we need to print a warning
  1852. // if strict mode is on and the variable has
  1853. // not been "cleared"/initialized with a set(foo ) call
  1854. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1855. !this->VariableInitialized(variable)) {
  1856. if (this->CheckSystemVars ||
  1857. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1858. std::ostringstream msg;
  1859. msg << "uninitialized variable \'" << variable << "\'";
  1860. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1861. }
  1862. }
  1863. }
  1864. void cmMakefile::RemoveDefinition(const std::string& name)
  1865. {
  1866. this->StateSnapshot.RemoveDefinition(name);
  1867. #ifndef CMAKE_BOOTSTRAP
  1868. cmVariableWatch* vv = this->GetVariableWatch();
  1869. if (vv) {
  1870. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1871. nullptr, this);
  1872. }
  1873. #endif
  1874. }
  1875. void cmMakefile::RemoveCacheDefinition(const std::string& name) const
  1876. {
  1877. this->GetState()->RemoveCacheEntry(name);
  1878. }
  1879. void cmMakefile::SetProjectName(std::string const& p)
  1880. {
  1881. this->StateSnapshot.SetProjectName(p);
  1882. }
  1883. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1884. {
  1885. // for these targets do not add anything
  1886. switch (target.GetType()) {
  1887. case cmStateEnums::UTILITY:
  1888. case cmStateEnums::GLOBAL_TARGET:
  1889. case cmStateEnums::INTERFACE_LIBRARY:
  1890. return;
  1891. default:;
  1892. }
  1893. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1894. cmList linkLibs{ *linkLibsProp };
  1895. for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
  1896. std::string libraryName = *j;
  1897. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1898. if (libraryName == "optimized"_s) {
  1899. libType = OPTIMIZED_LibraryType;
  1900. ++j;
  1901. libraryName = *j;
  1902. } else if (libraryName == "debug"_s) {
  1903. libType = DEBUG_LibraryType;
  1904. ++j;
  1905. libraryName = *j;
  1906. }
  1907. // This is equivalent to the target_link_libraries plain signature.
  1908. target.AddLinkLibrary(*this, libraryName, libType);
  1909. target.AppendProperty(
  1910. "INTERFACE_LINK_LIBRARIES",
  1911. target.GetDebugGeneratorExpressions(libraryName, libType));
  1912. }
  1913. }
  1914. }
  1915. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName,
  1916. bool globallyVisible)
  1917. {
  1918. this->AliasTargets[lname] = tgtName;
  1919. if (globallyVisible) {
  1920. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1921. }
  1922. }
  1923. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1924. cmStateEnums::TargetType type,
  1925. const std::vector<std::string>& srcs,
  1926. bool excludeFromAll)
  1927. {
  1928. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1929. type == cmStateEnums::SHARED_LIBRARY ||
  1930. type == cmStateEnums::MODULE_LIBRARY ||
  1931. type == cmStateEnums::OBJECT_LIBRARY ||
  1932. type == cmStateEnums::INTERFACE_LIBRARY);
  1933. cmTarget* target = this->AddNewTarget(type, lname);
  1934. // Clear its dependencies. Otherwise, dependencies might persist
  1935. // over changes in CMakeLists.txt, making the information stale and
  1936. // hence useless.
  1937. target->ClearDependencyInformation(*this);
  1938. if (excludeFromAll) {
  1939. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1940. }
  1941. target->AddSources(srcs);
  1942. this->AddGlobalLinkInformation(*target);
  1943. return target;
  1944. }
  1945. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1946. const std::vector<std::string>& srcs,
  1947. bool excludeFromAll)
  1948. {
  1949. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1950. if (excludeFromAll) {
  1951. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1952. }
  1953. target->AddSources(srcs);
  1954. this->AddGlobalLinkInformation(*target);
  1955. return target;
  1956. }
  1957. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1958. const std::string& name)
  1959. {
  1960. return &this->CreateNewTarget(name, type).first;
  1961. }
  1962. cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
  1963. const std::string& name)
  1964. {
  1965. return &this
  1966. ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
  1967. cmTarget::Visibility::Generated)
  1968. .first;
  1969. }
  1970. std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
  1971. const std::string& name, cmStateEnums::TargetType type,
  1972. cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
  1973. {
  1974. auto ib =
  1975. this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
  1976. auto it = ib.first;
  1977. if (!ib.second) {
  1978. return std::make_pair(std::ref(it->second), false);
  1979. }
  1980. this->OrderedTargets.push_back(&it->second);
  1981. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1982. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1983. return std::make_pair(std::ref(it->second), true);
  1984. }
  1985. cmTarget* cmMakefile::AddNewUtilityTarget(const std::string& utilityName,
  1986. bool excludeFromAll)
  1987. {
  1988. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1989. if (excludeFromAll) {
  1990. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1991. }
  1992. return target;
  1993. }
  1994. namespace {
  1995. }
  1996. #if !defined(CMAKE_BOOTSTRAP)
  1997. cmSourceGroup* cmMakefile::GetSourceGroup(
  1998. const std::vector<std::string>& name) const
  1999. {
  2000. cmSourceGroup* sg = nullptr;
  2001. // first look for source group starting with the same as the one we want
  2002. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  2003. std::string const& sgName = srcGroup.GetName();
  2004. if (sgName == name[0]) {
  2005. sg = const_cast<cmSourceGroup*>(&srcGroup);
  2006. break;
  2007. }
  2008. }
  2009. if (sg != nullptr) {
  2010. // iterate through its children to find match source group
  2011. for (unsigned int i = 1; i < name.size(); ++i) {
  2012. sg = sg->LookupChild(name[i]);
  2013. if (sg == nullptr) {
  2014. break;
  2015. }
  2016. }
  2017. }
  2018. return sg;
  2019. }
  2020. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  2021. {
  2022. std::vector<std::string> nameVector;
  2023. nameVector.push_back(name);
  2024. this->AddSourceGroup(nameVector, regex);
  2025. }
  2026. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  2027. const char* regex)
  2028. {
  2029. cmSourceGroup* sg = nullptr;
  2030. std::vector<std::string> currentName;
  2031. int i = 0;
  2032. const int lastElement = static_cast<int>(name.size() - 1);
  2033. for (i = lastElement; i >= 0; --i) {
  2034. currentName.assign(name.begin(), name.begin() + i + 1);
  2035. sg = this->GetSourceGroup(currentName);
  2036. if (sg != nullptr) {
  2037. break;
  2038. }
  2039. }
  2040. // i now contains the index of the last found component
  2041. if (i == lastElement) {
  2042. // group already exists, replace its regular expression
  2043. if (regex && sg) {
  2044. // We only want to set the regular expression. If there are already
  2045. // source files in the group, we don't want to remove them.
  2046. sg->SetGroupRegex(regex);
  2047. }
  2048. return;
  2049. }
  2050. if (i == -1) {
  2051. // group does not exist nor belong to any existing group
  2052. // add its first component
  2053. this->SourceGroups.emplace_back(name[0], regex);
  2054. sg = this->GetSourceGroup(currentName);
  2055. i = 0; // last component found
  2056. }
  2057. if (!sg) {
  2058. cmSystemTools::Error("Could not create source group ");
  2059. return;
  2060. }
  2061. // build the whole source group path
  2062. for (++i; i <= lastElement; ++i) {
  2063. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  2064. sg = sg->LookupChild(name[i]);
  2065. }
  2066. sg->SetGroupRegex(regex);
  2067. }
  2068. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  2069. const std::vector<std::string>& folders)
  2070. {
  2071. cmSourceGroup* sg = this->GetSourceGroup(folders);
  2072. if (sg == nullptr) {
  2073. this->AddSourceGroup(folders);
  2074. sg = this->GetSourceGroup(folders);
  2075. }
  2076. return sg;
  2077. }
  2078. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  2079. {
  2080. std::string delimiters;
  2081. if (cmValue p = this->GetDefinition("SOURCE_GROUP_DELIMITER")) {
  2082. delimiters = *p;
  2083. } else {
  2084. delimiters = "/\\";
  2085. }
  2086. return this->GetOrCreateSourceGroup(cmTokenize(name, delimiters));
  2087. }
  2088. /**
  2089. * Find a source group whose regular expression matches the filename
  2090. * part of the given source name. Search backward through the list of
  2091. * source groups, and take the first matching group found. This way
  2092. * non-inherited SOURCE_GROUP commands will have precedence over
  2093. * inherited ones.
  2094. */
  2095. cmSourceGroup* cmMakefile::FindSourceGroup(
  2096. const std::string& source, std::vector<cmSourceGroup>& groups) const
  2097. {
  2098. // First search for a group that lists the file explicitly.
  2099. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2100. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  2101. if (result) {
  2102. return result;
  2103. }
  2104. }
  2105. // Now search for a group whose regex matches the file.
  2106. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2107. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  2108. if (result) {
  2109. return result;
  2110. }
  2111. }
  2112. // Shouldn't get here, but just in case, return the default group.
  2113. return groups.data();
  2114. }
  2115. #endif
  2116. static bool mightExpandVariablesCMP0019(const char* s)
  2117. {
  2118. return s && *s && strstr(s, "${") && strchr(s, '}');
  2119. }
  2120. void cmMakefile::ExpandVariablesCMP0019()
  2121. {
  2122. // Drop this ancient compatibility behavior with a policy.
  2123. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  2124. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  2125. return;
  2126. }
  2127. std::ostringstream w;
  2128. cmValue includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  2129. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2130. std::string dirs = *includeDirs;
  2131. this->ExpandVariablesInString(dirs, true, true);
  2132. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2133. /* clang-format off */
  2134. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  2135. << " " << *includeDirs << "\n"
  2136. << "as\n"
  2137. << " " << dirs << "\n";
  2138. /* clang-format on */
  2139. }
  2140. this->SetProperty("INCLUDE_DIRECTORIES", dirs);
  2141. }
  2142. // Also for each target's INCLUDE_DIRECTORIES property:
  2143. for (auto& target : this->Targets) {
  2144. cmTarget& t = target.second;
  2145. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  2146. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  2147. continue;
  2148. }
  2149. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  2150. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2151. std::string dirs = *includeDirs;
  2152. this->ExpandVariablesInString(dirs, true, true);
  2153. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2154. /* clang-format off */
  2155. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  2156. << " " << *includeDirs << "\n"
  2157. << "as\n"
  2158. << " " << dirs << "\n";
  2159. /* clang-format on */
  2160. }
  2161. t.SetProperty("INCLUDE_DIRECTORIES", dirs);
  2162. }
  2163. }
  2164. if (cmValue linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2165. if (mightExpandVariablesCMP0019(linkDirsProp->c_str())) {
  2166. std::string d = *linkDirsProp;
  2167. const std::string orig = d;
  2168. this->ExpandVariablesInString(d, true, true);
  2169. if (pol == cmPolicies::WARN && d != orig) {
  2170. /* clang-format off */
  2171. w << "Evaluated link directories\n"
  2172. << " " << orig << "\n"
  2173. << "as\n"
  2174. << " " << d << "\n";
  2175. /* clang-format on */
  2176. }
  2177. }
  2178. }
  2179. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2180. cmList linkLibs{ *linkLibsProp };
  2181. for (auto l = linkLibs.begin(); l != linkLibs.end(); ++l) {
  2182. std::string libName = *l;
  2183. if (libName == "optimized"_s || libName == "debug"_s) {
  2184. ++l;
  2185. libName = *l;
  2186. }
  2187. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2188. const std::string orig = libName;
  2189. this->ExpandVariablesInString(libName, true, true);
  2190. if (pol == cmPolicies::WARN && libName != orig) {
  2191. /* clang-format off */
  2192. w << "Evaluated link library\n"
  2193. << " " << orig << "\n"
  2194. << "as\n"
  2195. << " " << libName << "\n";
  2196. /* clang-format on */
  2197. }
  2198. }
  2199. }
  2200. }
  2201. if (!w.str().empty()) {
  2202. std::ostringstream m;
  2203. /* clang-format off */
  2204. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2205. << "\n"
  2206. << "The following variable evaluations were encountered:\n"
  2207. << w.str();
  2208. /* clang-format on */
  2209. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2210. m.str(), this->Backtrace);
  2211. }
  2212. }
  2213. bool cmMakefile::IsOn(const std::string& name) const
  2214. {
  2215. return this->GetDefinition(name).IsOn();
  2216. }
  2217. bool cmMakefile::IsSet(const std::string& name) const
  2218. {
  2219. cmValue value = this->GetDefinition(name);
  2220. if (!value) {
  2221. return false;
  2222. }
  2223. if (value->empty()) {
  2224. return false;
  2225. }
  2226. if (cmIsNOTFOUND(*value)) {
  2227. return false;
  2228. }
  2229. return true;
  2230. }
  2231. bool cmMakefile::PlatformIs32Bit() const
  2232. {
  2233. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2234. if (*plat_abi == "ELF X32"_s) {
  2235. return false;
  2236. }
  2237. }
  2238. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2239. return atoi(sizeof_dptr->c_str()) == 4;
  2240. }
  2241. return false;
  2242. }
  2243. bool cmMakefile::PlatformIs64Bit() const
  2244. {
  2245. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2246. return atoi(sizeof_dptr->c_str()) == 8;
  2247. }
  2248. return false;
  2249. }
  2250. bool cmMakefile::PlatformIsx32() const
  2251. {
  2252. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2253. if (*plat_abi == "ELF X32"_s) {
  2254. return true;
  2255. }
  2256. }
  2257. return false;
  2258. }
  2259. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2260. {
  2261. std::string sdkRoot;
  2262. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2263. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2264. struct
  2265. {
  2266. std::string name;
  2267. AppleSDK sdk;
  2268. } const sdkDatabase[]{
  2269. { "appletvos", AppleSDK::AppleTVOS },
  2270. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2271. { "iphoneos", AppleSDK::IPhoneOS },
  2272. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2273. { "watchos", AppleSDK::WatchOS },
  2274. { "watchsimulator", AppleSDK::WatchSimulator },
  2275. { "xros", AppleSDK::XROS },
  2276. { "xrsimulator", AppleSDK::XRSimulator },
  2277. };
  2278. for (auto const& entry : sdkDatabase) {
  2279. if (cmHasPrefix(sdkRoot, entry.name) ||
  2280. sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
  2281. return entry.sdk;
  2282. }
  2283. }
  2284. return AppleSDK::MacOS;
  2285. }
  2286. bool cmMakefile::PlatformIsAppleEmbedded() const
  2287. {
  2288. return this->GetAppleSDKType() != AppleSDK::MacOS;
  2289. }
  2290. bool cmMakefile::PlatformIsAppleSimulator() const
  2291. {
  2292. return std::set<AppleSDK>{
  2293. AppleSDK::AppleTVSimulator,
  2294. AppleSDK::IPhoneSimulator,
  2295. AppleSDK::WatchSimulator,
  2296. AppleSDK::XRSimulator,
  2297. }
  2298. .count(this->GetAppleSDKType());
  2299. }
  2300. bool cmMakefile::PlatformIsAppleCatalyst() const
  2301. {
  2302. std::string systemName;
  2303. systemName = this->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  2304. systemName = cmSystemTools::LowerCase(systemName);
  2305. return systemName == "ios" && this->GetAppleSDKType() == AppleSDK::MacOS;
  2306. }
  2307. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  2308. {
  2309. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  2310. }
  2311. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2312. {
  2313. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2314. if (!language.empty()) {
  2315. name += "_";
  2316. name += language;
  2317. }
  2318. name += "_FLAG";
  2319. return this->GetDefinition(name).GetCStr();
  2320. }
  2321. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2322. {
  2323. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2324. return true;
  2325. }
  2326. // If we are doing an in-source build, then the test will always fail
  2327. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2328. this->GetHomeOutputDirectory())) {
  2329. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2330. }
  2331. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2332. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2333. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2334. }
  2335. const std::string& cmMakefile::GetRequiredDefinition(
  2336. const std::string& name) const
  2337. {
  2338. static std::string const empty;
  2339. cmValue def = this->GetDefinition(name);
  2340. if (!def) {
  2341. cmSystemTools::Error("Error required internal CMake variable not "
  2342. "set, cmake may not be built correctly.\n"
  2343. "Missing variable is:\n" +
  2344. name);
  2345. return empty;
  2346. }
  2347. return *def;
  2348. }
  2349. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2350. {
  2351. cmValue def = this->StateSnapshot.GetDefinition(name);
  2352. if (!def) {
  2353. def = this->GetState()->GetInitializedCacheValue(name);
  2354. }
  2355. #ifndef CMAKE_BOOTSTRAP
  2356. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2357. if (!def) {
  2358. vv->VariableAccessed(
  2359. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2360. }
  2361. }
  2362. #endif
  2363. return def != nullptr;
  2364. }
  2365. bool cmMakefile::IsNormalDefinitionSet(const std::string& name) const
  2366. {
  2367. cmValue def = this->StateSnapshot.GetDefinition(name);
  2368. #ifndef CMAKE_BOOTSTRAP
  2369. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2370. if (!def) {
  2371. vv->VariableAccessed(
  2372. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2373. }
  2374. }
  2375. #endif
  2376. return def != nullptr;
  2377. }
  2378. cmValue cmMakefile::GetDefinition(const std::string& name) const
  2379. {
  2380. cmValue def = this->StateSnapshot.GetDefinition(name);
  2381. if (!def) {
  2382. def = this->GetState()->GetInitializedCacheValue(name);
  2383. }
  2384. #ifndef CMAKE_BOOTSTRAP
  2385. cmVariableWatch* vv = this->GetVariableWatch();
  2386. if (vv && !this->SuppressSideEffects) {
  2387. bool const watch_function_executed =
  2388. vv->VariableAccessed(name,
  2389. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2390. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2391. def.GetCStr(), this);
  2392. if (watch_function_executed) {
  2393. // A callback was executed and may have caused re-allocation of the
  2394. // variable storage. Look it up again for now.
  2395. // FIXME: Refactor variable storage to avoid this problem.
  2396. def = this->StateSnapshot.GetDefinition(name);
  2397. if (!def) {
  2398. def = this->GetState()->GetInitializedCacheValue(name);
  2399. }
  2400. }
  2401. }
  2402. #endif
  2403. return def;
  2404. }
  2405. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2406. {
  2407. return this->GetDefinition(name);
  2408. }
  2409. std::vector<std::string> cmMakefile::GetDefinitions() const
  2410. {
  2411. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2412. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2413. std::sort(res.begin(), res.end());
  2414. return res;
  2415. }
  2416. const std::string& cmMakefile::ExpandVariablesInString(
  2417. std::string& source) const
  2418. {
  2419. return this->ExpandVariablesInString(source, false, false);
  2420. }
  2421. const std::string& cmMakefile::ExpandVariablesInString(
  2422. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2423. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2424. {
  2425. bool compareResults = false;
  2426. MessageType mtype = MessageType::LOG;
  2427. std::string errorstr;
  2428. std::string original;
  2429. // Sanity check the @ONLY mode.
  2430. if (atOnly && (!noEscapes || !removeEmpty)) {
  2431. // This case should never be called. At-only is for
  2432. // configure-file/string which always does no escapes.
  2433. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2434. "ExpandVariablesInString @ONLY called "
  2435. "on something with escapes.");
  2436. return source;
  2437. }
  2438. // Variables used in the WARN case.
  2439. std::string newResult;
  2440. std::string newErrorstr;
  2441. MessageType newError = MessageType::LOG;
  2442. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2443. case cmPolicies::WARN: {
  2444. // Save the original string for the warning.
  2445. original = source;
  2446. newResult = source;
  2447. compareResults = true;
  2448. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2449. // dereferences since the OLD behavior is still what is actually used.
  2450. this->SuppressSideEffects = true;
  2451. newError = this->ExpandVariablesInStringNew(
  2452. newErrorstr, newResult, escapeQuotes, noEscapes, atOnly, filename,
  2453. line, replaceAt);
  2454. this->SuppressSideEffects = false;
  2455. CM_FALLTHROUGH;
  2456. }
  2457. case cmPolicies::OLD:
  2458. mtype = this->ExpandVariablesInStringOld(errorstr, source, escapeQuotes,
  2459. noEscapes, atOnly, filename,
  2460. line, removeEmpty, true);
  2461. break;
  2462. case cmPolicies::REQUIRED_IF_USED:
  2463. case cmPolicies::REQUIRED_ALWAYS:
  2464. // Messaging here would be *very* verbose.
  2465. case cmPolicies::NEW:
  2466. mtype = this->ExpandVariablesInStringNew(errorstr, source, escapeQuotes,
  2467. noEscapes, atOnly, filename,
  2468. line, replaceAt);
  2469. break;
  2470. }
  2471. // If it's an error in either case, just report the error...
  2472. if (mtype != MessageType::LOG) {
  2473. if (mtype == MessageType::FATAL_ERROR) {
  2474. cmSystemTools::SetFatalErrorOccurred();
  2475. }
  2476. this->IssueMessage(mtype, errorstr);
  2477. }
  2478. // ...otherwise, see if there's a difference that needs to be warned about.
  2479. else if (compareResults && (newResult != source || newError != mtype)) {
  2480. std::string msg =
  2481. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0053), '\n');
  2482. std::string msg_input = original;
  2483. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2484. msg += "For input:\n '";
  2485. msg += msg_input;
  2486. msg += "'\n";
  2487. std::string msg_old = source;
  2488. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2489. msg += "the old evaluation rules produce:\n '";
  2490. msg += msg_old;
  2491. msg += "'\n";
  2492. if (newError == mtype) {
  2493. std::string msg_new = newResult;
  2494. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2495. msg += "but the new evaluation rules produce:\n '";
  2496. msg += msg_new;
  2497. msg += "'\n";
  2498. } else {
  2499. std::string msg_err = newErrorstr;
  2500. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2501. msg += "but the new evaluation rules produce an error:\n ";
  2502. msg += msg_err;
  2503. msg += "\n";
  2504. }
  2505. msg +=
  2506. "Using the old result for compatibility since the policy is not set.";
  2507. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2508. }
  2509. return source;
  2510. }
  2511. MessageType cmMakefile::ExpandVariablesInStringOld(
  2512. std::string& errorstr, std::string& source, bool escapeQuotes,
  2513. bool noEscapes, bool atOnly, const char* filename, long line,
  2514. bool removeEmpty, bool replaceAt) const
  2515. {
  2516. // Fast path strings without any special characters.
  2517. if (source.find_first_of("$@\\") == std::string::npos) {
  2518. return MessageType::LOG;
  2519. }
  2520. // Special-case the @ONLY mode.
  2521. if (atOnly) {
  2522. // Store an original copy of the input.
  2523. std::string input = source;
  2524. // Start with empty output.
  2525. source.clear();
  2526. // Look for one @VAR@ at a time.
  2527. const char* in = input.c_str();
  2528. while (this->cmAtVarRegex.find(in)) {
  2529. // Get the range of the string to replace.
  2530. const char* first = in + this->cmAtVarRegex.start();
  2531. const char* last = in + this->cmAtVarRegex.end();
  2532. // Store the unchanged part of the string now.
  2533. source.append(in, first - in);
  2534. // Lookup the definition of VAR.
  2535. std::string var(first + 1, last - first - 2);
  2536. if (cmValue val = this->GetDefinition(var)) {
  2537. // Store the value in the output escaping as requested.
  2538. if (escapeQuotes) {
  2539. source.append(cmEscapeQuotes(*val));
  2540. } else {
  2541. source.append(*val);
  2542. }
  2543. }
  2544. // Continue looking for @VAR@ further along the string.
  2545. in = last;
  2546. }
  2547. // Append the rest of the unchanged part of the string.
  2548. source.append(in);
  2549. return MessageType::LOG;
  2550. }
  2551. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2552. // with GetDefinition(), if not found in the map, nothing is expanded.
  2553. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2554. // the current environment variables.
  2555. cmCommandArgumentParserHelper parser;
  2556. parser.SetMakefile(this);
  2557. parser.SetLineFile(line, filename);
  2558. parser.SetEscapeQuotes(escapeQuotes);
  2559. parser.SetNoEscapeMode(noEscapes);
  2560. parser.SetReplaceAtSyntax(replaceAt);
  2561. parser.SetRemoveEmpty(removeEmpty);
  2562. int res = parser.ParseString(source, 0);
  2563. const char* emsg = parser.GetError();
  2564. MessageType mtype = MessageType::LOG;
  2565. if (res && !emsg[0]) {
  2566. source = parser.GetResult();
  2567. } else {
  2568. // Construct the main error message.
  2569. std::ostringstream error;
  2570. error << "Syntax error in cmake code ";
  2571. if (filename && line > 0) {
  2572. // This filename and line number may be more specific than the
  2573. // command context because one command invocation can have
  2574. // arguments on multiple lines.
  2575. error << "at\n"
  2576. << " " << filename << ":" << line << "\n";
  2577. }
  2578. error << "when parsing string\n"
  2579. << " " << source << "\n";
  2580. error << emsg;
  2581. // If the parser failed ("res" is false) then this is a real
  2582. // argument parsing error, so the policy applies. Otherwise the
  2583. // parser reported an error message without failing because the
  2584. // helper implementation is unhappy, which has always reported an
  2585. // error.
  2586. mtype = MessageType::FATAL_ERROR;
  2587. if (!res) {
  2588. // This is a real argument parsing error. Use policy CMP0010 to
  2589. // decide whether it is an error.
  2590. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2591. case cmPolicies::WARN:
  2592. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2593. CM_FALLTHROUGH;
  2594. case cmPolicies::OLD:
  2595. // OLD behavior is to just warn and continue.
  2596. mtype = MessageType::AUTHOR_WARNING;
  2597. break;
  2598. case cmPolicies::REQUIRED_IF_USED:
  2599. case cmPolicies::REQUIRED_ALWAYS:
  2600. error << "\n"
  2601. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2602. break;
  2603. case cmPolicies::NEW:
  2604. // NEW behavior is to report the error.
  2605. break;
  2606. }
  2607. }
  2608. errorstr = error.str();
  2609. }
  2610. return mtype;
  2611. }
  2612. enum t_domain
  2613. {
  2614. NORMAL,
  2615. ENVIRONMENT,
  2616. CACHE
  2617. };
  2618. struct t_lookup
  2619. {
  2620. t_domain domain = NORMAL;
  2621. size_t loc = 0;
  2622. };
  2623. bool cmMakefile::IsProjectFile(const char* filename) const
  2624. {
  2625. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2626. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2627. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2628. }
  2629. size_t cmMakefile::GetRecursionDepthLimit() const
  2630. {
  2631. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2632. if (cmValue depthStr =
  2633. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2634. unsigned long depthUL;
  2635. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2636. depth = depthUL;
  2637. }
  2638. } else if (cm::optional<std::string> depthEnv =
  2639. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2640. unsigned long depthUL;
  2641. if (cmStrToULong(*depthEnv, &depthUL)) {
  2642. depth = depthUL;
  2643. }
  2644. }
  2645. return depth;
  2646. }
  2647. size_t cmMakefile::GetRecursionDepth() const
  2648. {
  2649. return this->RecursionDepth;
  2650. }
  2651. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2652. {
  2653. this->RecursionDepth = recursionDepth;
  2654. }
  2655. std::string cmMakefile::NewDeferId() const
  2656. {
  2657. return this->GetGlobalGenerator()->NewDeferId();
  2658. }
  2659. bool cmMakefile::DeferCall(std::string id, std::string file,
  2660. cmListFileFunction lff)
  2661. {
  2662. if (!this->Defer) {
  2663. return false;
  2664. }
  2665. this->Defer->Commands.emplace_back(
  2666. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2667. return true;
  2668. }
  2669. bool cmMakefile::DeferCancelCall(std::string const& id)
  2670. {
  2671. if (!this->Defer) {
  2672. return false;
  2673. }
  2674. for (DeferCommand& dc : this->Defer->Commands) {
  2675. if (dc.Id == id) {
  2676. dc.Id.clear();
  2677. }
  2678. }
  2679. return true;
  2680. }
  2681. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2682. {
  2683. cm::optional<std::string> ids;
  2684. if (this->Defer) {
  2685. ids = cmList::to_string(
  2686. cmMakeRange(this->Defer->Commands)
  2687. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2688. .transform(
  2689. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
  2690. }
  2691. return ids;
  2692. }
  2693. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2694. {
  2695. cm::optional<std::string> call;
  2696. if (this->Defer) {
  2697. std::string tmp;
  2698. for (DeferCommand const& dc : this->Defer->Commands) {
  2699. if (dc.Id == id) {
  2700. tmp = dc.Command.OriginalName();
  2701. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2702. tmp = cmStrCat(tmp, ';', arg.Value);
  2703. }
  2704. break;
  2705. }
  2706. }
  2707. call = std::move(tmp);
  2708. }
  2709. return call;
  2710. }
  2711. MessageType cmMakefile::ExpandVariablesInStringNew(
  2712. std::string& errorstr, std::string& source, bool escapeQuotes,
  2713. bool noEscapes, bool atOnly, const char* filename, long line,
  2714. bool replaceAt) const
  2715. {
  2716. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2717. // with GetDefinition(), if not found in the map, nothing is expanded.
  2718. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2719. // the current environment variables.
  2720. const char* in = source.c_str();
  2721. const char* last = in;
  2722. std::string result;
  2723. result.reserve(source.size());
  2724. std::vector<t_lookup> openstack;
  2725. bool error = false;
  2726. bool done = false;
  2727. MessageType mtype = MessageType::LOG;
  2728. cmState* state = this->GetCMakeInstance()->GetState();
  2729. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2730. do {
  2731. char inc = *in;
  2732. switch (inc) {
  2733. case '}':
  2734. if (!openstack.empty()) {
  2735. t_lookup var = openstack.back();
  2736. openstack.pop_back();
  2737. result.append(last, in - last);
  2738. std::string const& lookup = result.substr(var.loc);
  2739. cmValue value = nullptr;
  2740. std::string varresult;
  2741. std::string svalue;
  2742. switch (var.domain) {
  2743. case NORMAL:
  2744. if (filename && lookup == lineVar) {
  2745. cmListFileContext const& top = this->Backtrace.Top();
  2746. if (top.DeferId) {
  2747. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2748. } else {
  2749. varresult = std::to_string(line);
  2750. }
  2751. } else {
  2752. value = this->GetDefinition(lookup);
  2753. }
  2754. break;
  2755. case ENVIRONMENT:
  2756. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2757. value = cmValue(svalue);
  2758. }
  2759. break;
  2760. case CACHE:
  2761. value = state->GetCacheEntryValue(lookup);
  2762. break;
  2763. }
  2764. // Get the string we're meant to append to.
  2765. if (value) {
  2766. if (escapeQuotes) {
  2767. varresult = cmEscapeQuotes(*value);
  2768. } else {
  2769. varresult = *value;
  2770. }
  2771. } else if (!this->SuppressSideEffects) {
  2772. this->MaybeWarnUninitialized(lookup, filename);
  2773. }
  2774. result.replace(var.loc, result.size() - var.loc, varresult);
  2775. // Start looking from here on out.
  2776. last = in + 1;
  2777. }
  2778. break;
  2779. case '$':
  2780. if (!atOnly) {
  2781. t_lookup lookup;
  2782. const char* next = in + 1;
  2783. const char* start = nullptr;
  2784. char nextc = *next;
  2785. if (nextc == '{') {
  2786. // Looking for a variable.
  2787. start = in + 2;
  2788. lookup.domain = NORMAL;
  2789. } else if (nextc == '<') {
  2790. } else if (!nextc) {
  2791. result.append(last, next - last);
  2792. last = next;
  2793. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2794. // Looking for an environment variable.
  2795. start = in + 5;
  2796. lookup.domain = ENVIRONMENT;
  2797. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2798. // Looking for a cache variable.
  2799. start = in + 7;
  2800. lookup.domain = CACHE;
  2801. } else {
  2802. if (this->cmNamedCurly.find(next)) {
  2803. errorstr = "Syntax $" +
  2804. std::string(next, this->cmNamedCurly.end()) +
  2805. "{} is not supported. Only ${}, $ENV{}, "
  2806. "and $CACHE{} are allowed.";
  2807. mtype = MessageType::FATAL_ERROR;
  2808. error = true;
  2809. }
  2810. }
  2811. if (start) {
  2812. result.append(last, in - last);
  2813. last = start;
  2814. in = start - 1;
  2815. lookup.loc = result.size();
  2816. openstack.push_back(lookup);
  2817. }
  2818. break;
  2819. }
  2820. CM_FALLTHROUGH;
  2821. case '\\':
  2822. if (!noEscapes) {
  2823. const char* next = in + 1;
  2824. char nextc = *next;
  2825. if (nextc == 't') {
  2826. result.append(last, in - last);
  2827. result.push_back('\t');
  2828. last = next + 1;
  2829. } else if (nextc == 'n') {
  2830. result.append(last, in - last);
  2831. result.push_back('\n');
  2832. last = next + 1;
  2833. } else if (nextc == 'r') {
  2834. result.append(last, in - last);
  2835. result.push_back('\r');
  2836. last = next + 1;
  2837. } else if (nextc == ';' && openstack.empty()) {
  2838. // Handled in ExpandListArgument; pass the backslash literally.
  2839. } else if (isalnum(nextc) || nextc == '\0') {
  2840. errorstr += "Invalid character escape '\\";
  2841. if (nextc) {
  2842. errorstr += nextc;
  2843. errorstr += "'.";
  2844. } else {
  2845. errorstr += "' (at end of input).";
  2846. }
  2847. error = true;
  2848. } else {
  2849. // Take what we've found so far, skipping the escape character.
  2850. result.append(last, in - last);
  2851. // Start tracking from the next character.
  2852. last = in + 1;
  2853. }
  2854. // Skip the next character since it was escaped, but don't read past
  2855. // the end of the string.
  2856. if (*last) {
  2857. ++in;
  2858. }
  2859. }
  2860. break;
  2861. case '\n':
  2862. // Onto the next line.
  2863. ++line;
  2864. break;
  2865. case '\0':
  2866. done = true;
  2867. break;
  2868. case '@':
  2869. if (replaceAt) {
  2870. const char* nextAt = strchr(in + 1, '@');
  2871. if (nextAt && nextAt != in + 1 &&
  2872. nextAt ==
  2873. in + 1 +
  2874. strspn(in + 1,
  2875. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2876. "abcdefghijklmnopqrstuvwxyz"
  2877. "0123456789/_.+-")) {
  2878. std::string variable(in + 1, nextAt - in - 1);
  2879. std::string varresult;
  2880. if (filename && variable == lineVar) {
  2881. varresult = std::to_string(line);
  2882. } else {
  2883. cmValue def = this->GetDefinition(variable);
  2884. if (def) {
  2885. varresult = *def;
  2886. } else if (!this->SuppressSideEffects) {
  2887. this->MaybeWarnUninitialized(variable, filename);
  2888. }
  2889. }
  2890. if (escapeQuotes) {
  2891. varresult = cmEscapeQuotes(varresult);
  2892. }
  2893. // Skip over the variable.
  2894. result.append(last, in - last);
  2895. result.append(varresult);
  2896. in = nextAt;
  2897. last = in + 1;
  2898. break;
  2899. }
  2900. }
  2901. // Failed to find a valid @ expansion; treat it as literal.
  2902. CM_FALLTHROUGH;
  2903. default: {
  2904. if (!openstack.empty() &&
  2905. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2906. inc == '+' || inc == '-')) {
  2907. errorstr += "Invalid character (\'";
  2908. errorstr += inc;
  2909. result.append(last, in - last);
  2910. errorstr += cmStrCat("\') in a variable name: "
  2911. "'",
  2912. result.substr(openstack.back().loc), '\'');
  2913. mtype = MessageType::FATAL_ERROR;
  2914. error = true;
  2915. }
  2916. break;
  2917. }
  2918. }
  2919. // Look at the next character.
  2920. } while (!error && !done && *++in);
  2921. // Check for open variable references yet.
  2922. if (!error && !openstack.empty()) {
  2923. // There's an open variable reference waiting. Policy CMP0010 flags
  2924. // whether this is an error or not. The new parser now enforces
  2925. // CMP0010 as well.
  2926. errorstr += "There is an unterminated variable reference.";
  2927. error = true;
  2928. }
  2929. if (error) {
  2930. std::ostringstream emsg;
  2931. emsg << "Syntax error in cmake code ";
  2932. if (filename) {
  2933. // This filename and line number may be more specific than the
  2934. // command context because one command invocation can have
  2935. // arguments on multiple lines.
  2936. emsg << "at\n"
  2937. << " " << filename << ":" << line << "\n";
  2938. }
  2939. emsg << "when parsing string\n"
  2940. << " " << source << "\n";
  2941. emsg << errorstr;
  2942. mtype = MessageType::FATAL_ERROR;
  2943. errorstr = emsg.str();
  2944. } else {
  2945. // Append the rest of the unchanged part of the string.
  2946. result.append(last);
  2947. source = result;
  2948. }
  2949. return mtype;
  2950. }
  2951. void cmMakefile::RemoveVariablesInString(std::string& source,
  2952. bool atOnly) const
  2953. {
  2954. if (!atOnly) {
  2955. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2956. while (var.find(source)) {
  2957. source.erase(var.start(), var.end() - var.start());
  2958. }
  2959. }
  2960. if (!atOnly) {
  2961. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2962. while (varb.find(source)) {
  2963. source.erase(varb.start(), varb.end() - varb.start());
  2964. }
  2965. }
  2966. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2967. while (var2.find(source)) {
  2968. source.erase(var2.start(), var2.end() - var2.start());
  2969. }
  2970. }
  2971. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2972. {
  2973. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2974. return;
  2975. }
  2976. std::string initConfigs;
  2977. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2978. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2979. initConfigs = genDefault;
  2980. }
  2981. this->AddCacheDefinition(
  2982. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2983. "Semicolon separated list of supported configuration types, "
  2984. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2985. "anything else will be ignored.",
  2986. cmStateEnums::STRING);
  2987. }
  2988. std::string cmMakefile::GetDefaultConfiguration() const
  2989. {
  2990. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2991. return std::string{};
  2992. }
  2993. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2994. }
  2995. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2996. GeneratorConfigQuery mode) const
  2997. {
  2998. cmList configs;
  2999. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  3000. configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
  3001. } else if (mode != cmMakefile::OnlyMultiConfig) {
  3002. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  3003. if (!buildType.empty()) {
  3004. configs.emplace_back(buildType);
  3005. }
  3006. }
  3007. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  3008. configs.emplace_back();
  3009. }
  3010. return std::move(configs.data());
  3011. }
  3012. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  3013. cmExecutionStatus& status)
  3014. {
  3015. // if there are no blockers get out of here
  3016. if (this->FunctionBlockers.empty()) {
  3017. return false;
  3018. }
  3019. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  3020. }
  3021. void cmMakefile::PushFunctionBlockerBarrier()
  3022. {
  3023. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  3024. }
  3025. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  3026. {
  3027. // Remove any extra entries pushed on the barrier.
  3028. FunctionBlockersType::size_type barrier =
  3029. this->FunctionBlockerBarriers.back();
  3030. while (this->FunctionBlockers.size() > barrier) {
  3031. std::unique_ptr<cmFunctionBlocker> fb(
  3032. std::move(this->FunctionBlockers.top()));
  3033. this->FunctionBlockers.pop();
  3034. if (reportError) {
  3035. // Report the context in which the unclosed block was opened.
  3036. cmListFileContext const& lfc = fb->GetStartingContext();
  3037. std::ostringstream e;
  3038. /* clang-format off */
  3039. e << "A logical block opening on the line\n"
  3040. << " " << lfc << "\n"
  3041. << "is not closed.";
  3042. /* clang-format on */
  3043. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3044. reportError = false;
  3045. }
  3046. }
  3047. // Remove the barrier.
  3048. this->FunctionBlockerBarriers.pop_back();
  3049. }
  3050. void cmMakefile::PushLoopBlock()
  3051. {
  3052. assert(!this->LoopBlockCounter.empty());
  3053. this->LoopBlockCounter.top()++;
  3054. }
  3055. void cmMakefile::PopLoopBlock()
  3056. {
  3057. assert(!this->LoopBlockCounter.empty());
  3058. assert(this->LoopBlockCounter.top() > 0);
  3059. this->LoopBlockCounter.top()--;
  3060. }
  3061. void cmMakefile::PushLoopBlockBarrier()
  3062. {
  3063. this->LoopBlockCounter.push(0);
  3064. }
  3065. void cmMakefile::PopLoopBlockBarrier()
  3066. {
  3067. assert(!this->LoopBlockCounter.empty());
  3068. assert(this->LoopBlockCounter.top() == 0);
  3069. this->LoopBlockCounter.pop();
  3070. }
  3071. bool cmMakefile::IsLoopBlock() const
  3072. {
  3073. assert(!this->LoopBlockCounter.empty());
  3074. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  3075. }
  3076. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  3077. std::vector<std::string>& outArgs) const
  3078. {
  3079. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3080. std::string value;
  3081. outArgs.reserve(inArgs.size());
  3082. for (cmListFileArgument const& i : inArgs) {
  3083. // No expansion in a bracket argument.
  3084. if (i.Delim == cmListFileArgument::Bracket) {
  3085. outArgs.push_back(i.Value);
  3086. continue;
  3087. }
  3088. // Expand the variables in the argument.
  3089. value = i.Value;
  3090. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3091. i.Line, false, false);
  3092. // If the argument is quoted, it should be one argument.
  3093. // Otherwise, it may be a list of arguments.
  3094. if (i.Delim == cmListFileArgument::Quoted) {
  3095. outArgs.push_back(value);
  3096. } else {
  3097. cmExpandList(value, outArgs);
  3098. }
  3099. }
  3100. return !cmSystemTools::GetFatalErrorOccurred();
  3101. }
  3102. bool cmMakefile::ExpandArguments(
  3103. std::vector<cmListFileArgument> const& inArgs,
  3104. std::vector<cmExpandedCommandArgument>& outArgs) const
  3105. {
  3106. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3107. std::string value;
  3108. outArgs.reserve(inArgs.size());
  3109. for (cmListFileArgument const& i : inArgs) {
  3110. // No expansion in a bracket argument.
  3111. if (i.Delim == cmListFileArgument::Bracket) {
  3112. outArgs.emplace_back(i.Value, true);
  3113. continue;
  3114. }
  3115. // Expand the variables in the argument.
  3116. value = i.Value;
  3117. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3118. i.Line, false, false);
  3119. // If the argument is quoted, it should be one argument.
  3120. // Otherwise, it may be a list of arguments.
  3121. if (i.Delim == cmListFileArgument::Quoted) {
  3122. outArgs.emplace_back(value, true);
  3123. } else {
  3124. cmList stringArgs{ value };
  3125. for (std::string const& stringArg : stringArgs) {
  3126. outArgs.emplace_back(stringArg, false);
  3127. }
  3128. }
  3129. }
  3130. return !cmSystemTools::GetFatalErrorOccurred();
  3131. }
  3132. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  3133. {
  3134. if (!this->ExecutionStatusStack.empty()) {
  3135. // Record the context in which the blocker is created.
  3136. fb->SetStartingContext(this->Backtrace.Top());
  3137. }
  3138. this->FunctionBlockers.push(std::move(fb));
  3139. }
  3140. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  3141. {
  3142. assert(!this->FunctionBlockers.empty());
  3143. assert(this->FunctionBlockerBarriers.empty() ||
  3144. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  3145. auto b = std::move(this->FunctionBlockers.top());
  3146. this->FunctionBlockers.pop();
  3147. return b;
  3148. }
  3149. std::string const& cmMakefile::GetHomeDirectory() const
  3150. {
  3151. return this->GetCMakeInstance()->GetHomeDirectory();
  3152. }
  3153. std::string const& cmMakefile::GetHomeOutputDirectory() const
  3154. {
  3155. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3156. }
  3157. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  3158. {
  3159. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  3160. }
  3161. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  3162. {
  3163. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  3164. // this->MarkVariableAsUsed("CMAKE_ARGC");
  3165. for (unsigned int t = 0; t < args.size(); ++t) {
  3166. std::ostringstream tmpStream;
  3167. tmpStream << "CMAKE_ARGV" << t;
  3168. this->AddDefinition(tmpStream.str(), args[t]);
  3169. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  3170. }
  3171. }
  3172. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  3173. cmSourceFileLocationKind kind) const
  3174. {
  3175. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  3176. if (kind == cmSourceFileLocationKind::Known) {
  3177. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  3178. if (sfsi != this->KnownFileSearchIndex.end()) {
  3179. return sfsi->second;
  3180. }
  3181. }
  3182. cmSourceFileLocation sfl(this, sourceName, kind);
  3183. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  3184. #if defined(_WIN32) || defined(__APPLE__)
  3185. name = cmSystemTools::LowerCase(name);
  3186. #endif
  3187. auto sfsi = this->SourceFileSearchIndex.find(name);
  3188. if (sfsi != this->SourceFileSearchIndex.end()) {
  3189. for (auto* sf : sfsi->second) {
  3190. if (sf->Matches(sfl)) {
  3191. return sf;
  3192. }
  3193. }
  3194. }
  3195. return nullptr;
  3196. }
  3197. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  3198. bool generated,
  3199. cmSourceFileLocationKind kind)
  3200. {
  3201. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  3202. auto name =
  3203. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  3204. #if defined(_WIN32) || defined(__APPLE__)
  3205. name = cmSystemTools::LowerCase(name);
  3206. #endif
  3207. this->SourceFileSearchIndex[name].push_back(sf.get());
  3208. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  3209. if (kind == cmSourceFileLocationKind::Known) {
  3210. this->KnownFileSearchIndex[sourceName] = sf.get();
  3211. }
  3212. this->SourceFiles.push_back(std::move(sf));
  3213. return this->SourceFiles.back().get();
  3214. }
  3215. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  3216. bool generated,
  3217. cmSourceFileLocationKind kind)
  3218. {
  3219. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  3220. return esf;
  3221. }
  3222. return this->CreateSource(sourceName, generated, kind);
  3223. }
  3224. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  3225. const std::string& sourceName)
  3226. {
  3227. cmSourceFile* sf =
  3228. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  3229. sf->MarkAsGenerated(); // In case we did not create the source file.
  3230. return sf;
  3231. }
  3232. void cmMakefile::CreateGeneratedOutputs(
  3233. const std::vector<std::string>& outputs)
  3234. {
  3235. for (std::string const& o : outputs) {
  3236. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  3237. this->GetOrCreateGeneratedSource(o);
  3238. }
  3239. }
  3240. }
  3241. void cmMakefile::AddTargetObject(std::string const& tgtName,
  3242. std::string const& objFile)
  3243. {
  3244. cmSourceFile* sf =
  3245. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  3246. sf->SetObjectLibrary(tgtName);
  3247. sf->SetProperty("EXTERNAL_OBJECT", "1");
  3248. // TODO: Compute a language for this object based on the associated source
  3249. // file that compiles to it. Needs a policy as it likely affects link
  3250. // language selection if done unconditionally.
  3251. #if !defined(CMAKE_BOOTSTRAP)
  3252. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  3253. sf->ResolveFullPath());
  3254. #endif
  3255. }
  3256. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  3257. bool optional)
  3258. {
  3259. if (this->DeferRunning) {
  3260. this->IssueMessage(
  3261. MessageType::FATAL_ERROR,
  3262. "Languages may not be enabled during deferred execution.");
  3263. return;
  3264. }
  3265. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  3266. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  3267. }
  3268. std::vector<std::string> unique_languages;
  3269. {
  3270. std::vector<std::string> duplicate_languages;
  3271. for (std::string const& language : languages) {
  3272. if (!cm::contains(unique_languages, language)) {
  3273. unique_languages.push_back(language);
  3274. } else if (!cm::contains(duplicate_languages, language)) {
  3275. duplicate_languages.push_back(language);
  3276. }
  3277. }
  3278. if (!duplicate_languages.empty()) {
  3279. auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
  3280. this->IssueMessage(
  3281. MessageType::AUTHOR_WARNING,
  3282. cmStrCat("Languages to be enabled may not be specified more "
  3283. "than once at the same time. The following language",
  3284. quantity, " been specified multiple times: ",
  3285. cmJoin(duplicate_languages, ", ")));
  3286. }
  3287. }
  3288. // If RC is explicitly listed we need to do it after other languages.
  3289. // On some platforms we enable RC implicitly while enabling others.
  3290. // Do not let that look like recursive enable_language(RC).
  3291. std::vector<std::string> languages_without_RC;
  3292. std::vector<std::string> languages_for_RC;
  3293. languages_without_RC.reserve(unique_languages.size());
  3294. for (std::string const& language : unique_languages) {
  3295. if (language == "RC"_s) {
  3296. languages_for_RC.push_back(language);
  3297. } else {
  3298. languages_without_RC.push_back(language);
  3299. }
  3300. }
  3301. if (!languages_without_RC.empty()) {
  3302. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  3303. optional);
  3304. }
  3305. if (!languages_for_RC.empty()) {
  3306. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  3307. optional);
  3308. }
  3309. }
  3310. int cmMakefile::TryCompile(const std::string& srcdir,
  3311. const std::string& bindir,
  3312. const std::string& projectName,
  3313. const std::string& targetName, bool fast, int jobs,
  3314. const std::vector<std::string>* cmakeArgs,
  3315. std::string& output)
  3316. {
  3317. this->IsSourceFileTryCompile = fast;
  3318. // does the binary directory exist ? If not create it...
  3319. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3320. cmSystemTools::MakeDirectory(bindir);
  3321. }
  3322. // change to the tests directory and run cmake
  3323. // use the cmake object instead of calling cmake
  3324. cmWorkingDirectory workdir(bindir);
  3325. if (workdir.Failed()) {
  3326. this->IssueMessage(MessageType::FATAL_ERROR,
  3327. cmStrCat("Failed to set working directory to ", bindir,
  3328. " : ",
  3329. std::strerror(workdir.GetLastResult())));
  3330. cmSystemTools::SetFatalErrorOccurred();
  3331. this->IsSourceFileTryCompile = false;
  3332. return 1;
  3333. }
  3334. // make sure the same generator is used
  3335. // use this program as the cmake to be run, it should not
  3336. // be run that way but the cmake object requires a valid path
  3337. cmake cm(cmake::RoleProject, cmState::Project,
  3338. cmState::ProjectKind::TryCompile);
  3339. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3340. if (!gg) {
  3341. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3342. "Global generator '" +
  3343. this->GetGlobalGenerator()->GetName() +
  3344. "' could not be created.");
  3345. cmSystemTools::SetFatalErrorOccurred();
  3346. this->IsSourceFileTryCompile = false;
  3347. return 1;
  3348. }
  3349. gg->RecursionDepth = this->RecursionDepth;
  3350. cm.SetGlobalGenerator(std::move(gg));
  3351. // copy trace state
  3352. cm.SetTraceRedirect(this->GetCMakeInstance());
  3353. // do a configure
  3354. cm.SetHomeDirectory(srcdir);
  3355. cm.SetHomeOutputDirectory(bindir);
  3356. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3357. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3358. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3359. cm.LoadCache();
  3360. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  3361. if (cmValue config =
  3362. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3363. // Tell the single-configuration generator which one to use.
  3364. // Add this before the user-provided CMake arguments in case
  3365. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3366. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3367. cmStateEnums::STRING);
  3368. }
  3369. }
  3370. cmValue recursionDepth =
  3371. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3372. if (recursionDepth) {
  3373. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3374. "Maximum recursion depth", cmStateEnums::STRING);
  3375. }
  3376. // if cmake args were provided then pass them in
  3377. if (cmakeArgs) {
  3378. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3379. //
  3380. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  3381. // However, there is a subtle problem when certain arguments are passed to
  3382. // a macro wrapping around try_compile or try_run that does not escape
  3383. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3384. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3385. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3386. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3387. // the try_compile or try_run does not get the proper value of VAR. If we
  3388. // call SetArgs here then it would treat "b" as the source directory and
  3389. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3390. // does not exist", thus breaking the try_compile or try_run completely.
  3391. //
  3392. // Strictly speaking the bug is in the wrapper macro because the CMake
  3393. // language has always flattened nested lists and the macro should escape
  3394. // the semicolons in its arguments before forwarding them. However, this
  3395. // bug is so subtle that projects typically work anyway, usually because
  3396. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3397. // correct result. Calling SetArgs here would break such projects that
  3398. // previously built. Instead we work around the issue by never reporting
  3399. // unused arguments and ignoring options such as --no-warn-unused-cli.
  3400. cm.SetWarnUnusedCli(false);
  3401. // cm.SetArgs(*cmakeArgs, true);
  3402. cm.SetCacheArgs(*cmakeArgs);
  3403. }
  3404. // to save time we pass the EnableLanguage info directly
  3405. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  3406. this->GetGlobalGenerator(), this);
  3407. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3408. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3409. cmStateEnums::INTERNAL);
  3410. } else {
  3411. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3412. cmStateEnums::INTERNAL);
  3413. }
  3414. if (cm.Configure() != 0) {
  3415. this->IssueMessage(MessageType::FATAL_ERROR,
  3416. "Failed to configure test project build system.");
  3417. cmSystemTools::SetFatalErrorOccurred();
  3418. this->IsSourceFileTryCompile = false;
  3419. return 1;
  3420. }
  3421. if (cm.Generate() != 0) {
  3422. this->IssueMessage(MessageType::FATAL_ERROR,
  3423. "Failed to generate test project build system.");
  3424. cmSystemTools::SetFatalErrorOccurred();
  3425. this->IsSourceFileTryCompile = false;
  3426. return 1;
  3427. }
  3428. // finally call the generator to actually build the resulting project
  3429. int ret = this->GetGlobalGenerator()->TryCompile(
  3430. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3431. this->IsSourceFileTryCompile = false;
  3432. return ret;
  3433. }
  3434. bool cmMakefile::GetIsSourceFileTryCompile() const
  3435. {
  3436. return this->IsSourceFileTryCompile;
  3437. }
  3438. cmake* cmMakefile::GetCMakeInstance() const
  3439. {
  3440. return this->GlobalGenerator->GetCMakeInstance();
  3441. }
  3442. cmMessenger* cmMakefile::GetMessenger() const
  3443. {
  3444. return this->GetCMakeInstance()->GetMessenger();
  3445. }
  3446. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3447. {
  3448. return this->GlobalGenerator;
  3449. }
  3450. #ifndef CMAKE_BOOTSTRAP
  3451. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3452. {
  3453. if (this->GetCMakeInstance() &&
  3454. this->GetCMakeInstance()->GetVariableWatch()) {
  3455. return this->GetCMakeInstance()->GetVariableWatch();
  3456. }
  3457. return nullptr;
  3458. }
  3459. #endif
  3460. cmState* cmMakefile::GetState() const
  3461. {
  3462. return this->GetCMakeInstance()->GetState();
  3463. }
  3464. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3465. {
  3466. cmake* cm = this->GetCMakeInstance();
  3467. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3468. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3469. // directly be fed to the compiler, which will be confused.
  3470. return;
  3471. }
  3472. cm->UpdateProgress(message, s);
  3473. #ifdef CMake_ENABLE_DEBUGGER
  3474. if (cm->GetDebugAdapter() != nullptr) {
  3475. cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
  3476. }
  3477. #endif
  3478. }
  3479. std::string cmMakefile::GetModulesFile(cm::string_view filename, bool& system,
  3480. bool debug,
  3481. std::string& debugBuffer) const
  3482. {
  3483. std::string result;
  3484. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3485. // and then decide based on the policy setting which one to return.
  3486. // See CMP0017 for more details.
  3487. // The specific problem was that KDE 4.5.0 installs a
  3488. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3489. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3490. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3491. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3492. // new features, which were not there in the version from kdelibs, and so
  3493. // failed ("
  3494. std::string moduleInCMakeRoot;
  3495. std::string moduleInCMakeModulePath;
  3496. // Always search in CMAKE_MODULE_PATH:
  3497. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3498. if (cmakeModulePath) {
  3499. cmList modulePath{ *cmakeModulePath };
  3500. // Look through the possible module directories.
  3501. for (std::string itempl : modulePath) {
  3502. cmSystemTools::ConvertToUnixSlashes(itempl);
  3503. itempl += "/";
  3504. itempl += filename;
  3505. if (cmSystemTools::FileExists(itempl)) {
  3506. moduleInCMakeModulePath = itempl;
  3507. break;
  3508. }
  3509. if (debug) {
  3510. debugBuffer = cmStrCat(debugBuffer, " ", itempl, "\n");
  3511. }
  3512. }
  3513. }
  3514. // Always search in the standard modules location.
  3515. moduleInCMakeRoot =
  3516. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  3517. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3518. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3519. if (debug) {
  3520. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, "\n");
  3521. }
  3522. moduleInCMakeRoot.clear();
  3523. }
  3524. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3525. // from which we are being called is located itself in CMAKE_ROOT, then
  3526. // prefer results from CMAKE_ROOT depending on the policy setting.
  3527. system = false;
  3528. result = moduleInCMakeModulePath;
  3529. if (result.empty()) {
  3530. system = true;
  3531. result = moduleInCMakeRoot;
  3532. }
  3533. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3534. cmValue currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3535. std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
  3536. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  3537. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3538. case cmPolicies::WARN: {
  3539. std::ostringstream e;
  3540. /* clang-format off */
  3541. e << "File " << *currentFile << " includes "
  3542. << moduleInCMakeModulePath
  3543. << " (found via CMAKE_MODULE_PATH) which shadows "
  3544. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3545. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3546. /* clang-format on */
  3547. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3548. CM_FALLTHROUGH;
  3549. }
  3550. case cmPolicies::OLD:
  3551. system = false;
  3552. result = moduleInCMakeModulePath;
  3553. break;
  3554. case cmPolicies::REQUIRED_IF_USED:
  3555. case cmPolicies::REQUIRED_ALWAYS:
  3556. case cmPolicies::NEW:
  3557. system = true;
  3558. result = moduleInCMakeRoot;
  3559. break;
  3560. }
  3561. }
  3562. }
  3563. return result;
  3564. }
  3565. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3566. bool atOnly, bool escapeQuotes) const
  3567. {
  3568. // Split input to handle one line at a time.
  3569. std::string::const_iterator lineStart = input.begin();
  3570. while (lineStart != input.end()) {
  3571. // Find the end of this line.
  3572. std::string::const_iterator lineEnd = lineStart;
  3573. while (lineEnd != input.end() && *lineEnd != '\n') {
  3574. ++lineEnd;
  3575. }
  3576. // Copy the line.
  3577. std::string line(lineStart, lineEnd);
  3578. // Skip the newline character.
  3579. bool haveNewline = (lineEnd != input.end());
  3580. if (haveNewline) {
  3581. ++lineEnd;
  3582. }
  3583. // Replace #cmakedefine instances.
  3584. if (this->cmDefineRegex.find(line)) {
  3585. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3586. if (!def.IsOff()) {
  3587. const std::string indentation = this->cmDefineRegex.match(1);
  3588. cmSystemTools::ReplaceString(line,
  3589. cmStrCat("#", indentation, "cmakedefine"),
  3590. cmStrCat("#", indentation, "define"));
  3591. output += line;
  3592. } else {
  3593. output += "/* #undef ";
  3594. output += this->cmDefineRegex.match(2);
  3595. output += " */";
  3596. }
  3597. } else if (this->cmDefine01Regex.find(line)) {
  3598. const std::string indentation = this->cmDefine01Regex.match(1);
  3599. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3600. cmSystemTools::ReplaceString(line,
  3601. cmStrCat("#", indentation, "cmakedefine01"),
  3602. cmStrCat("#", indentation, "define"));
  3603. output += line;
  3604. if (!def.IsOff()) {
  3605. output += " 1";
  3606. } else {
  3607. output += " 0";
  3608. }
  3609. } else {
  3610. output += line;
  3611. }
  3612. if (haveNewline) {
  3613. output += "\n";
  3614. }
  3615. // Move to the next line.
  3616. lineStart = lineEnd;
  3617. }
  3618. // Perform variable replacements.
  3619. const char* filename = nullptr;
  3620. long lineNumber = -1;
  3621. if (!this->Backtrace.Empty()) {
  3622. const auto& currentTrace = this->Backtrace.Top();
  3623. filename = currentTrace.FilePath.c_str();
  3624. lineNumber = currentTrace.Line;
  3625. }
  3626. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3627. lineNumber, true, true);
  3628. }
  3629. int cmMakefile::ConfigureFile(const std::string& infile,
  3630. const std::string& outfile, bool copyonly,
  3631. bool atOnly, bool escapeQuotes,
  3632. mode_t permissions, cmNewLineStyle newLine)
  3633. {
  3634. int res = 1;
  3635. if (!this->CanIWriteThisFile(outfile)) {
  3636. cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
  3637. " into a source directory."));
  3638. return 0;
  3639. }
  3640. if (!cmSystemTools::FileExists(infile)) {
  3641. cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
  3642. return 0;
  3643. }
  3644. std::string soutfile = outfile;
  3645. const std::string& sinfile = infile;
  3646. this->AddCMakeDependFile(sinfile);
  3647. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3648. // Re-generate if non-temporary outputs are missing.
  3649. // when we finalize the configuration we will remove all
  3650. // output files that now don't exist.
  3651. this->AddCMakeOutputFile(soutfile);
  3652. if (permissions == 0) {
  3653. cmSystemTools::GetPermissions(sinfile, permissions);
  3654. }
  3655. std::string::size_type pos = soutfile.rfind('/');
  3656. if (pos != std::string::npos) {
  3657. std::string path = soutfile.substr(0, pos);
  3658. cmSystemTools::MakeDirectory(path);
  3659. }
  3660. if (copyonly) {
  3661. if (!cmSystemTools::CopyFileIfDifferent(sinfile, soutfile)) {
  3662. this->IssueMessage(MessageType::FATAL_ERROR,
  3663. cmSystemTools::GetLastSystemError());
  3664. return 0;
  3665. }
  3666. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3667. this->IssueMessage(MessageType::FATAL_ERROR,
  3668. cmSystemTools::GetLastSystemError());
  3669. return 0;
  3670. }
  3671. } else {
  3672. std::string newLineCharacters;
  3673. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3674. if (newLine.IsValid()) {
  3675. newLineCharacters = newLine.GetCharacters();
  3676. omode |= std::ios::binary;
  3677. } else {
  3678. newLineCharacters = "\n";
  3679. }
  3680. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3681. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3682. if (!fout) {
  3683. cmSystemTools::Error("Could not open file for write in copy operation " +
  3684. tempOutputFile);
  3685. cmSystemTools::ReportLastSystemError("");
  3686. return 0;
  3687. }
  3688. cmsys::ifstream fin(sinfile.c_str());
  3689. if (!fin) {
  3690. cmSystemTools::Error("Could not open file for read in copy operation " +
  3691. sinfile);
  3692. return 0;
  3693. }
  3694. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3695. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3696. std::ostringstream e;
  3697. e << "File starts with a Byte-Order-Mark that is not UTF-8:\n "
  3698. << sinfile;
  3699. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3700. return 0;
  3701. }
  3702. // rewind to copy BOM to output file
  3703. fin.seekg(0);
  3704. // now copy input to output and expand variables in the
  3705. // input file at the same time
  3706. std::string inLine;
  3707. std::string outLine;
  3708. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3709. outLine.clear();
  3710. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3711. fout << outLine << newLineCharacters;
  3712. }
  3713. // close the files before attempting to copy
  3714. fin.close();
  3715. fout.close();
  3716. if (!cmSystemTools::CopyFileIfDifferent(tempOutputFile, soutfile)) {
  3717. this->IssueMessage(MessageType::FATAL_ERROR,
  3718. cmSystemTools::GetLastSystemError());
  3719. res = 0;
  3720. } else {
  3721. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3722. this->IssueMessage(MessageType::FATAL_ERROR,
  3723. cmSystemTools::GetLastSystemError());
  3724. res = 0;
  3725. }
  3726. }
  3727. cmSystemTools::RemoveFile(tempOutputFile);
  3728. }
  3729. return res;
  3730. }
  3731. void cmMakefile::SetProperty(const std::string& prop, cmValue value)
  3732. {
  3733. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3734. }
  3735. void cmMakefile::AppendProperty(const std::string& prop,
  3736. const std::string& value, bool asString)
  3737. {
  3738. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3739. this->Backtrace);
  3740. }
  3741. cmValue cmMakefile::GetProperty(const std::string& prop) const
  3742. {
  3743. // Check for computed properties.
  3744. static std::string output;
  3745. if (prop == "TESTS"_s) {
  3746. std::vector<std::string> keys;
  3747. // get list of keys
  3748. const auto* t = this;
  3749. std::transform(
  3750. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3751. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3752. output = cmList::to_string(keys);
  3753. return cmValue(output);
  3754. }
  3755. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3756. }
  3757. cmValue cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3758. {
  3759. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3760. }
  3761. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3762. {
  3763. return this->GetProperty(prop).IsOn();
  3764. }
  3765. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3766. {
  3767. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3768. }
  3769. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3770. {
  3771. auto i = this->Targets.find(name);
  3772. if (i != this->Targets.end()) {
  3773. return &i->second;
  3774. }
  3775. return nullptr;
  3776. }
  3777. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3778. {
  3779. cmTest* test = this->GetTest(testName);
  3780. if (test) {
  3781. return test;
  3782. }
  3783. auto newTest = cm::make_unique<cmTest>(this);
  3784. test = newTest.get();
  3785. newTest->SetName(testName);
  3786. this->Tests[testName] = std::move(newTest);
  3787. return test;
  3788. }
  3789. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3790. {
  3791. auto mi = this->Tests.find(testName);
  3792. if (mi != this->Tests.end()) {
  3793. return mi->second.get();
  3794. }
  3795. return nullptr;
  3796. }
  3797. void cmMakefile::GetTests(const std::string& config,
  3798. std::vector<cmTest*>& tests) const
  3799. {
  3800. for (const auto& generator : this->GetTestGenerators()) {
  3801. if (generator->TestsForConfig(config)) {
  3802. tests.push_back(generator->GetTest());
  3803. }
  3804. }
  3805. }
  3806. void cmMakefile::AddCMakeDependFilesFromUser()
  3807. {
  3808. cmList deps;
  3809. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3810. deps.assign(*deps_str);
  3811. }
  3812. for (auto const& dep : deps) {
  3813. if (cmSystemTools::FileIsFullPath(dep)) {
  3814. this->AddCMakeDependFile(dep);
  3815. } else {
  3816. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3817. this->AddCMakeDependFile(f);
  3818. }
  3819. }
  3820. }
  3821. std::string cmMakefile::FormatListFileStack() const
  3822. {
  3823. std::vector<std::string> listFiles;
  3824. cmStateSnapshot snp = this->StateSnapshot;
  3825. while (snp.IsValid()) {
  3826. listFiles.push_back(snp.GetExecutionListFile());
  3827. snp = snp.GetCallStackParent();
  3828. }
  3829. std::reverse(listFiles.begin(), listFiles.end());
  3830. std::ostringstream tmp;
  3831. size_t depth = listFiles.size();
  3832. if (depth > 0) {
  3833. auto it = listFiles.end();
  3834. do {
  3835. if (depth != listFiles.size()) {
  3836. tmp << "\n ";
  3837. }
  3838. --it;
  3839. tmp << "[";
  3840. tmp << depth;
  3841. tmp << "]\t";
  3842. tmp << *it;
  3843. depth--;
  3844. } while (it != listFiles.begin());
  3845. }
  3846. return tmp.str();
  3847. }
  3848. void cmMakefile::PushScope()
  3849. {
  3850. this->StateSnapshot =
  3851. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3852. this->PushLoopBlockBarrier();
  3853. #if !defined(CMAKE_BOOTSTRAP)
  3854. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3855. #endif
  3856. }
  3857. void cmMakefile::PopScope()
  3858. {
  3859. #if !defined(CMAKE_BOOTSTRAP)
  3860. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3861. #endif
  3862. this->PopLoopBlockBarrier();
  3863. this->PopSnapshot();
  3864. }
  3865. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3866. {
  3867. if (var.empty()) {
  3868. return;
  3869. }
  3870. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3871. std::ostringstream m;
  3872. m << "Cannot set \"" << var << "\": current scope has no parent.";
  3873. this->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  3874. return;
  3875. }
  3876. #ifndef CMAKE_BOOTSTRAP
  3877. cmVariableWatch* vv = this->GetVariableWatch();
  3878. if (vv) {
  3879. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3880. varDef, this);
  3881. }
  3882. #endif
  3883. }
  3884. void cmMakefile::RaiseScope(const std::vector<std::string>& variables)
  3885. {
  3886. for (auto const& varName : variables) {
  3887. if (this->IsNormalDefinitionSet(varName)) {
  3888. this->RaiseScope(varName, this->GetDefinition(varName));
  3889. } else {
  3890. // unset variable in parent scope
  3891. this->RaiseScope(varName, nullptr);
  3892. }
  3893. }
  3894. }
  3895. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3896. cmStateEnums::TargetType type,
  3897. bool global)
  3898. {
  3899. // Create the target.
  3900. std::unique_ptr<cmTarget> target(
  3901. new cmTarget(name, type,
  3902. global ? cmTarget::Visibility::ImportedGlobally
  3903. : cmTarget::Visibility::Imported,
  3904. this, cmTarget::PerConfig::Yes));
  3905. // Add to the set of available imported targets.
  3906. this->ImportedTargets[name] = target.get();
  3907. this->GetGlobalGenerator()->IndexTarget(target.get());
  3908. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3909. // Transfer ownership to this cmMakefile object.
  3910. this->ImportedTargetsOwned.push_back(std::move(target));
  3911. return this->ImportedTargetsOwned.back().get();
  3912. }
  3913. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3914. bool excludeAliases) const
  3915. {
  3916. // Look for an imported target. These take priority because they
  3917. // are more local in scope and do not have to be globally unique.
  3918. auto targetName = name;
  3919. if (!excludeAliases) {
  3920. // Look for local alias targets.
  3921. auto alias = this->AliasTargets.find(name);
  3922. if (alias != this->AliasTargets.end()) {
  3923. targetName = alias->second;
  3924. }
  3925. }
  3926. auto imported = this->ImportedTargets.find(targetName);
  3927. if (imported != this->ImportedTargets.end()) {
  3928. return imported->second;
  3929. }
  3930. // Look for a target built in this directory.
  3931. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3932. return t;
  3933. }
  3934. // Look for a target built in this project.
  3935. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3936. }
  3937. bool cmMakefile::IsAlias(const std::string& name) const
  3938. {
  3939. if (cm::contains(this->AliasTargets, name)) {
  3940. return true;
  3941. }
  3942. return this->GetGlobalGenerator()->IsAlias(name);
  3943. }
  3944. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3945. bool isCustom) const
  3946. {
  3947. if (this->IsAlias(name)) {
  3948. std::ostringstream e;
  3949. e << "cannot create target \"" << name
  3950. << "\" because an alias with the same name already exists.";
  3951. msg = e.str();
  3952. return false;
  3953. }
  3954. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3955. // The name given conflicts with an existing target. Produce an
  3956. // error in a compatible way.
  3957. if (existing->IsImported()) {
  3958. // Imported targets were not supported in previous versions.
  3959. // This is new code, so we can make it an error.
  3960. std::ostringstream e;
  3961. e << "cannot create target \"" << name
  3962. << "\" because an imported target with the same name already exists.";
  3963. msg = e.str();
  3964. return false;
  3965. }
  3966. // target names must be globally unique
  3967. switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
  3968. case cmPolicies::WARN:
  3969. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3970. cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
  3971. CM_FALLTHROUGH;
  3972. case cmPolicies::OLD:
  3973. return true;
  3974. case cmPolicies::REQUIRED_IF_USED:
  3975. case cmPolicies::REQUIRED_ALWAYS:
  3976. this->IssueMessage(
  3977. MessageType::FATAL_ERROR,
  3978. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
  3979. return true;
  3980. case cmPolicies::NEW:
  3981. break;
  3982. }
  3983. // The conflict is with a non-imported target.
  3984. // Allow this if the user has requested support.
  3985. cmake* cm = this->GetCMakeInstance();
  3986. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3987. this != existing->GetMakefile() &&
  3988. cm->GetState()->GetGlobalPropertyAsBool(
  3989. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3990. return true;
  3991. }
  3992. // Produce an error that tells the user how to work around the
  3993. // problem.
  3994. std::ostringstream e;
  3995. e << "cannot create target \"" << name
  3996. << "\" because another target with the same name already exists. "
  3997. << "The existing target is ";
  3998. switch (existing->GetType()) {
  3999. case cmStateEnums::EXECUTABLE:
  4000. e << "an executable ";
  4001. break;
  4002. case cmStateEnums::STATIC_LIBRARY:
  4003. e << "a static library ";
  4004. break;
  4005. case cmStateEnums::SHARED_LIBRARY:
  4006. e << "a shared library ";
  4007. break;
  4008. case cmStateEnums::MODULE_LIBRARY:
  4009. e << "a module library ";
  4010. break;
  4011. case cmStateEnums::UTILITY:
  4012. e << "a custom target ";
  4013. break;
  4014. case cmStateEnums::INTERFACE_LIBRARY:
  4015. e << "an interface library ";
  4016. break;
  4017. default:
  4018. break;
  4019. }
  4020. e << "created in source directory \""
  4021. << existing->GetMakefile()->GetCurrentSourceDirectory() << "\". "
  4022. << "See documentation for policy CMP0002 for more details.";
  4023. msg = e.str();
  4024. return false;
  4025. }
  4026. return true;
  4027. }
  4028. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  4029. const std::string& binPath) const
  4030. {
  4031. // Make sure the binary directory is unique.
  4032. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  4033. if (gg->BinaryDirectoryIsNew(binPath)) {
  4034. return true;
  4035. }
  4036. std::ostringstream e;
  4037. switch (this->GetPolicyStatus(cmPolicies::CMP0013)) {
  4038. case cmPolicies::WARN:
  4039. // Print the warning.
  4040. /* clang-format off */
  4041. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0013)
  4042. << "\n"
  4043. << "The binary directory\n"
  4044. << " " << binPath << "\n"
  4045. << "is already used to build a source directory. "
  4046. << "This command uses it to build source directory\n"
  4047. << " " << srcPath << "\n"
  4048. << "which can generate conflicting build files. "
  4049. << "CMake does not support this use case but it used "
  4050. << "to work accidentally and is being allowed for "
  4051. << "compatibility.";
  4052. /* clang-format on */
  4053. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  4054. CM_FALLTHROUGH;
  4055. case cmPolicies::OLD:
  4056. // OLD behavior does not warn.
  4057. return true;
  4058. case cmPolicies::REQUIRED_IF_USED:
  4059. case cmPolicies::REQUIRED_ALWAYS:
  4060. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0013) << "\n";
  4061. CM_FALLTHROUGH;
  4062. case cmPolicies::NEW:
  4063. // NEW behavior prints the error.
  4064. /* clang-format off */
  4065. e << "The binary directory\n"
  4066. << " " << binPath << "\n"
  4067. << "is already used to build a source directory. "
  4068. << "It cannot be used to build source directory\n"
  4069. << " " << srcPath << "\n"
  4070. << "Specify a unique binary directory name.";
  4071. /* clang-format on */
  4072. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4073. break;
  4074. }
  4075. return false;
  4076. }
  4077. static std::string const matchVariables[] = {
  4078. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  4079. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  4080. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  4081. };
  4082. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  4083. void cmMakefile::ClearMatches()
  4084. {
  4085. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  4086. if (!nMatchesStr) {
  4087. return;
  4088. }
  4089. int nMatches = atoi(nMatchesStr->c_str());
  4090. for (int i = 0; i <= nMatches; i++) {
  4091. std::string const& var = matchVariables[i];
  4092. std::string const& s = this->GetSafeDefinition(var);
  4093. if (!s.empty()) {
  4094. this->AddDefinition(var, "");
  4095. this->MarkVariableAsUsed(var);
  4096. }
  4097. }
  4098. this->AddDefinition(nMatchesVariable, "0");
  4099. this->MarkVariableAsUsed(nMatchesVariable);
  4100. }
  4101. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  4102. {
  4103. char highest = 0;
  4104. for (int i = 0; i < 10; i++) {
  4105. std::string const& m = re.match(i);
  4106. if (!m.empty()) {
  4107. std::string const& var = matchVariables[i];
  4108. this->AddDefinition(var, m);
  4109. this->MarkVariableAsUsed(var);
  4110. highest = static_cast<char>('0' + i);
  4111. }
  4112. }
  4113. char nMatches[] = { highest, '\0' };
  4114. this->AddDefinition(nMatchesVariable, nMatches);
  4115. this->MarkVariableAsUsed(nMatchesVariable);
  4116. }
  4117. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  4118. {
  4119. return this->StateSnapshot;
  4120. }
  4121. const char* cmMakefile::GetDefineFlagsCMP0059() const
  4122. {
  4123. return this->DefineFlagsOrig.c_str();
  4124. }
  4125. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  4126. bool parent_scope) const
  4127. {
  4128. return this->StateSnapshot.GetPolicy(id, parent_scope);
  4129. }
  4130. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  4131. {
  4132. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  4133. if (cmValue val = this->GetDefinition(var)) {
  4134. return val.IsOn();
  4135. }
  4136. // Enable optional policy warnings with --debug-output, --trace,
  4137. // or --trace-expand.
  4138. cmake* cm = this->GetCMakeInstance();
  4139. return cm->GetDebugOutput() || cm->GetTrace();
  4140. }
  4141. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  4142. {
  4143. cmPolicies::PolicyID pid;
  4144. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  4145. std::ostringstream e;
  4146. e << "Policy \"" << id << "\" is not known to this version of CMake.";
  4147. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4148. return false;
  4149. }
  4150. return this->SetPolicy(pid, status);
  4151. }
  4152. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  4153. cmPolicies::PolicyStatus status)
  4154. {
  4155. // A REQUIRED_ALWAYS policy may be set only to NEW.
  4156. if (status != cmPolicies::NEW &&
  4157. cmPolicies::GetPolicyStatus(id) == cmPolicies::REQUIRED_ALWAYS) {
  4158. std::string msg = cmPolicies::GetRequiredAlwaysPolicyError(id);
  4159. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  4160. return false;
  4161. }
  4162. // Deprecate old policies.
  4163. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0129 &&
  4164. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  4165. (
  4166. // Policies set by cmCoreTryCompile::TryCompileCode.
  4167. id == cmPolicies::CMP0065 || id == cmPolicies::CMP0083 ||
  4168. id == cmPolicies::CMP0091 || id == cmPolicies::CMP0104 ||
  4169. id == cmPolicies::CMP0123 || id == cmPolicies::CMP0126 ||
  4170. id == cmPolicies::CMP0128)) &&
  4171. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  4172. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  4173. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  4174. cmPolicies::GetPolicyDeprecatedWarning(id));
  4175. }
  4176. this->StateSnapshot.SetPolicy(id, status);
  4177. return true;
  4178. }
  4179. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  4180. : Makefile(m)
  4181. {
  4182. this->Makefile->PushPolicy();
  4183. }
  4184. cmMakefile::PolicyPushPop::~PolicyPushPop()
  4185. {
  4186. this->Makefile->PopPolicy();
  4187. }
  4188. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  4189. {
  4190. this->StateSnapshot.PushPolicy(pm, weak);
  4191. }
  4192. void cmMakefile::PopPolicy()
  4193. {
  4194. if (!this->StateSnapshot.PopPolicy()) {
  4195. this->IssueMessage(MessageType::FATAL_ERROR,
  4196. "cmake_policy POP without matching PUSH");
  4197. }
  4198. }
  4199. void cmMakefile::PopSnapshot(bool reportError)
  4200. {
  4201. // cmStateSnapshot manages nested policy scopes within it.
  4202. // Since the scope corresponding to the snapshot is closing,
  4203. // reject any still-open nested policy scopes with an error.
  4204. while (this->StateSnapshot.CanPopPolicyScope()) {
  4205. if (reportError) {
  4206. this->IssueMessage(MessageType::FATAL_ERROR,
  4207. "cmake_policy PUSH without matching POP");
  4208. reportError = false;
  4209. }
  4210. this->PopPolicy();
  4211. }
  4212. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  4213. assert(this->StateSnapshot.IsValid());
  4214. }
  4215. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  4216. std::string const& version_max)
  4217. {
  4218. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  4219. cmPolicies::WarnCompat::On);
  4220. }
  4221. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  4222. : Makefile(m)
  4223. {
  4224. this->Makefile->StateSnapshot =
  4225. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  4226. this->Makefile->StateSnapshot);
  4227. }
  4228. cmMakefile::VariablePushPop::~VariablePushPop()
  4229. {
  4230. this->Makefile->PopSnapshot();
  4231. }
  4232. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  4233. cmListFileContext const& context) const
  4234. {
  4235. return !this->CMP0054ReportedIds.insert(context).second;
  4236. }
  4237. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  4238. {
  4239. /* Record the setting of every policy. */
  4240. using PolicyID = cmPolicies::PolicyID;
  4241. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  4242. pid = static_cast<PolicyID>(pid + 1)) {
  4243. pm.Set(pid, this->GetPolicyStatus(pid));
  4244. }
  4245. }
  4246. bool cmMakefile::IgnoreErrorsCMP0061() const
  4247. {
  4248. bool ignoreErrors = true;
  4249. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  4250. case cmPolicies::WARN:
  4251. // No warning for this policy!
  4252. CM_FALLTHROUGH;
  4253. case cmPolicies::OLD:
  4254. break;
  4255. case cmPolicies::REQUIRED_IF_USED:
  4256. case cmPolicies::REQUIRED_ALWAYS:
  4257. case cmPolicies::NEW:
  4258. ignoreErrors = false;
  4259. break;
  4260. }
  4261. return ignoreErrors;
  4262. }
  4263. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  4264. const std::string& fileName,
  4265. cmPolicies::PolicyMap const& pm)
  4266. : Makefile(mf)
  4267. {
  4268. this->Makefile->PushFunctionScope(fileName, pm);
  4269. }
  4270. cmMakefile::FunctionPushPop::~FunctionPushPop()
  4271. {
  4272. this->Makefile->PopFunctionScope(this->ReportError);
  4273. }
  4274. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  4275. const std::string& fileName,
  4276. const cmPolicies::PolicyMap& pm)
  4277. : Makefile(mf)
  4278. {
  4279. this->Makefile->PushMacroScope(fileName, pm);
  4280. }
  4281. cmMakefile::MacroPushPop::~MacroPushPop()
  4282. {
  4283. this->Makefile->PopMacroScope(this->ReportError);
  4284. }
  4285. cmMakefile::FindPackageStackRAII::FindPackageStackRAII(cmMakefile* mf,
  4286. std::string const& name)
  4287. : Makefile(mf)
  4288. {
  4289. this->Makefile->FindPackageStack =
  4290. this->Makefile->FindPackageStack.Push(cmFindPackageCall{
  4291. name,
  4292. this->Makefile->FindPackageStackNextIndex,
  4293. });
  4294. this->Makefile->FindPackageStackNextIndex++;
  4295. }
  4296. cmMakefile::FindPackageStackRAII::~FindPackageStackRAII()
  4297. {
  4298. this->Makefile->FindPackageStackNextIndex =
  4299. this->Makefile->FindPackageStack.Top().Index + 1;
  4300. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  4301. if (!this->Makefile->FindPackageStack.Empty()) {
  4302. auto top = this->Makefile->FindPackageStack.Top();
  4303. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  4304. top.Index = this->Makefile->FindPackageStackNextIndex;
  4305. this->Makefile->FindPackageStackNextIndex++;
  4306. this->Makefile->FindPackageStack =
  4307. this->Makefile->FindPackageStack.Push(top);
  4308. }
  4309. }
  4310. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  4311. std::string const& pkg)
  4312. : Makefile(mf)
  4313. , OldValue(this->Makefile->DebugFindPkg)
  4314. {
  4315. this->Makefile->DebugFindPkg =
  4316. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  4317. }
  4318. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  4319. {
  4320. this->Makefile->DebugFindPkg = this->OldValue;
  4321. }
  4322. bool cmMakefile::GetDebugFindPkgMode() const
  4323. {
  4324. return this->DebugFindPkg;
  4325. }