cmMakefile.cxx 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840
  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"] = (missing == CommandMissingFromStack::Yes ? 1 : 0) +
  327. static_cast<Json::Value::UInt64>(this->ExecutionStatusStack.size());
  328. val["global_frame"] = (missing == CommandMissingFromStack::Yes ? 1 : 0) +
  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. // Find the target to which to add the custom command.
  1010. auto ti = this->Targets.find(target);
  1011. if (ti == this->Targets.end()) {
  1012. MessageType messageType = MessageType::AUTHOR_WARNING;
  1013. bool issueMessage = false;
  1014. std::ostringstream e;
  1015. switch (this->GetPolicyStatus(cmPolicies::CMP0040)) {
  1016. case cmPolicies::WARN:
  1017. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
  1018. issueMessage = true;
  1019. CM_FALLTHROUGH;
  1020. case cmPolicies::OLD:
  1021. break;
  1022. case cmPolicies::NEW:
  1023. case cmPolicies::REQUIRED_IF_USED:
  1024. case cmPolicies::REQUIRED_ALWAYS:
  1025. issueMessage = true;
  1026. messageType = MessageType::FATAL_ERROR;
  1027. break;
  1028. }
  1029. if (issueMessage) {
  1030. if (cmTarget const* t = this->FindTargetToUse(target)) {
  1031. if (t->IsImported()) {
  1032. e << "TARGET '" << target
  1033. << "' is IMPORTED and does not build here.";
  1034. } else {
  1035. e << "TARGET '" << target << "' was not created in this directory.";
  1036. }
  1037. } else {
  1038. e << "No TARGET '" << target
  1039. << "' has been created in this directory.";
  1040. }
  1041. this->GetCMakeInstance()->IssueMessage(messageType, e.str(), lfbt);
  1042. }
  1043. return nullptr;
  1044. }
  1045. cmTarget* t = &ti->second;
  1046. if (objLibCommands == cmObjectLibraryCommands::Reject &&
  1047. t->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1048. std::ostringstream e;
  1049. e << "Target \"" << target
  1050. << "\" is an OBJECT library "
  1051. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  1052. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1053. lfbt);
  1054. return nullptr;
  1055. }
  1056. if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1057. std::ostringstream e;
  1058. e << "Target \"" << target
  1059. << "\" is an INTERFACE library "
  1060. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  1061. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1062. lfbt);
  1063. return nullptr;
  1064. }
  1065. return t;
  1066. }
  1067. cmTarget* cmMakefile::AddCustomCommandToTarget(
  1068. const std::string& target, cmCustomCommandType type,
  1069. std::unique_ptr<cmCustomCommand> cc)
  1070. {
  1071. const auto& byproducts = cc->GetByproducts();
  1072. const auto& commandLines = cc->GetCommandLines();
  1073. cmTarget* t = this->GetCustomCommandTarget(
  1074. target, cmObjectLibraryCommands::Reject, this->Backtrace);
  1075. // Validate custom commands.
  1076. if (!t || !this->ValidateCustomCommand(commandLines)) {
  1077. return t;
  1078. }
  1079. // Always create the byproduct sources and mark them generated.
  1080. this->CreateGeneratedOutputs(byproducts);
  1081. cc->RecordPolicyValues(this->GetStateSnapshot());
  1082. // Dispatch command creation to allow generator expressions in outputs.
  1083. this->AddGeneratorAction(
  1084. std::move(cc),
  1085. [this, t, type](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1086. std::unique_ptr<cmCustomCommand> tcc) {
  1087. BacktraceGuard guard(this->Backtrace, lfbt);
  1088. tcc->SetBacktrace(lfbt);
  1089. detail::AddCustomCommandToTarget(lg, cmCommandOrigin::Project, t, type,
  1090. std::move(tcc));
  1091. });
  1092. return t;
  1093. }
  1094. void cmMakefile::AddCustomCommandToOutput(
  1095. std::unique_ptr<cmCustomCommand> cc, const CommandSourceCallback& callback,
  1096. bool replace)
  1097. {
  1098. const auto& outputs = cc->GetOutputs();
  1099. const auto& byproducts = cc->GetByproducts();
  1100. const auto& commandLines = cc->GetCommandLines();
  1101. // Make sure there is at least one output.
  1102. if (outputs.empty()) {
  1103. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  1104. return;
  1105. }
  1106. // Validate custom commands.
  1107. if (!this->ValidateCustomCommand(commandLines)) {
  1108. return;
  1109. }
  1110. // Always create the output sources and mark them generated.
  1111. this->CreateGeneratedOutputs(outputs);
  1112. this->CreateGeneratedOutputs(byproducts);
  1113. cc->RecordPolicyValues(this->GetStateSnapshot());
  1114. // Dispatch command creation to allow generator expressions in outputs.
  1115. this->AddGeneratorAction(
  1116. std::move(cc),
  1117. [this, replace, callback](cmLocalGenerator& lg,
  1118. const cmListFileBacktrace& lfbt,
  1119. std::unique_ptr<cmCustomCommand> tcc) {
  1120. BacktraceGuard guard(this->Backtrace, lfbt);
  1121. tcc->SetBacktrace(lfbt);
  1122. cmSourceFile* sf = detail::AddCustomCommandToOutput(
  1123. lg, cmCommandOrigin::Project, std::move(tcc), replace);
  1124. if (callback && sf) {
  1125. callback(sf);
  1126. }
  1127. });
  1128. }
  1129. void cmMakefile::AddCustomCommandOldStyle(
  1130. const std::string& target, const std::vector<std::string>& outputs,
  1131. const std::vector<std::string>& depends, const std::string& source,
  1132. const cmCustomCommandLines& commandLines, const char* comment)
  1133. {
  1134. auto cc = cm::make_unique<cmCustomCommand>();
  1135. cc->SetDepends(depends);
  1136. cc->SetCommandLines(commandLines);
  1137. cc->SetComment(comment);
  1138. // Translate the old-style signature to one of the new-style
  1139. // signatures.
  1140. if (source == target) {
  1141. // In the old-style signature if the source and target were the
  1142. // same then it added a post-build rule to the target. Preserve
  1143. // this behavior.
  1144. this->AddCustomCommandToTarget(target, cmCustomCommandType::POST_BUILD,
  1145. std::move(cc));
  1146. return;
  1147. }
  1148. auto ti = this->Targets.find(target);
  1149. cmTarget* t = ti != this->Targets.end() ? &ti->second : nullptr;
  1150. auto addRuleFileToTarget = [=](cmSourceFile* sf) {
  1151. // If the rule was added to the source (and not a .rule file),
  1152. // then add the source to the target to make sure the rule is
  1153. // included.
  1154. if (!sf->GetPropertyAsBool("__CMAKE_RULE")) {
  1155. if (t) {
  1156. t->AddSource(sf->ResolveFullPath());
  1157. } else {
  1158. cmSystemTools::Error("Attempt to add a custom rule to a target "
  1159. "that does not exist yet for target " +
  1160. target);
  1161. }
  1162. }
  1163. };
  1164. // Each output must get its own copy of this rule.
  1165. cmsys::RegularExpression sourceFiles(
  1166. "\\.(C|M|c|c\\+\\+|cc|cpp|cxx|mpp|ixx|cppm|ccm|cxxm|c\\+\\+m|cu|m|mm|"
  1167. "rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
  1168. "hm|hpp|hxx|in|txx|inl)$");
  1169. // Choose whether to use a main dependency.
  1170. if (sourceFiles.find(source)) {
  1171. // The source looks like a real file. Use it as the main dependency.
  1172. for (std::string const& output : outputs) {
  1173. auto cc1 = cm::make_unique<cmCustomCommand>(*cc);
  1174. cc1->SetOutputs(output);
  1175. cc1->SetMainDependency(source);
  1176. this->AddCustomCommandToOutput(std::move(cc1), addRuleFileToTarget);
  1177. }
  1178. } else {
  1179. cc->AppendDepends({ source });
  1180. // The source may not be a real file. Do not use a main dependency.
  1181. for (std::string const& output : outputs) {
  1182. auto cc1 = cm::make_unique<cmCustomCommand>(*cc);
  1183. cc1->SetOutputs(output);
  1184. this->AddCustomCommandToOutput(std::move(cc1), addRuleFileToTarget);
  1185. }
  1186. }
  1187. }
  1188. void cmMakefile::AppendCustomCommandToOutput(
  1189. const std::string& output, const std::vector<std::string>& depends,
  1190. const cmImplicitDependsList& implicit_depends,
  1191. const cmCustomCommandLines& commandLines)
  1192. {
  1193. // Validate custom commands.
  1194. if (this->ValidateCustomCommand(commandLines)) {
  1195. // Dispatch command creation to allow generator expressions in outputs.
  1196. this->AddGeneratorAction(
  1197. [this, output, depends, implicit_depends,
  1198. commandLines](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt) {
  1199. BacktraceGuard guard(this->Backtrace, lfbt);
  1200. detail::AppendCustomCommandToOutput(lg, lfbt, output, depends,
  1201. implicit_depends, commandLines);
  1202. });
  1203. }
  1204. }
  1205. cmTarget* cmMakefile::AddUtilityCommand(const std::string& utilityName,
  1206. bool excludeFromAll,
  1207. std::unique_ptr<cmCustomCommand> cc)
  1208. {
  1209. const auto& depends = cc->GetDepends();
  1210. const auto& byproducts = cc->GetByproducts();
  1211. const auto& commandLines = cc->GetCommandLines();
  1212. cmTarget* target = this->AddNewUtilityTarget(utilityName, excludeFromAll);
  1213. // Validate custom commands.
  1214. if ((commandLines.empty() && depends.empty()) ||
  1215. !this->ValidateCustomCommand(commandLines)) {
  1216. return target;
  1217. }
  1218. // Always create the byproduct sources and mark them generated.
  1219. this->CreateGeneratedOutputs(byproducts);
  1220. cc->RecordPolicyValues(this->GetStateSnapshot());
  1221. // Dispatch command creation to allow generator expressions in outputs.
  1222. this->AddGeneratorAction(
  1223. std::move(cc),
  1224. [this, target](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1225. std::unique_ptr<cmCustomCommand> tcc) {
  1226. BacktraceGuard guard(this->Backtrace, lfbt);
  1227. tcc->SetBacktrace(lfbt);
  1228. detail::AddUtilityCommand(lg, cmCommandOrigin::Project, target,
  1229. std::move(tcc));
  1230. });
  1231. return target;
  1232. }
  1233. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1234. {
  1235. // remove any \n\r
  1236. std::string::size_type initSize = dflags.size();
  1237. dflags += ' ';
  1238. dflags += flag;
  1239. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1240. std::replace(flagStart, dflags.end(), '\n', ' ');
  1241. std::replace(flagStart, dflags.end(), '\r', ' ');
  1242. }
  1243. void cmMakefile::AddDefineFlag(std::string const& flag)
  1244. {
  1245. if (flag.empty()) {
  1246. return;
  1247. }
  1248. // Update the string used for the old DEFINITIONS property.
  1249. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1250. // If this is really a definition, update COMPILE_DEFINITIONS.
  1251. if (this->ParseDefineFlag(flag, false)) {
  1252. return;
  1253. }
  1254. // Add this flag that does not look like a definition.
  1255. s_AddDefineFlag(flag, this->DefineFlags);
  1256. }
  1257. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1258. {
  1259. std::string::size_type const len = flag.length();
  1260. // Remove all instances of the flag that are surrounded by
  1261. // whitespace or the beginning/end of the string.
  1262. for (std::string::size_type lpos = dflags.find(flag, 0);
  1263. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1264. std::string::size_type rpos = lpos + len;
  1265. if ((lpos <= 0 || isspace(dflags[lpos - 1])) &&
  1266. (rpos >= dflags.size() || isspace(dflags[rpos]))) {
  1267. dflags.erase(lpos, len);
  1268. } else {
  1269. ++lpos;
  1270. }
  1271. }
  1272. }
  1273. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1274. {
  1275. // Check the length of the flag to remove.
  1276. if (flag.empty()) {
  1277. return;
  1278. }
  1279. // Update the string used for the old DEFINITIONS property.
  1280. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1281. // If this is really a definition, update COMPILE_DEFINITIONS.
  1282. if (this->ParseDefineFlag(flag, true)) {
  1283. return;
  1284. }
  1285. // Remove this flag that does not look like a definition.
  1286. s_RemoveDefineFlag(flag, this->DefineFlags);
  1287. }
  1288. void cmMakefile::AddCompileDefinition(std::string const& option)
  1289. {
  1290. this->AppendProperty("COMPILE_DEFINITIONS", option);
  1291. }
  1292. void cmMakefile::AddCompileOption(std::string const& option)
  1293. {
  1294. this->AppendProperty("COMPILE_OPTIONS", option);
  1295. }
  1296. void cmMakefile::AddLinkOption(std::string const& option)
  1297. {
  1298. this->AppendProperty("LINK_OPTIONS", option);
  1299. }
  1300. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1301. {
  1302. if (before) {
  1303. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
  1304. BT<std::string>(directory, this->Backtrace));
  1305. } else {
  1306. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
  1307. BT<std::string>(directory, this->Backtrace));
  1308. }
  1309. }
  1310. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1311. {
  1312. // Create a regular expression to match valid definitions.
  1313. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1314. // Make sure the definition matches.
  1315. if (!valid.find(def)) {
  1316. return false;
  1317. }
  1318. // Definitions with non-trivial values require a policy check.
  1319. static cmsys::RegularExpression trivial(
  1320. "^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
  1321. if (!trivial.find(def)) {
  1322. // This definition has a non-trivial value.
  1323. switch (this->GetPolicyStatus(cmPolicies::CMP0005)) {
  1324. case cmPolicies::WARN:
  1325. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1326. cmPolicies::GetPolicyWarning(cmPolicies::CMP0005));
  1327. CM_FALLTHROUGH;
  1328. case cmPolicies::OLD:
  1329. // OLD behavior is to not escape the value. We should not
  1330. // convert the definition to use the property.
  1331. return false;
  1332. case cmPolicies::REQUIRED_IF_USED:
  1333. case cmPolicies::REQUIRED_ALWAYS:
  1334. this->IssueMessage(
  1335. MessageType::FATAL_ERROR,
  1336. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005));
  1337. return false;
  1338. case cmPolicies::NEW:
  1339. // NEW behavior is to escape the value. Proceed to convert it
  1340. // to an entry in the property.
  1341. break;
  1342. }
  1343. }
  1344. // Get the definition part after the flag.
  1345. const char* define = def.c_str() + 2;
  1346. if (remove) {
  1347. if (cmValue cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1348. // Expand the list.
  1349. cmList defs{ *cdefs };
  1350. // Recompose the list without the definition.
  1351. defs.remove_items({ define });
  1352. // Store the new list.
  1353. this->SetProperty("COMPILE_DEFINITIONS", defs.to_string());
  1354. }
  1355. } else {
  1356. // Append the definition to the directory property.
  1357. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1358. }
  1359. return true;
  1360. }
  1361. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1362. {
  1363. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1364. // define flags
  1365. this->DefineFlags = parent->DefineFlags;
  1366. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1367. // Include transform property. There is no per-config version.
  1368. {
  1369. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1370. this->SetProperty(prop, parent->GetProperty(prop));
  1371. }
  1372. // compile definitions property and per-config versions
  1373. cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
  1374. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1375. this->SetProperty("COMPILE_DEFINITIONS",
  1376. parent->GetProperty("COMPILE_DEFINITIONS"));
  1377. std::vector<std::string> configs =
  1378. this->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  1379. for (std::string const& config : configs) {
  1380. std::string defPropName =
  1381. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  1382. cmValue prop = parent->GetProperty(defPropName);
  1383. this->SetProperty(defPropName, prop);
  1384. }
  1385. }
  1386. // labels
  1387. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1388. // link libraries
  1389. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1390. // the initial project name
  1391. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1392. // Copy include regular expressions.
  1393. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1394. // Imported targets.
  1395. this->ImportedTargets = parent->ImportedTargets;
  1396. // Non-global Alias targets.
  1397. this->AliasTargets = parent->AliasTargets;
  1398. // Recursion depth.
  1399. this->RecursionDepth = parent->RecursionDepth;
  1400. }
  1401. void cmMakefile::AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g)
  1402. {
  1403. if (g) {
  1404. this->InstallGenerators.push_back(std::move(g));
  1405. }
  1406. }
  1407. void cmMakefile::AddTestGenerator(std::unique_ptr<cmTestGenerator> g)
  1408. {
  1409. if (g) {
  1410. this->TestGenerators.push_back(std::move(g));
  1411. }
  1412. }
  1413. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1414. const cmPolicies::PolicyMap& pm)
  1415. {
  1416. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1417. this->StateSnapshot, fileName);
  1418. assert(this->StateSnapshot.IsValid());
  1419. this->PushLoopBlockBarrier();
  1420. #if !defined(CMAKE_BOOTSTRAP)
  1421. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1422. #endif
  1423. this->PushFunctionBlockerBarrier();
  1424. this->PushPolicy(true, pm);
  1425. }
  1426. void cmMakefile::PopFunctionScope(bool reportError)
  1427. {
  1428. this->PopPolicy();
  1429. this->PopSnapshot(reportError);
  1430. this->PopFunctionBlockerBarrier(reportError);
  1431. #if !defined(CMAKE_BOOTSTRAP)
  1432. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1433. #endif
  1434. this->PopLoopBlockBarrier();
  1435. }
  1436. void cmMakefile::PushMacroScope(std::string const& fileName,
  1437. const cmPolicies::PolicyMap& pm)
  1438. {
  1439. this->StateSnapshot =
  1440. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1441. assert(this->StateSnapshot.IsValid());
  1442. this->PushFunctionBlockerBarrier();
  1443. this->PushPolicy(true, pm);
  1444. }
  1445. void cmMakefile::PopMacroScope(bool reportError)
  1446. {
  1447. this->PopPolicy();
  1448. this->PopSnapshot(reportError);
  1449. this->PopFunctionBlockerBarrier(reportError);
  1450. }
  1451. bool cmMakefile::IsRootMakefile() const
  1452. {
  1453. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1454. }
  1455. class cmMakefile::BuildsystemFileScope
  1456. {
  1457. public:
  1458. BuildsystemFileScope(cmMakefile* mf)
  1459. : Makefile(mf)
  1460. {
  1461. std::string currentStart =
  1462. cmStrCat(this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource(),
  1463. "/CMakeLists.txt");
  1464. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1465. this->Makefile->StateSnapshot =
  1466. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1467. this->Makefile->StateSnapshot);
  1468. this->Makefile->PushFunctionBlockerBarrier();
  1469. this->GG = mf->GetGlobalGenerator();
  1470. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1471. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1472. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1473. this->GG->SetCurrentMakefile(mf);
  1474. #if !defined(CMAKE_BOOTSTRAP)
  1475. this->GG->GetFileLockPool().PushFileScope();
  1476. #endif
  1477. }
  1478. ~BuildsystemFileScope()
  1479. {
  1480. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1481. this->Makefile->PopSnapshot(this->ReportError);
  1482. #if !defined(CMAKE_BOOTSTRAP)
  1483. this->GG->GetFileLockPool().PopFileScope();
  1484. #endif
  1485. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1486. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1487. }
  1488. void Quiet() { this->ReportError = false; }
  1489. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1490. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1491. private:
  1492. cmMakefile* Makefile;
  1493. cmGlobalGenerator* GG;
  1494. cmMakefile* CurrentMakefile;
  1495. cmStateSnapshot Snapshot;
  1496. bool ReportError = true;
  1497. };
  1498. void cmMakefile::Configure()
  1499. {
  1500. std::string currentStart = cmStrCat(
  1501. this->StateSnapshot.GetDirectory().GetCurrentSource(), "/CMakeLists.txt");
  1502. // Add the bottom of all backtraces within this directory.
  1503. // We will never pop this scope because it should be available
  1504. // for messages during the generate step too.
  1505. this->Backtrace =
  1506. this->Backtrace.Push(cmListFileContext::FromListFilePath(currentStart));
  1507. BuildsystemFileScope scope(this);
  1508. // make sure the CMakeFiles dir is there
  1509. std::string filesDir = cmStrCat(
  1510. this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles");
  1511. cmSystemTools::MakeDirectory(filesDir);
  1512. assert(cmSystemTools::FileExists(currentStart, true));
  1513. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart);
  1514. #ifdef CMake_ENABLE_DEBUGGER
  1515. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1516. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  1517. this, currentStart);
  1518. }
  1519. #endif
  1520. cmListFile listFile;
  1521. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1522. this->Backtrace)) {
  1523. #ifdef CMake_ENABLE_DEBUGGER
  1524. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1525. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1526. }
  1527. #endif
  1528. return;
  1529. }
  1530. #ifdef CMake_ENABLE_DEBUGGER
  1531. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1532. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1533. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  1534. currentStart, listFile.Functions);
  1535. }
  1536. #endif
  1537. if (this->IsRootMakefile()) {
  1538. bool hasVersion = false;
  1539. // search for the right policy command
  1540. for (cmListFileFunction const& func : listFile.Functions) {
  1541. if (func.LowerCaseName() == "cmake_minimum_required"_s) {
  1542. hasVersion = true;
  1543. break;
  1544. }
  1545. }
  1546. // if no policy command is found this is an error if they use any
  1547. // non advanced functions or a lot of functions
  1548. if (!hasVersion) {
  1549. bool isProblem = true;
  1550. if (listFile.Functions.size() < 30) {
  1551. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1552. // these commands must have backwards compatibility forever and
  1553. // and that is a lot longer than your tiny mind can comprehend mortal
  1554. std::set<std::string> allowedCommands;
  1555. allowedCommands.insert("project");
  1556. allowedCommands.insert("set");
  1557. allowedCommands.insert("if");
  1558. allowedCommands.insert("endif");
  1559. allowedCommands.insert("else");
  1560. allowedCommands.insert("elseif");
  1561. allowedCommands.insert("add_executable");
  1562. allowedCommands.insert("add_library");
  1563. allowedCommands.insert("target_link_libraries");
  1564. allowedCommands.insert("option");
  1565. allowedCommands.insert("message");
  1566. isProblem = false;
  1567. for (cmListFileFunction const& func : listFile.Functions) {
  1568. if (!cm::contains(allowedCommands, func.LowerCaseName())) {
  1569. isProblem = true;
  1570. break;
  1571. }
  1572. }
  1573. }
  1574. if (isProblem) {
  1575. // Tell the top level cmMakefile to diagnose
  1576. // this violation of CMP0000.
  1577. this->SetCheckCMP0000(true);
  1578. // Implicitly set the version for the user.
  1579. cmPolicies::ApplyPolicyVersion(this, 2, 4, 0,
  1580. cmPolicies::WarnCompat::Off);
  1581. }
  1582. }
  1583. bool hasProject = false;
  1584. // search for a project command
  1585. for (cmListFileFunction const& func : listFile.Functions) {
  1586. if (func.LowerCaseName() == "project"_s) {
  1587. hasProject = true;
  1588. break;
  1589. }
  1590. }
  1591. // if no project command is found, add one
  1592. if (!hasProject) {
  1593. this->GetCMakeInstance()->IssueMessage(
  1594. MessageType::AUTHOR_WARNING,
  1595. "No project() command is present. The top-level CMakeLists.txt "
  1596. "file must contain a literal, direct call to the project() command. "
  1597. "Add a line of code such as\n"
  1598. " project(ProjectName)\n"
  1599. "near the top of the file, but after cmake_minimum_required().\n"
  1600. "CMake is pretending there is a \"project(Project)\" command on "
  1601. "the first line.",
  1602. this->Backtrace);
  1603. cmListFileFunction project{ "project",
  1604. 0,
  1605. 0,
  1606. { { "Project", cmListFileArgument::Unquoted,
  1607. 0 },
  1608. { "__CMAKE_INJECTED_PROJECT_COMMAND__",
  1609. cmListFileArgument::Unquoted, 0 } } };
  1610. listFile.Functions.insert(listFile.Functions.begin(), project);
  1611. }
  1612. }
  1613. this->Defer = cm::make_unique<DeferCommands>();
  1614. this->RunListFile(listFile, currentStart, this->Defer.get());
  1615. this->Defer.reset();
  1616. if (cmSystemTools::GetFatalErrorOccurred()) {
  1617. scope.Quiet();
  1618. }
  1619. // at the end handle any old style subdirs
  1620. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1621. // for each subdir recurse
  1622. auto sdi = subdirs.begin();
  1623. for (; sdi != subdirs.end(); ++sdi) {
  1624. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1625. this->ConfigureSubDirectory(*sdi);
  1626. }
  1627. this->AddCMakeDependFilesFromUser();
  1628. }
  1629. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1630. {
  1631. mf->InitializeFromParent(this);
  1632. std::string currentStart = mf->GetCurrentSourceDirectory();
  1633. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1634. std::string msg = cmStrCat(" Entering ", currentStart);
  1635. cmSystemTools::Message(msg);
  1636. }
  1637. std::string const currentStartFile =
  1638. cmStrCat(currentStart, "/CMakeLists.txt");
  1639. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1640. // The file is missing. Check policy CMP0014.
  1641. std::ostringstream e;
  1642. /* clang-format off */
  1643. e << "The source directory\n"
  1644. << " " << currentStart << "\n"
  1645. << "does not contain a CMakeLists.txt file.";
  1646. /* clang-format on */
  1647. switch (this->GetPolicyStatus(cmPolicies::CMP0014)) {
  1648. case cmPolicies::WARN:
  1649. // Print the warning.
  1650. /* clang-format off */
  1651. e << "\n"
  1652. << "CMake does not support this case but it used "
  1653. << "to work accidentally and is being allowed for "
  1654. << "compatibility."
  1655. << "\n"
  1656. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
  1657. /* clang-format on */
  1658. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1659. CM_FALLTHROUGH;
  1660. case cmPolicies::OLD:
  1661. // OLD behavior does not warn.
  1662. break;
  1663. case cmPolicies::REQUIRED_IF_USED:
  1664. case cmPolicies::REQUIRED_ALWAYS:
  1665. e << "\n" << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
  1666. CM_FALLTHROUGH;
  1667. case cmPolicies::NEW:
  1668. // NEW behavior prints the error.
  1669. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1670. break;
  1671. }
  1672. return;
  1673. }
  1674. // finally configure the subdir
  1675. mf->Configure();
  1676. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1677. std::string msg =
  1678. cmStrCat(" Returning to ", this->GetCurrentSourceDirectory());
  1679. cmSystemTools::Message(msg);
  1680. }
  1681. }
  1682. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1683. const std::string& binPath,
  1684. bool excludeFromAll, bool immediate,
  1685. bool system)
  1686. {
  1687. if (this->DeferRunning) {
  1688. this->IssueMessage(
  1689. MessageType::FATAL_ERROR,
  1690. "Subdirectories may not be created during deferred execution.");
  1691. return;
  1692. }
  1693. // Make sure the binary directory is unique.
  1694. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1695. return;
  1696. }
  1697. cmStateSnapshot newSnapshot =
  1698. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1699. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1700. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1701. cmSystemTools::MakeDirectory(binPath);
  1702. auto subMfu =
  1703. cm::make_unique<cmMakefile>(this->GlobalGenerator, newSnapshot);
  1704. auto* subMf = subMfu.get();
  1705. this->GetGlobalGenerator()->AddMakefile(std::move(subMfu));
  1706. if (excludeFromAll) {
  1707. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1708. }
  1709. if (system) {
  1710. subMf->SetProperty("SYSTEM", "TRUE");
  1711. }
  1712. if (immediate) {
  1713. this->ConfigureSubDirectory(subMf);
  1714. } else {
  1715. this->UnConfiguredDirectories.push_back(subMf);
  1716. }
  1717. this->AddInstallGenerator(cm::make_unique<cmInstallSubdirectoryGenerator>(
  1718. subMf, binPath, this->GetBacktrace()));
  1719. }
  1720. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1721. {
  1722. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1723. }
  1724. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1725. {
  1726. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1727. }
  1728. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1729. {
  1730. std::vector<cmTarget*> tgts;
  1731. tgts.reserve(this->ImportedTargets.size());
  1732. for (auto const& impTarget : this->ImportedTargets) {
  1733. tgts.push_back(impTarget.second);
  1734. }
  1735. return tgts;
  1736. }
  1737. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1738. bool before)
  1739. {
  1740. if (incs.empty()) {
  1741. return;
  1742. }
  1743. std::string entryString = cmList::to_string(incs);
  1744. if (before) {
  1745. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1746. BT<std::string>(entryString, this->Backtrace));
  1747. } else {
  1748. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1749. BT<std::string>(entryString, this->Backtrace));
  1750. }
  1751. // Property on each target:
  1752. for (auto& target : this->Targets) {
  1753. cmTarget& t = target.second;
  1754. t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
  1755. }
  1756. }
  1757. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1758. {
  1759. if (incs.empty()) {
  1760. return;
  1761. }
  1762. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1763. for (auto& target : this->Targets) {
  1764. cmTarget& t = target.second;
  1765. t.AddSystemIncludeDirectories(incs);
  1766. }
  1767. }
  1768. void cmMakefile::AddDefinition(const std::string& name, cm::string_view value)
  1769. {
  1770. this->StateSnapshot.SetDefinition(name, value);
  1771. #ifndef CMAKE_BOOTSTRAP
  1772. cmVariableWatch* vv = this->GetVariableWatch();
  1773. if (vv) {
  1774. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1775. value.data(), this);
  1776. }
  1777. #endif
  1778. }
  1779. void cmMakefile::AddDefinitionBool(const std::string& name, bool value)
  1780. {
  1781. this->AddDefinition(name, value ? "ON" : "OFF");
  1782. }
  1783. void cmMakefile::AddCacheDefinition(const std::string& name, cmValue value,
  1784. cmValue doc,
  1785. cmStateEnums::CacheEntryType type,
  1786. bool force)
  1787. {
  1788. cmValue existingValue = this->GetState()->GetInitializedCacheValue(name);
  1789. // must be outside the following if() to keep it alive long enough
  1790. std::string nvalue;
  1791. if (existingValue &&
  1792. (this->GetState()->GetCacheEntryType(name) ==
  1793. cmStateEnums::UNINITIALIZED)) {
  1794. // if this is not a force, then use the value from the cache
  1795. // if it is a force, then use the value being passed in
  1796. if (!force) {
  1797. value = existingValue;
  1798. }
  1799. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1800. cmList files(value);
  1801. for (auto& file : files) {
  1802. if (!cmIsOff(file)) {
  1803. file = cmSystemTools::CollapseFullPath(file);
  1804. }
  1805. }
  1806. nvalue = files.to_string();
  1807. value = cmValue{ nvalue };
  1808. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1809. value = this->GetState()->GetInitializedCacheValue(name);
  1810. }
  1811. }
  1812. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1813. switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
  1814. case cmPolicies::WARN:
  1815. if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
  1816. this->IsNormalDefinitionSet(name)) {
  1817. this->IssueMessage(
  1818. MessageType::AUTHOR_WARNING,
  1819. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0126),
  1820. "\nFor compatibility with older versions of CMake, normal "
  1821. "variable \"",
  1822. name, "\" will be removed from the current scope."));
  1823. }
  1824. CM_FALLTHROUGH;
  1825. case cmPolicies::OLD:
  1826. // if there was a definition then remove it
  1827. this->StateSnapshot.RemoveDefinition(name);
  1828. break;
  1829. case cmPolicies::NEW:
  1830. case cmPolicies::REQUIRED_IF_USED:
  1831. case cmPolicies::REQUIRED_ALWAYS:
  1832. break;
  1833. }
  1834. }
  1835. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1836. {
  1837. this->StateSnapshot.GetDefinition(var);
  1838. }
  1839. bool cmMakefile::VariableInitialized(const std::string& var) const
  1840. {
  1841. return this->StateSnapshot.IsInitialized(var);
  1842. }
  1843. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1844. const char* sourceFilename) const
  1845. {
  1846. // check to see if we need to print a warning
  1847. // if strict mode is on and the variable has
  1848. // not been "cleared"/initialized with a set(foo ) call
  1849. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1850. !this->VariableInitialized(variable)) {
  1851. if (this->CheckSystemVars ||
  1852. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1853. std::ostringstream msg;
  1854. msg << "uninitialized variable \'" << variable << "\'";
  1855. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1856. }
  1857. }
  1858. }
  1859. void cmMakefile::RemoveDefinition(const std::string& name)
  1860. {
  1861. this->StateSnapshot.RemoveDefinition(name);
  1862. #ifndef CMAKE_BOOTSTRAP
  1863. cmVariableWatch* vv = this->GetVariableWatch();
  1864. if (vv) {
  1865. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1866. nullptr, this);
  1867. }
  1868. #endif
  1869. }
  1870. void cmMakefile::RemoveCacheDefinition(const std::string& name) const
  1871. {
  1872. this->GetState()->RemoveCacheEntry(name);
  1873. }
  1874. void cmMakefile::SetProjectName(std::string const& p)
  1875. {
  1876. this->StateSnapshot.SetProjectName(p);
  1877. }
  1878. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1879. {
  1880. // for these targets do not add anything
  1881. switch (target.GetType()) {
  1882. case cmStateEnums::UTILITY:
  1883. case cmStateEnums::GLOBAL_TARGET:
  1884. case cmStateEnums::INTERFACE_LIBRARY:
  1885. return;
  1886. default:;
  1887. }
  1888. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1889. cmList linkLibs{ *linkLibsProp };
  1890. for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
  1891. std::string libraryName = *j;
  1892. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1893. if (libraryName == "optimized"_s) {
  1894. libType = OPTIMIZED_LibraryType;
  1895. ++j;
  1896. libraryName = *j;
  1897. } else if (libraryName == "debug"_s) {
  1898. libType = DEBUG_LibraryType;
  1899. ++j;
  1900. libraryName = *j;
  1901. }
  1902. // This is equivalent to the target_link_libraries plain signature.
  1903. target.AddLinkLibrary(*this, libraryName, libType);
  1904. target.AppendProperty(
  1905. "INTERFACE_LINK_LIBRARIES",
  1906. target.GetDebugGeneratorExpressions(libraryName, libType));
  1907. }
  1908. }
  1909. }
  1910. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName,
  1911. bool globallyVisible)
  1912. {
  1913. this->AliasTargets[lname] = tgtName;
  1914. if (globallyVisible) {
  1915. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1916. }
  1917. }
  1918. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1919. cmStateEnums::TargetType type,
  1920. const std::vector<std::string>& srcs,
  1921. bool excludeFromAll)
  1922. {
  1923. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1924. type == cmStateEnums::SHARED_LIBRARY ||
  1925. type == cmStateEnums::MODULE_LIBRARY ||
  1926. type == cmStateEnums::OBJECT_LIBRARY ||
  1927. type == cmStateEnums::INTERFACE_LIBRARY);
  1928. cmTarget* target = this->AddNewTarget(type, lname);
  1929. // Clear its dependencies. Otherwise, dependencies might persist
  1930. // over changes in CMakeLists.txt, making the information stale and
  1931. // hence useless.
  1932. target->ClearDependencyInformation(*this);
  1933. if (excludeFromAll) {
  1934. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1935. }
  1936. target->AddSources(srcs);
  1937. this->AddGlobalLinkInformation(*target);
  1938. return target;
  1939. }
  1940. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1941. const std::vector<std::string>& srcs,
  1942. bool excludeFromAll)
  1943. {
  1944. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1945. if (excludeFromAll) {
  1946. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1947. }
  1948. target->AddSources(srcs);
  1949. this->AddGlobalLinkInformation(*target);
  1950. return target;
  1951. }
  1952. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1953. const std::string& name)
  1954. {
  1955. return &this->CreateNewTarget(name, type).first;
  1956. }
  1957. cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
  1958. const std::string& name)
  1959. {
  1960. return &this
  1961. ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
  1962. cmTarget::Visibility::Generated)
  1963. .first;
  1964. }
  1965. std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
  1966. const std::string& name, cmStateEnums::TargetType type,
  1967. cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
  1968. {
  1969. auto ib =
  1970. this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
  1971. auto it = ib.first;
  1972. if (!ib.second) {
  1973. return std::make_pair(std::ref(it->second), false);
  1974. }
  1975. this->OrderedTargets.push_back(&it->second);
  1976. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1977. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1978. return std::make_pair(std::ref(it->second), true);
  1979. }
  1980. cmTarget* cmMakefile::AddNewUtilityTarget(const std::string& utilityName,
  1981. bool excludeFromAll)
  1982. {
  1983. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1984. if (excludeFromAll) {
  1985. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1986. }
  1987. return target;
  1988. }
  1989. namespace {
  1990. }
  1991. #if !defined(CMAKE_BOOTSTRAP)
  1992. cmSourceGroup* cmMakefile::GetSourceGroup(
  1993. const std::vector<std::string>& name) const
  1994. {
  1995. cmSourceGroup* sg = nullptr;
  1996. // first look for source group starting with the same as the one we want
  1997. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1998. std::string const& sgName = srcGroup.GetName();
  1999. if (sgName == name[0]) {
  2000. sg = const_cast<cmSourceGroup*>(&srcGroup);
  2001. break;
  2002. }
  2003. }
  2004. if (sg != nullptr) {
  2005. // iterate through its children to find match source group
  2006. for (unsigned int i = 1; i < name.size(); ++i) {
  2007. sg = sg->LookupChild(name[i]);
  2008. if (sg == nullptr) {
  2009. break;
  2010. }
  2011. }
  2012. }
  2013. return sg;
  2014. }
  2015. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  2016. {
  2017. std::vector<std::string> nameVector;
  2018. nameVector.push_back(name);
  2019. this->AddSourceGroup(nameVector, regex);
  2020. }
  2021. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  2022. const char* regex)
  2023. {
  2024. cmSourceGroup* sg = nullptr;
  2025. std::vector<std::string> currentName;
  2026. int i = 0;
  2027. const int lastElement = static_cast<int>(name.size() - 1);
  2028. for (i = lastElement; i >= 0; --i) {
  2029. currentName.assign(name.begin(), name.begin() + i + 1);
  2030. sg = this->GetSourceGroup(currentName);
  2031. if (sg != nullptr) {
  2032. break;
  2033. }
  2034. }
  2035. // i now contains the index of the last found component
  2036. if (i == lastElement) {
  2037. // group already exists, replace its regular expression
  2038. if (regex && sg) {
  2039. // We only want to set the regular expression. If there are already
  2040. // source files in the group, we don't want to remove them.
  2041. sg->SetGroupRegex(regex);
  2042. }
  2043. return;
  2044. }
  2045. if (i == -1) {
  2046. // group does not exist nor belong to any existing group
  2047. // add its first component
  2048. this->SourceGroups.emplace_back(name[0], regex);
  2049. sg = this->GetSourceGroup(currentName);
  2050. i = 0; // last component found
  2051. }
  2052. if (!sg) {
  2053. cmSystemTools::Error("Could not create source group ");
  2054. return;
  2055. }
  2056. // build the whole source group path
  2057. for (++i; i <= lastElement; ++i) {
  2058. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  2059. sg = sg->LookupChild(name[i]);
  2060. }
  2061. sg->SetGroupRegex(regex);
  2062. }
  2063. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  2064. const std::vector<std::string>& folders)
  2065. {
  2066. cmSourceGroup* sg = this->GetSourceGroup(folders);
  2067. if (sg == nullptr) {
  2068. this->AddSourceGroup(folders);
  2069. sg = this->GetSourceGroup(folders);
  2070. }
  2071. return sg;
  2072. }
  2073. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  2074. {
  2075. std::string delimiters;
  2076. if (cmValue p = this->GetDefinition("SOURCE_GROUP_DELIMITER")) {
  2077. delimiters = *p;
  2078. } else {
  2079. delimiters = "/\\";
  2080. }
  2081. return this->GetOrCreateSourceGroup(cmTokenize(name, delimiters));
  2082. }
  2083. /**
  2084. * Find a source group whose regular expression matches the filename
  2085. * part of the given source name. Search backward through the list of
  2086. * source groups, and take the first matching group found. This way
  2087. * non-inherited SOURCE_GROUP commands will have precedence over
  2088. * inherited ones.
  2089. */
  2090. cmSourceGroup* cmMakefile::FindSourceGroup(
  2091. const std::string& source, std::vector<cmSourceGroup>& groups) const
  2092. {
  2093. // First search for a group that lists the file explicitly.
  2094. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2095. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  2096. if (result) {
  2097. return result;
  2098. }
  2099. }
  2100. // Now search for a group whose regex matches the file.
  2101. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2102. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  2103. if (result) {
  2104. return result;
  2105. }
  2106. }
  2107. // Shouldn't get here, but just in case, return the default group.
  2108. return groups.data();
  2109. }
  2110. #endif
  2111. static bool mightExpandVariablesCMP0019(const char* s)
  2112. {
  2113. return s && *s && strstr(s, "${") && strchr(s, '}');
  2114. }
  2115. void cmMakefile::ExpandVariablesCMP0019()
  2116. {
  2117. // Drop this ancient compatibility behavior with a policy.
  2118. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  2119. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  2120. return;
  2121. }
  2122. std::ostringstream w;
  2123. cmValue includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  2124. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2125. std::string dirs = *includeDirs;
  2126. this->ExpandVariablesInString(dirs, true, true);
  2127. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2128. /* clang-format off */
  2129. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  2130. << " " << *includeDirs << "\n"
  2131. << "as\n"
  2132. << " " << dirs << "\n";
  2133. /* clang-format on */
  2134. }
  2135. this->SetProperty("INCLUDE_DIRECTORIES", dirs);
  2136. }
  2137. // Also for each target's INCLUDE_DIRECTORIES property:
  2138. for (auto& target : this->Targets) {
  2139. cmTarget& t = target.second;
  2140. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  2141. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  2142. continue;
  2143. }
  2144. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  2145. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2146. std::string dirs = *includeDirs;
  2147. this->ExpandVariablesInString(dirs, true, true);
  2148. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2149. /* clang-format off */
  2150. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  2151. << " " << *includeDirs << "\n"
  2152. << "as\n"
  2153. << " " << dirs << "\n";
  2154. /* clang-format on */
  2155. }
  2156. t.SetProperty("INCLUDE_DIRECTORIES", dirs);
  2157. }
  2158. }
  2159. if (cmValue linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2160. if (mightExpandVariablesCMP0019(linkDirsProp->c_str())) {
  2161. std::string d = *linkDirsProp;
  2162. const std::string orig = d;
  2163. this->ExpandVariablesInString(d, true, true);
  2164. if (pol == cmPolicies::WARN && d != orig) {
  2165. /* clang-format off */
  2166. w << "Evaluated link directories\n"
  2167. << " " << orig << "\n"
  2168. << "as\n"
  2169. << " " << d << "\n";
  2170. /* clang-format on */
  2171. }
  2172. }
  2173. }
  2174. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2175. cmList linkLibs{ *linkLibsProp };
  2176. for (auto l = linkLibs.begin(); l != linkLibs.end(); ++l) {
  2177. std::string libName = *l;
  2178. if (libName == "optimized"_s || libName == "debug"_s) {
  2179. ++l;
  2180. libName = *l;
  2181. }
  2182. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2183. const std::string orig = libName;
  2184. this->ExpandVariablesInString(libName, true, true);
  2185. if (pol == cmPolicies::WARN && libName != orig) {
  2186. /* clang-format off */
  2187. w << "Evaluated link library\n"
  2188. << " " << orig << "\n"
  2189. << "as\n"
  2190. << " " << libName << "\n";
  2191. /* clang-format on */
  2192. }
  2193. }
  2194. }
  2195. }
  2196. if (!w.str().empty()) {
  2197. std::ostringstream m;
  2198. /* clang-format off */
  2199. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2200. << "\n"
  2201. << "The following variable evaluations were encountered:\n"
  2202. << w.str();
  2203. /* clang-format on */
  2204. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2205. m.str(), this->Backtrace);
  2206. }
  2207. }
  2208. bool cmMakefile::IsOn(const std::string& name) const
  2209. {
  2210. return cmIsOn(this->GetDefinition(name));
  2211. }
  2212. bool cmMakefile::IsSet(const std::string& name) const
  2213. {
  2214. cmValue value = this->GetDefinition(name);
  2215. if (!value) {
  2216. return false;
  2217. }
  2218. if (value->empty()) {
  2219. return false;
  2220. }
  2221. if (cmIsNOTFOUND(*value)) {
  2222. return false;
  2223. }
  2224. return true;
  2225. }
  2226. bool cmMakefile::PlatformIs32Bit() const
  2227. {
  2228. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2229. if (*plat_abi == "ELF X32"_s) {
  2230. return false;
  2231. }
  2232. }
  2233. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2234. return atoi(sizeof_dptr->c_str()) == 4;
  2235. }
  2236. return false;
  2237. }
  2238. bool cmMakefile::PlatformIs64Bit() const
  2239. {
  2240. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2241. return atoi(sizeof_dptr->c_str()) == 8;
  2242. }
  2243. return false;
  2244. }
  2245. bool cmMakefile::PlatformIsx32() const
  2246. {
  2247. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2248. if (*plat_abi == "ELF X32"_s) {
  2249. return true;
  2250. }
  2251. }
  2252. return false;
  2253. }
  2254. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2255. {
  2256. std::string sdkRoot;
  2257. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2258. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2259. struct
  2260. {
  2261. std::string name;
  2262. AppleSDK sdk;
  2263. } const sdkDatabase[]{
  2264. { "appletvos", AppleSDK::AppleTVOS },
  2265. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2266. { "iphoneos", AppleSDK::IPhoneOS },
  2267. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2268. { "watchos", AppleSDK::WatchOS },
  2269. { "watchsimulator", AppleSDK::WatchSimulator },
  2270. { "xros", AppleSDK::XROS },
  2271. { "xrsimulator", AppleSDK::XRSimulator },
  2272. };
  2273. for (auto const& entry : sdkDatabase) {
  2274. if (cmHasPrefix(sdkRoot, entry.name) ||
  2275. sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
  2276. return entry.sdk;
  2277. }
  2278. }
  2279. return AppleSDK::MacOS;
  2280. }
  2281. bool cmMakefile::PlatformIsAppleEmbedded() const
  2282. {
  2283. return this->GetAppleSDKType() != AppleSDK::MacOS;
  2284. }
  2285. bool cmMakefile::PlatformIsAppleSimulator() const
  2286. {
  2287. return std::set<AppleSDK>{
  2288. AppleSDK::AppleTVSimulator,
  2289. AppleSDK::IPhoneSimulator,
  2290. AppleSDK::WatchSimulator,
  2291. AppleSDK::XRSimulator,
  2292. }
  2293. .count(this->GetAppleSDKType());
  2294. }
  2295. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  2296. {
  2297. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  2298. }
  2299. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2300. {
  2301. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2302. if (!language.empty()) {
  2303. name += "_";
  2304. name += language;
  2305. }
  2306. name += "_FLAG";
  2307. return this->GetDefinition(name).GetCStr();
  2308. }
  2309. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2310. {
  2311. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2312. return true;
  2313. }
  2314. // If we are doing an in-source build, then the test will always fail
  2315. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2316. this->GetHomeOutputDirectory())) {
  2317. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2318. }
  2319. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2320. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2321. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2322. }
  2323. const std::string& cmMakefile::GetRequiredDefinition(
  2324. const std::string& name) const
  2325. {
  2326. static std::string const empty;
  2327. cmValue def = this->GetDefinition(name);
  2328. if (!def) {
  2329. cmSystemTools::Error("Error required internal CMake variable not "
  2330. "set, cmake may not be built correctly.\n"
  2331. "Missing variable is:\n" +
  2332. name);
  2333. return empty;
  2334. }
  2335. return *def;
  2336. }
  2337. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2338. {
  2339. cmValue def = this->StateSnapshot.GetDefinition(name);
  2340. if (!def) {
  2341. def = this->GetState()->GetInitializedCacheValue(name);
  2342. }
  2343. #ifndef CMAKE_BOOTSTRAP
  2344. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2345. if (!def) {
  2346. vv->VariableAccessed(
  2347. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2348. }
  2349. }
  2350. #endif
  2351. return def != nullptr;
  2352. }
  2353. bool cmMakefile::IsNormalDefinitionSet(const std::string& name) const
  2354. {
  2355. cmValue def = this->StateSnapshot.GetDefinition(name);
  2356. #ifndef CMAKE_BOOTSTRAP
  2357. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2358. if (!def) {
  2359. vv->VariableAccessed(
  2360. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2361. }
  2362. }
  2363. #endif
  2364. return def != nullptr;
  2365. }
  2366. cmValue cmMakefile::GetDefinition(const std::string& name) const
  2367. {
  2368. cmValue def = this->StateSnapshot.GetDefinition(name);
  2369. if (!def) {
  2370. def = this->GetState()->GetInitializedCacheValue(name);
  2371. }
  2372. #ifndef CMAKE_BOOTSTRAP
  2373. cmVariableWatch* vv = this->GetVariableWatch();
  2374. if (vv && !this->SuppressSideEffects) {
  2375. bool const watch_function_executed =
  2376. vv->VariableAccessed(name,
  2377. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2378. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2379. def.GetCStr(), this);
  2380. if (watch_function_executed) {
  2381. // A callback was executed and may have caused re-allocation of the
  2382. // variable storage. Look it up again for now.
  2383. // FIXME: Refactor variable storage to avoid this problem.
  2384. def = this->StateSnapshot.GetDefinition(name);
  2385. if (!def) {
  2386. def = this->GetState()->GetInitializedCacheValue(name);
  2387. }
  2388. }
  2389. }
  2390. #endif
  2391. return def;
  2392. }
  2393. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2394. {
  2395. return this->GetDefinition(name);
  2396. }
  2397. std::vector<std::string> cmMakefile::GetDefinitions() const
  2398. {
  2399. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2400. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2401. std::sort(res.begin(), res.end());
  2402. return res;
  2403. }
  2404. const std::string& cmMakefile::ExpandVariablesInString(
  2405. std::string& source) const
  2406. {
  2407. return this->ExpandVariablesInString(source, false, false);
  2408. }
  2409. const std::string& cmMakefile::ExpandVariablesInString(
  2410. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2411. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2412. {
  2413. bool compareResults = false;
  2414. MessageType mtype = MessageType::LOG;
  2415. std::string errorstr;
  2416. std::string original;
  2417. // Sanity check the @ONLY mode.
  2418. if (atOnly && (!noEscapes || !removeEmpty)) {
  2419. // This case should never be called. At-only is for
  2420. // configure-file/string which always does no escapes.
  2421. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2422. "ExpandVariablesInString @ONLY called "
  2423. "on something with escapes.");
  2424. return source;
  2425. }
  2426. // Variables used in the WARN case.
  2427. std::string newResult;
  2428. std::string newErrorstr;
  2429. MessageType newError = MessageType::LOG;
  2430. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2431. case cmPolicies::WARN: {
  2432. // Save the original string for the warning.
  2433. original = source;
  2434. newResult = source;
  2435. compareResults = true;
  2436. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2437. // dereferences since the OLD behavior is still what is actually used.
  2438. this->SuppressSideEffects = true;
  2439. newError = this->ExpandVariablesInStringNew(
  2440. newErrorstr, newResult, escapeQuotes, noEscapes, atOnly, filename,
  2441. line, replaceAt);
  2442. this->SuppressSideEffects = false;
  2443. CM_FALLTHROUGH;
  2444. }
  2445. case cmPolicies::OLD:
  2446. mtype = this->ExpandVariablesInStringOld(errorstr, source, escapeQuotes,
  2447. noEscapes, atOnly, filename,
  2448. line, removeEmpty, true);
  2449. break;
  2450. case cmPolicies::REQUIRED_IF_USED:
  2451. case cmPolicies::REQUIRED_ALWAYS:
  2452. // Messaging here would be *very* verbose.
  2453. case cmPolicies::NEW:
  2454. mtype = this->ExpandVariablesInStringNew(errorstr, source, escapeQuotes,
  2455. noEscapes, atOnly, filename,
  2456. line, replaceAt);
  2457. break;
  2458. }
  2459. // If it's an error in either case, just report the error...
  2460. if (mtype != MessageType::LOG) {
  2461. if (mtype == MessageType::FATAL_ERROR) {
  2462. cmSystemTools::SetFatalErrorOccurred();
  2463. }
  2464. this->IssueMessage(mtype, errorstr);
  2465. }
  2466. // ...otherwise, see if there's a difference that needs to be warned about.
  2467. else if (compareResults && (newResult != source || newError != mtype)) {
  2468. std::string msg =
  2469. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0053), '\n');
  2470. std::string msg_input = original;
  2471. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2472. msg += "For input:\n '";
  2473. msg += msg_input;
  2474. msg += "'\n";
  2475. std::string msg_old = source;
  2476. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2477. msg += "the old evaluation rules produce:\n '";
  2478. msg += msg_old;
  2479. msg += "'\n";
  2480. if (newError == mtype) {
  2481. std::string msg_new = newResult;
  2482. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2483. msg += "but the new evaluation rules produce:\n '";
  2484. msg += msg_new;
  2485. msg += "'\n";
  2486. } else {
  2487. std::string msg_err = newErrorstr;
  2488. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2489. msg += "but the new evaluation rules produce an error:\n ";
  2490. msg += msg_err;
  2491. msg += "\n";
  2492. }
  2493. msg +=
  2494. "Using the old result for compatibility since the policy is not set.";
  2495. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2496. }
  2497. return source;
  2498. }
  2499. MessageType cmMakefile::ExpandVariablesInStringOld(
  2500. std::string& errorstr, std::string& source, bool escapeQuotes,
  2501. bool noEscapes, bool atOnly, const char* filename, long line,
  2502. bool removeEmpty, bool replaceAt) const
  2503. {
  2504. // Fast path strings without any special characters.
  2505. if (source.find_first_of("$@\\") == std::string::npos) {
  2506. return MessageType::LOG;
  2507. }
  2508. // Special-case the @ONLY mode.
  2509. if (atOnly) {
  2510. // Store an original copy of the input.
  2511. std::string input = source;
  2512. // Start with empty output.
  2513. source.clear();
  2514. // Look for one @VAR@ at a time.
  2515. const char* in = input.c_str();
  2516. while (this->cmAtVarRegex.find(in)) {
  2517. // Get the range of the string to replace.
  2518. const char* first = in + this->cmAtVarRegex.start();
  2519. const char* last = in + this->cmAtVarRegex.end();
  2520. // Store the unchanged part of the string now.
  2521. source.append(in, first - in);
  2522. // Lookup the definition of VAR.
  2523. std::string var(first + 1, last - first - 2);
  2524. if (cmValue val = this->GetDefinition(var)) {
  2525. // Store the value in the output escaping as requested.
  2526. if (escapeQuotes) {
  2527. source.append(cmEscapeQuotes(*val));
  2528. } else {
  2529. source.append(*val);
  2530. }
  2531. }
  2532. // Continue looking for @VAR@ further along the string.
  2533. in = last;
  2534. }
  2535. // Append the rest of the unchanged part of the string.
  2536. source.append(in);
  2537. return MessageType::LOG;
  2538. }
  2539. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2540. // with GetDefinition(), if not found in the map, nothing is expanded.
  2541. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2542. // the current environment variables.
  2543. cmCommandArgumentParserHelper parser;
  2544. parser.SetMakefile(this);
  2545. parser.SetLineFile(line, filename);
  2546. parser.SetEscapeQuotes(escapeQuotes);
  2547. parser.SetNoEscapeMode(noEscapes);
  2548. parser.SetReplaceAtSyntax(replaceAt);
  2549. parser.SetRemoveEmpty(removeEmpty);
  2550. int res = parser.ParseString(source, 0);
  2551. const char* emsg = parser.GetError();
  2552. MessageType mtype = MessageType::LOG;
  2553. if (res && !emsg[0]) {
  2554. source = parser.GetResult();
  2555. } else {
  2556. // Construct the main error message.
  2557. std::ostringstream error;
  2558. error << "Syntax error in cmake code ";
  2559. if (filename && line > 0) {
  2560. // This filename and line number may be more specific than the
  2561. // command context because one command invocation can have
  2562. // arguments on multiple lines.
  2563. error << "at\n"
  2564. << " " << filename << ":" << line << "\n";
  2565. }
  2566. error << "when parsing string\n"
  2567. << " " << source << "\n";
  2568. error << emsg;
  2569. // If the parser failed ("res" is false) then this is a real
  2570. // argument parsing error, so the policy applies. Otherwise the
  2571. // parser reported an error message without failing because the
  2572. // helper implementation is unhappy, which has always reported an
  2573. // error.
  2574. mtype = MessageType::FATAL_ERROR;
  2575. if (!res) {
  2576. // This is a real argument parsing error. Use policy CMP0010 to
  2577. // decide whether it is an error.
  2578. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2579. case cmPolicies::WARN:
  2580. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2581. CM_FALLTHROUGH;
  2582. case cmPolicies::OLD:
  2583. // OLD behavior is to just warn and continue.
  2584. mtype = MessageType::AUTHOR_WARNING;
  2585. break;
  2586. case cmPolicies::REQUIRED_IF_USED:
  2587. case cmPolicies::REQUIRED_ALWAYS:
  2588. error << "\n"
  2589. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2590. break;
  2591. case cmPolicies::NEW:
  2592. // NEW behavior is to report the error.
  2593. break;
  2594. }
  2595. }
  2596. errorstr = error.str();
  2597. }
  2598. return mtype;
  2599. }
  2600. enum t_domain
  2601. {
  2602. NORMAL,
  2603. ENVIRONMENT,
  2604. CACHE
  2605. };
  2606. struct t_lookup
  2607. {
  2608. t_domain domain = NORMAL;
  2609. size_t loc = 0;
  2610. };
  2611. bool cmMakefile::IsProjectFile(const char* filename) const
  2612. {
  2613. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2614. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2615. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2616. }
  2617. size_t cmMakefile::GetRecursionDepthLimit() const
  2618. {
  2619. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2620. if (cmValue depthStr =
  2621. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2622. unsigned long depthUL;
  2623. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2624. depth = depthUL;
  2625. }
  2626. } else if (cm::optional<std::string> depthEnv =
  2627. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2628. unsigned long depthUL;
  2629. if (cmStrToULong(*depthEnv, &depthUL)) {
  2630. depth = depthUL;
  2631. }
  2632. }
  2633. return depth;
  2634. }
  2635. size_t cmMakefile::GetRecursionDepth() const
  2636. {
  2637. return this->RecursionDepth;
  2638. }
  2639. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2640. {
  2641. this->RecursionDepth = recursionDepth;
  2642. }
  2643. std::string cmMakefile::NewDeferId() const
  2644. {
  2645. return this->GetGlobalGenerator()->NewDeferId();
  2646. }
  2647. bool cmMakefile::DeferCall(std::string id, std::string file,
  2648. cmListFileFunction lff)
  2649. {
  2650. if (!this->Defer) {
  2651. return false;
  2652. }
  2653. this->Defer->Commands.emplace_back(
  2654. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2655. return true;
  2656. }
  2657. bool cmMakefile::DeferCancelCall(std::string const& id)
  2658. {
  2659. if (!this->Defer) {
  2660. return false;
  2661. }
  2662. for (DeferCommand& dc : this->Defer->Commands) {
  2663. if (dc.Id == id) {
  2664. dc.Id.clear();
  2665. }
  2666. }
  2667. return true;
  2668. }
  2669. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2670. {
  2671. cm::optional<std::string> ids;
  2672. if (this->Defer) {
  2673. ids = cmList::to_string(
  2674. cmMakeRange(this->Defer->Commands)
  2675. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2676. .transform(
  2677. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
  2678. }
  2679. return ids;
  2680. }
  2681. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2682. {
  2683. cm::optional<std::string> call;
  2684. if (this->Defer) {
  2685. std::string tmp;
  2686. for (DeferCommand const& dc : this->Defer->Commands) {
  2687. if (dc.Id == id) {
  2688. tmp = dc.Command.OriginalName();
  2689. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2690. tmp = cmStrCat(tmp, ';', arg.Value);
  2691. }
  2692. break;
  2693. }
  2694. }
  2695. call = std::move(tmp);
  2696. }
  2697. return call;
  2698. }
  2699. MessageType cmMakefile::ExpandVariablesInStringNew(
  2700. std::string& errorstr, std::string& source, bool escapeQuotes,
  2701. bool noEscapes, bool atOnly, const char* filename, long line,
  2702. bool replaceAt) const
  2703. {
  2704. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2705. // with GetDefinition(), if not found in the map, nothing is expanded.
  2706. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2707. // the current environment variables.
  2708. const char* in = source.c_str();
  2709. const char* last = in;
  2710. std::string result;
  2711. result.reserve(source.size());
  2712. std::vector<t_lookup> openstack;
  2713. bool error = false;
  2714. bool done = false;
  2715. MessageType mtype = MessageType::LOG;
  2716. cmState* state = this->GetCMakeInstance()->GetState();
  2717. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2718. do {
  2719. char inc = *in;
  2720. switch (inc) {
  2721. case '}':
  2722. if (!openstack.empty()) {
  2723. t_lookup var = openstack.back();
  2724. openstack.pop_back();
  2725. result.append(last, in - last);
  2726. std::string const& lookup = result.substr(var.loc);
  2727. cmValue value = nullptr;
  2728. std::string varresult;
  2729. std::string svalue;
  2730. switch (var.domain) {
  2731. case NORMAL:
  2732. if (filename && lookup == lineVar) {
  2733. cmListFileContext const& top = this->Backtrace.Top();
  2734. if (top.DeferId) {
  2735. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2736. } else {
  2737. varresult = std::to_string(line);
  2738. }
  2739. } else {
  2740. value = this->GetDefinition(lookup);
  2741. }
  2742. break;
  2743. case ENVIRONMENT:
  2744. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2745. value = cmValue(svalue);
  2746. }
  2747. break;
  2748. case CACHE:
  2749. value = state->GetCacheEntryValue(lookup);
  2750. break;
  2751. }
  2752. // Get the string we're meant to append to.
  2753. if (value) {
  2754. if (escapeQuotes) {
  2755. varresult = cmEscapeQuotes(*value);
  2756. } else {
  2757. varresult = *value;
  2758. }
  2759. } else if (!this->SuppressSideEffects) {
  2760. this->MaybeWarnUninitialized(lookup, filename);
  2761. }
  2762. result.replace(var.loc, result.size() - var.loc, varresult);
  2763. // Start looking from here on out.
  2764. last = in + 1;
  2765. }
  2766. break;
  2767. case '$':
  2768. if (!atOnly) {
  2769. t_lookup lookup;
  2770. const char* next = in + 1;
  2771. const char* start = nullptr;
  2772. char nextc = *next;
  2773. if (nextc == '{') {
  2774. // Looking for a variable.
  2775. start = in + 2;
  2776. lookup.domain = NORMAL;
  2777. } else if (nextc == '<') {
  2778. } else if (!nextc) {
  2779. result.append(last, next - last);
  2780. last = next;
  2781. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2782. // Looking for an environment variable.
  2783. start = in + 5;
  2784. lookup.domain = ENVIRONMENT;
  2785. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2786. // Looking for a cache variable.
  2787. start = in + 7;
  2788. lookup.domain = CACHE;
  2789. } else {
  2790. if (this->cmNamedCurly.find(next)) {
  2791. errorstr = "Syntax $" +
  2792. std::string(next, this->cmNamedCurly.end()) +
  2793. "{} is not supported. Only ${}, $ENV{}, "
  2794. "and $CACHE{} are allowed.";
  2795. mtype = MessageType::FATAL_ERROR;
  2796. error = true;
  2797. }
  2798. }
  2799. if (start) {
  2800. result.append(last, in - last);
  2801. last = start;
  2802. in = start - 1;
  2803. lookup.loc = result.size();
  2804. openstack.push_back(lookup);
  2805. }
  2806. break;
  2807. }
  2808. CM_FALLTHROUGH;
  2809. case '\\':
  2810. if (!noEscapes) {
  2811. const char* next = in + 1;
  2812. char nextc = *next;
  2813. if (nextc == 't') {
  2814. result.append(last, in - last);
  2815. result.push_back('\t');
  2816. last = next + 1;
  2817. } else if (nextc == 'n') {
  2818. result.append(last, in - last);
  2819. result.push_back('\n');
  2820. last = next + 1;
  2821. } else if (nextc == 'r') {
  2822. result.append(last, in - last);
  2823. result.push_back('\r');
  2824. last = next + 1;
  2825. } else if (nextc == ';' && openstack.empty()) {
  2826. // Handled in ExpandListArgument; pass the backslash literally.
  2827. } else if (isalnum(nextc) || nextc == '\0') {
  2828. errorstr += "Invalid character escape '\\";
  2829. if (nextc) {
  2830. errorstr += nextc;
  2831. errorstr += "'.";
  2832. } else {
  2833. errorstr += "' (at end of input).";
  2834. }
  2835. error = true;
  2836. } else {
  2837. // Take what we've found so far, skipping the escape character.
  2838. result.append(last, in - last);
  2839. // Start tracking from the next character.
  2840. last = in + 1;
  2841. }
  2842. // Skip the next character since it was escaped, but don't read past
  2843. // the end of the string.
  2844. if (*last) {
  2845. ++in;
  2846. }
  2847. }
  2848. break;
  2849. case '\n':
  2850. // Onto the next line.
  2851. ++line;
  2852. break;
  2853. case '\0':
  2854. done = true;
  2855. break;
  2856. case '@':
  2857. if (replaceAt) {
  2858. const char* nextAt = strchr(in + 1, '@');
  2859. if (nextAt && nextAt != in + 1 &&
  2860. nextAt ==
  2861. in + 1 +
  2862. strspn(in + 1,
  2863. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2864. "abcdefghijklmnopqrstuvwxyz"
  2865. "0123456789/_.+-")) {
  2866. std::string variable(in + 1, nextAt - in - 1);
  2867. std::string varresult;
  2868. if (filename && variable == lineVar) {
  2869. varresult = std::to_string(line);
  2870. } else {
  2871. cmValue def = this->GetDefinition(variable);
  2872. if (def) {
  2873. varresult = *def;
  2874. } else if (!this->SuppressSideEffects) {
  2875. this->MaybeWarnUninitialized(variable, filename);
  2876. }
  2877. }
  2878. if (escapeQuotes) {
  2879. varresult = cmEscapeQuotes(varresult);
  2880. }
  2881. // Skip over the variable.
  2882. result.append(last, in - last);
  2883. result.append(varresult);
  2884. in = nextAt;
  2885. last = in + 1;
  2886. break;
  2887. }
  2888. }
  2889. // Failed to find a valid @ expansion; treat it as literal.
  2890. CM_FALLTHROUGH;
  2891. default: {
  2892. if (!openstack.empty() &&
  2893. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2894. inc == '+' || inc == '-')) {
  2895. errorstr += "Invalid character (\'";
  2896. errorstr += inc;
  2897. result.append(last, in - last);
  2898. errorstr += cmStrCat("\') in a variable name: "
  2899. "'",
  2900. result.substr(openstack.back().loc), '\'');
  2901. mtype = MessageType::FATAL_ERROR;
  2902. error = true;
  2903. }
  2904. break;
  2905. }
  2906. }
  2907. // Look at the next character.
  2908. } while (!error && !done && *++in);
  2909. // Check for open variable references yet.
  2910. if (!error && !openstack.empty()) {
  2911. // There's an open variable reference waiting. Policy CMP0010 flags
  2912. // whether this is an error or not. The new parser now enforces
  2913. // CMP0010 as well.
  2914. errorstr += "There is an unterminated variable reference.";
  2915. error = true;
  2916. }
  2917. if (error) {
  2918. std::ostringstream emsg;
  2919. emsg << "Syntax error in cmake code ";
  2920. if (filename) {
  2921. // This filename and line number may be more specific than the
  2922. // command context because one command invocation can have
  2923. // arguments on multiple lines.
  2924. emsg << "at\n"
  2925. << " " << filename << ":" << line << "\n";
  2926. }
  2927. emsg << "when parsing string\n"
  2928. << " " << source << "\n";
  2929. emsg << errorstr;
  2930. mtype = MessageType::FATAL_ERROR;
  2931. errorstr = emsg.str();
  2932. } else {
  2933. // Append the rest of the unchanged part of the string.
  2934. result.append(last);
  2935. source = result;
  2936. }
  2937. return mtype;
  2938. }
  2939. void cmMakefile::RemoveVariablesInString(std::string& source,
  2940. bool atOnly) const
  2941. {
  2942. if (!atOnly) {
  2943. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2944. while (var.find(source)) {
  2945. source.erase(var.start(), var.end() - var.start());
  2946. }
  2947. }
  2948. if (!atOnly) {
  2949. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2950. while (varb.find(source)) {
  2951. source.erase(varb.start(), varb.end() - varb.start());
  2952. }
  2953. }
  2954. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2955. while (var2.find(source)) {
  2956. source.erase(var2.start(), var2.end() - var2.start());
  2957. }
  2958. }
  2959. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2960. {
  2961. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2962. return;
  2963. }
  2964. std::string initConfigs;
  2965. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2966. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2967. initConfigs = genDefault;
  2968. }
  2969. this->AddCacheDefinition(
  2970. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2971. "Semicolon separated list of supported configuration types, "
  2972. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2973. "anything else will be ignored.",
  2974. cmStateEnums::STRING);
  2975. }
  2976. std::string cmMakefile::GetDefaultConfiguration() const
  2977. {
  2978. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2979. return std::string{};
  2980. }
  2981. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2982. }
  2983. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2984. GeneratorConfigQuery mode) const
  2985. {
  2986. cmList configs;
  2987. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2988. configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
  2989. } else if (mode != cmMakefile::OnlyMultiConfig) {
  2990. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2991. if (!buildType.empty()) {
  2992. configs.emplace_back(buildType);
  2993. }
  2994. }
  2995. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  2996. configs.emplace_back();
  2997. }
  2998. return std::move(configs.data());
  2999. }
  3000. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  3001. cmExecutionStatus& status)
  3002. {
  3003. // if there are no blockers get out of here
  3004. if (this->FunctionBlockers.empty()) {
  3005. return false;
  3006. }
  3007. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  3008. }
  3009. void cmMakefile::PushFunctionBlockerBarrier()
  3010. {
  3011. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  3012. }
  3013. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  3014. {
  3015. // Remove any extra entries pushed on the barrier.
  3016. FunctionBlockersType::size_type barrier =
  3017. this->FunctionBlockerBarriers.back();
  3018. while (this->FunctionBlockers.size() > barrier) {
  3019. std::unique_ptr<cmFunctionBlocker> fb(
  3020. std::move(this->FunctionBlockers.top()));
  3021. this->FunctionBlockers.pop();
  3022. if (reportError) {
  3023. // Report the context in which the unclosed block was opened.
  3024. cmListFileContext const& lfc = fb->GetStartingContext();
  3025. std::ostringstream e;
  3026. /* clang-format off */
  3027. e << "A logical block opening on the line\n"
  3028. << " " << lfc << "\n"
  3029. << "is not closed.";
  3030. /* clang-format on */
  3031. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3032. reportError = false;
  3033. }
  3034. }
  3035. // Remove the barrier.
  3036. this->FunctionBlockerBarriers.pop_back();
  3037. }
  3038. void cmMakefile::PushLoopBlock()
  3039. {
  3040. assert(!this->LoopBlockCounter.empty());
  3041. this->LoopBlockCounter.top()++;
  3042. }
  3043. void cmMakefile::PopLoopBlock()
  3044. {
  3045. assert(!this->LoopBlockCounter.empty());
  3046. assert(this->LoopBlockCounter.top() > 0);
  3047. this->LoopBlockCounter.top()--;
  3048. }
  3049. void cmMakefile::PushLoopBlockBarrier()
  3050. {
  3051. this->LoopBlockCounter.push(0);
  3052. }
  3053. void cmMakefile::PopLoopBlockBarrier()
  3054. {
  3055. assert(!this->LoopBlockCounter.empty());
  3056. assert(this->LoopBlockCounter.top() == 0);
  3057. this->LoopBlockCounter.pop();
  3058. }
  3059. bool cmMakefile::IsLoopBlock() const
  3060. {
  3061. assert(!this->LoopBlockCounter.empty());
  3062. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  3063. }
  3064. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  3065. std::vector<std::string>& outArgs) const
  3066. {
  3067. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3068. std::string value;
  3069. outArgs.reserve(inArgs.size());
  3070. for (cmListFileArgument const& i : inArgs) {
  3071. // No expansion in a bracket argument.
  3072. if (i.Delim == cmListFileArgument::Bracket) {
  3073. outArgs.push_back(i.Value);
  3074. continue;
  3075. }
  3076. // Expand the variables in the argument.
  3077. value = i.Value;
  3078. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3079. i.Line, false, false);
  3080. // If the argument is quoted, it should be one argument.
  3081. // Otherwise, it may be a list of arguments.
  3082. if (i.Delim == cmListFileArgument::Quoted) {
  3083. outArgs.push_back(value);
  3084. } else {
  3085. cmExpandList(value, outArgs);
  3086. }
  3087. }
  3088. return !cmSystemTools::GetFatalErrorOccurred();
  3089. }
  3090. bool cmMakefile::ExpandArguments(
  3091. std::vector<cmListFileArgument> const& inArgs,
  3092. std::vector<cmExpandedCommandArgument>& outArgs) const
  3093. {
  3094. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3095. std::string value;
  3096. outArgs.reserve(inArgs.size());
  3097. for (cmListFileArgument const& i : inArgs) {
  3098. // No expansion in a bracket argument.
  3099. if (i.Delim == cmListFileArgument::Bracket) {
  3100. outArgs.emplace_back(i.Value, true);
  3101. continue;
  3102. }
  3103. // Expand the variables in the argument.
  3104. value = i.Value;
  3105. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3106. i.Line, false, false);
  3107. // If the argument is quoted, it should be one argument.
  3108. // Otherwise, it may be a list of arguments.
  3109. if (i.Delim == cmListFileArgument::Quoted) {
  3110. outArgs.emplace_back(value, true);
  3111. } else {
  3112. cmList stringArgs{ value };
  3113. for (std::string const& stringArg : stringArgs) {
  3114. outArgs.emplace_back(stringArg, false);
  3115. }
  3116. }
  3117. }
  3118. return !cmSystemTools::GetFatalErrorOccurred();
  3119. }
  3120. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  3121. {
  3122. if (!this->ExecutionStatusStack.empty()) {
  3123. // Record the context in which the blocker is created.
  3124. fb->SetStartingContext(this->Backtrace.Top());
  3125. }
  3126. this->FunctionBlockers.push(std::move(fb));
  3127. }
  3128. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  3129. {
  3130. assert(!this->FunctionBlockers.empty());
  3131. assert(this->FunctionBlockerBarriers.empty() ||
  3132. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  3133. auto b = std::move(this->FunctionBlockers.top());
  3134. this->FunctionBlockers.pop();
  3135. return b;
  3136. }
  3137. std::string const& cmMakefile::GetHomeDirectory() const
  3138. {
  3139. return this->GetCMakeInstance()->GetHomeDirectory();
  3140. }
  3141. std::string const& cmMakefile::GetHomeOutputDirectory() const
  3142. {
  3143. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3144. }
  3145. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  3146. {
  3147. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  3148. }
  3149. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  3150. {
  3151. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  3152. // this->MarkVariableAsUsed("CMAKE_ARGC");
  3153. for (unsigned int t = 0; t < args.size(); ++t) {
  3154. std::ostringstream tmpStream;
  3155. tmpStream << "CMAKE_ARGV" << t;
  3156. this->AddDefinition(tmpStream.str(), args[t]);
  3157. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  3158. }
  3159. }
  3160. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  3161. cmSourceFileLocationKind kind) const
  3162. {
  3163. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  3164. if (kind == cmSourceFileLocationKind::Known) {
  3165. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  3166. if (sfsi != this->KnownFileSearchIndex.end()) {
  3167. return sfsi->second;
  3168. }
  3169. }
  3170. cmSourceFileLocation sfl(this, sourceName, kind);
  3171. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  3172. #if defined(_WIN32) || defined(__APPLE__)
  3173. name = cmSystemTools::LowerCase(name);
  3174. #endif
  3175. auto sfsi = this->SourceFileSearchIndex.find(name);
  3176. if (sfsi != this->SourceFileSearchIndex.end()) {
  3177. for (auto* sf : sfsi->second) {
  3178. if (sf->Matches(sfl)) {
  3179. return sf;
  3180. }
  3181. }
  3182. }
  3183. return nullptr;
  3184. }
  3185. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  3186. bool generated,
  3187. cmSourceFileLocationKind kind)
  3188. {
  3189. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  3190. auto name =
  3191. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  3192. #if defined(_WIN32) || defined(__APPLE__)
  3193. name = cmSystemTools::LowerCase(name);
  3194. #endif
  3195. this->SourceFileSearchIndex[name].push_back(sf.get());
  3196. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  3197. if (kind == cmSourceFileLocationKind::Known) {
  3198. this->KnownFileSearchIndex[sourceName] = sf.get();
  3199. }
  3200. this->SourceFiles.push_back(std::move(sf));
  3201. return this->SourceFiles.back().get();
  3202. }
  3203. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  3204. bool generated,
  3205. cmSourceFileLocationKind kind)
  3206. {
  3207. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  3208. return esf;
  3209. }
  3210. return this->CreateSource(sourceName, generated, kind);
  3211. }
  3212. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  3213. const std::string& sourceName)
  3214. {
  3215. cmSourceFile* sf =
  3216. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  3217. sf->MarkAsGenerated(); // In case we did not create the source file.
  3218. return sf;
  3219. }
  3220. void cmMakefile::CreateGeneratedOutputs(
  3221. const std::vector<std::string>& outputs)
  3222. {
  3223. for (std::string const& o : outputs) {
  3224. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  3225. this->GetOrCreateGeneratedSource(o);
  3226. }
  3227. }
  3228. }
  3229. void cmMakefile::AddTargetObject(std::string const& tgtName,
  3230. std::string const& objFile)
  3231. {
  3232. cmSourceFile* sf =
  3233. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  3234. sf->SetObjectLibrary(tgtName);
  3235. sf->SetProperty("EXTERNAL_OBJECT", "1");
  3236. // TODO: Compute a language for this object based on the associated source
  3237. // file that compiles to it. Needs a policy as it likely affects link
  3238. // language selection if done unconditionally.
  3239. #if !defined(CMAKE_BOOTSTRAP)
  3240. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  3241. sf->ResolveFullPath());
  3242. #endif
  3243. }
  3244. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  3245. bool optional)
  3246. {
  3247. if (this->DeferRunning) {
  3248. this->IssueMessage(
  3249. MessageType::FATAL_ERROR,
  3250. "Languages may not be enabled during deferred execution.");
  3251. return;
  3252. }
  3253. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  3254. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  3255. }
  3256. std::vector<std::string> unique_languages;
  3257. {
  3258. std::vector<std::string> duplicate_languages;
  3259. for (std::string const& language : languages) {
  3260. if (!cm::contains(unique_languages, language)) {
  3261. unique_languages.push_back(language);
  3262. } else if (!cm::contains(duplicate_languages, language)) {
  3263. duplicate_languages.push_back(language);
  3264. }
  3265. }
  3266. if (!duplicate_languages.empty()) {
  3267. auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
  3268. this->IssueMessage(
  3269. MessageType::AUTHOR_WARNING,
  3270. cmStrCat("Languages to be enabled may not be specified more "
  3271. "than once at the same time. The following language",
  3272. quantity, " been specified multiple times: ",
  3273. cmJoin(duplicate_languages, ", ")));
  3274. }
  3275. }
  3276. // If RC is explicitly listed we need to do it after other languages.
  3277. // On some platforms we enable RC implicitly while enabling others.
  3278. // Do not let that look like recursive enable_language(RC).
  3279. std::vector<std::string> languages_without_RC;
  3280. std::vector<std::string> languages_for_RC;
  3281. languages_without_RC.reserve(unique_languages.size());
  3282. for (std::string const& language : unique_languages) {
  3283. if (language == "RC"_s) {
  3284. languages_for_RC.push_back(language);
  3285. } else {
  3286. languages_without_RC.push_back(language);
  3287. }
  3288. }
  3289. if (!languages_without_RC.empty()) {
  3290. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  3291. optional);
  3292. }
  3293. if (!languages_for_RC.empty()) {
  3294. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  3295. optional);
  3296. }
  3297. }
  3298. int cmMakefile::TryCompile(const std::string& srcdir,
  3299. const std::string& bindir,
  3300. const std::string& projectName,
  3301. const std::string& targetName, bool fast, int jobs,
  3302. const std::vector<std::string>* cmakeArgs,
  3303. std::string& output)
  3304. {
  3305. this->IsSourceFileTryCompile = fast;
  3306. // does the binary directory exist ? If not create it...
  3307. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3308. cmSystemTools::MakeDirectory(bindir);
  3309. }
  3310. // change to the tests directory and run cmake
  3311. // use the cmake object instead of calling cmake
  3312. cmWorkingDirectory workdir(bindir);
  3313. if (workdir.Failed()) {
  3314. this->IssueMessage(MessageType::FATAL_ERROR,
  3315. cmStrCat("Failed to set working directory to ", bindir,
  3316. " : ",
  3317. std::strerror(workdir.GetLastResult())));
  3318. cmSystemTools::SetFatalErrorOccurred();
  3319. this->IsSourceFileTryCompile = false;
  3320. return 1;
  3321. }
  3322. // make sure the same generator is used
  3323. // use this program as the cmake to be run, it should not
  3324. // be run that way but the cmake object requires a valid path
  3325. cmake cm(cmake::RoleProject, cmState::Project,
  3326. cmState::ProjectKind::TryCompile);
  3327. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3328. if (!gg) {
  3329. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3330. "Global generator '" +
  3331. this->GetGlobalGenerator()->GetName() +
  3332. "' could not be created.");
  3333. cmSystemTools::SetFatalErrorOccurred();
  3334. this->IsSourceFileTryCompile = false;
  3335. return 1;
  3336. }
  3337. gg->RecursionDepth = this->RecursionDepth;
  3338. cm.SetGlobalGenerator(std::move(gg));
  3339. // copy trace state
  3340. cm.SetTraceRedirect(this->GetCMakeInstance());
  3341. // do a configure
  3342. cm.SetHomeDirectory(srcdir);
  3343. cm.SetHomeOutputDirectory(bindir);
  3344. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3345. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3346. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3347. cm.LoadCache();
  3348. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  3349. if (cmValue config =
  3350. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3351. // Tell the single-configuration generator which one to use.
  3352. // Add this before the user-provided CMake arguments in case
  3353. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3354. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3355. cmStateEnums::STRING);
  3356. }
  3357. }
  3358. cmValue recursionDepth =
  3359. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3360. if (recursionDepth) {
  3361. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3362. "Maximum recursion depth", cmStateEnums::STRING);
  3363. }
  3364. // if cmake args were provided then pass them in
  3365. if (cmakeArgs) {
  3366. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3367. //
  3368. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  3369. // However, there is a subtle problem when certain arguments are passed to
  3370. // a macro wrapping around try_compile or try_run that does not escape
  3371. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3372. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3373. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3374. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3375. // the try_compile or try_run does not get the proper value of VAR. If we
  3376. // call SetArgs here then it would treat "b" as the source directory and
  3377. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3378. // does not exist", thus breaking the try_compile or try_run completely.
  3379. //
  3380. // Strictly speaking the bug is in the wrapper macro because the CMake
  3381. // language has always flattened nested lists and the macro should escape
  3382. // the semicolons in its arguments before forwarding them. However, this
  3383. // bug is so subtle that projects typically work anyway, usually because
  3384. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3385. // correct result. Calling SetArgs here would break such projects that
  3386. // previously built. Instead we work around the issue by never reporting
  3387. // unused arguments and ignoring options such as --no-warn-unused-cli.
  3388. cm.SetWarnUnusedCli(false);
  3389. // cm.SetArgs(*cmakeArgs, true);
  3390. cm.SetCacheArgs(*cmakeArgs);
  3391. }
  3392. // to save time we pass the EnableLanguage info directly
  3393. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  3394. this->GetGlobalGenerator(), this);
  3395. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3396. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3397. cmStateEnums::INTERNAL);
  3398. } else {
  3399. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3400. cmStateEnums::INTERNAL);
  3401. }
  3402. if (cm.Configure() != 0) {
  3403. this->IssueMessage(MessageType::FATAL_ERROR,
  3404. "Failed to configure test project build system.");
  3405. cmSystemTools::SetFatalErrorOccurred();
  3406. this->IsSourceFileTryCompile = false;
  3407. return 1;
  3408. }
  3409. if (cm.Generate() != 0) {
  3410. this->IssueMessage(MessageType::FATAL_ERROR,
  3411. "Failed to generate test project build system.");
  3412. cmSystemTools::SetFatalErrorOccurred();
  3413. this->IsSourceFileTryCompile = false;
  3414. return 1;
  3415. }
  3416. // finally call the generator to actually build the resulting project
  3417. int ret = this->GetGlobalGenerator()->TryCompile(
  3418. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3419. this->IsSourceFileTryCompile = false;
  3420. return ret;
  3421. }
  3422. bool cmMakefile::GetIsSourceFileTryCompile() const
  3423. {
  3424. return this->IsSourceFileTryCompile;
  3425. }
  3426. cmake* cmMakefile::GetCMakeInstance() const
  3427. {
  3428. return this->GlobalGenerator->GetCMakeInstance();
  3429. }
  3430. cmMessenger* cmMakefile::GetMessenger() const
  3431. {
  3432. return this->GetCMakeInstance()->GetMessenger();
  3433. }
  3434. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3435. {
  3436. return this->GlobalGenerator;
  3437. }
  3438. #ifndef CMAKE_BOOTSTRAP
  3439. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3440. {
  3441. if (this->GetCMakeInstance() &&
  3442. this->GetCMakeInstance()->GetVariableWatch()) {
  3443. return this->GetCMakeInstance()->GetVariableWatch();
  3444. }
  3445. return nullptr;
  3446. }
  3447. #endif
  3448. cmState* cmMakefile::GetState() const
  3449. {
  3450. return this->GetCMakeInstance()->GetState();
  3451. }
  3452. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3453. {
  3454. cmake* cm = this->GetCMakeInstance();
  3455. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3456. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3457. // directly be fed to the compiler, which will be confused.
  3458. return;
  3459. }
  3460. cm->UpdateProgress(message, s);
  3461. #ifdef CMake_ENABLE_DEBUGGER
  3462. if (cm->GetDebugAdapter() != nullptr) {
  3463. cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
  3464. }
  3465. #endif
  3466. }
  3467. std::string cmMakefile::GetModulesFile(const std::string& filename,
  3468. bool& system, bool debug,
  3469. std::string& debugBuffer) const
  3470. {
  3471. std::string result;
  3472. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3473. // and then decide based on the policy setting which one to return.
  3474. // See CMP0017 for more details.
  3475. // The specific problem was that KDE 4.5.0 installs a
  3476. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3477. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3478. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3479. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3480. // new features, which were not there in the version from kdelibs, and so
  3481. // failed ("
  3482. std::string moduleInCMakeRoot;
  3483. std::string moduleInCMakeModulePath;
  3484. // Always search in CMAKE_MODULE_PATH:
  3485. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3486. if (cmakeModulePath) {
  3487. cmList modulePath{ *cmakeModulePath };
  3488. // Look through the possible module directories.
  3489. for (std::string itempl : modulePath) {
  3490. cmSystemTools::ConvertToUnixSlashes(itempl);
  3491. itempl += "/";
  3492. itempl += filename;
  3493. if (cmSystemTools::FileExists(itempl)) {
  3494. moduleInCMakeModulePath = itempl;
  3495. break;
  3496. }
  3497. if (debug) {
  3498. debugBuffer = cmStrCat(debugBuffer, " ", itempl, "\n");
  3499. }
  3500. }
  3501. }
  3502. // Always search in the standard modules location.
  3503. moduleInCMakeRoot =
  3504. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  3505. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3506. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3507. if (debug) {
  3508. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, "\n");
  3509. }
  3510. moduleInCMakeRoot.clear();
  3511. }
  3512. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3513. // from which we are being called is located itself in CMAKE_ROOT, then
  3514. // prefer results from CMAKE_ROOT depending on the policy setting.
  3515. system = false;
  3516. result = moduleInCMakeModulePath;
  3517. if (result.empty()) {
  3518. system = true;
  3519. result = moduleInCMakeRoot;
  3520. }
  3521. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3522. cmValue currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3523. std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
  3524. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  3525. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3526. case cmPolicies::WARN: {
  3527. std::ostringstream e;
  3528. /* clang-format off */
  3529. e << "File " << *currentFile << " includes "
  3530. << moduleInCMakeModulePath
  3531. << " (found via CMAKE_MODULE_PATH) which shadows "
  3532. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3533. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3534. /* clang-format on */
  3535. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3536. CM_FALLTHROUGH;
  3537. }
  3538. case cmPolicies::OLD:
  3539. system = false;
  3540. result = moduleInCMakeModulePath;
  3541. break;
  3542. case cmPolicies::REQUIRED_IF_USED:
  3543. case cmPolicies::REQUIRED_ALWAYS:
  3544. case cmPolicies::NEW:
  3545. system = true;
  3546. result = moduleInCMakeRoot;
  3547. break;
  3548. }
  3549. }
  3550. }
  3551. return result;
  3552. }
  3553. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3554. bool atOnly, bool escapeQuotes) const
  3555. {
  3556. // Split input to handle one line at a time.
  3557. std::string::const_iterator lineStart = input.begin();
  3558. while (lineStart != input.end()) {
  3559. // Find the end of this line.
  3560. std::string::const_iterator lineEnd = lineStart;
  3561. while (lineEnd != input.end() && *lineEnd != '\n') {
  3562. ++lineEnd;
  3563. }
  3564. // Copy the line.
  3565. std::string line(lineStart, lineEnd);
  3566. // Skip the newline character.
  3567. bool haveNewline = (lineEnd != input.end());
  3568. if (haveNewline) {
  3569. ++lineEnd;
  3570. }
  3571. // Replace #cmakedefine instances.
  3572. if (this->cmDefineRegex.find(line)) {
  3573. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3574. if (!cmIsOff(def)) {
  3575. const std::string indentation = this->cmDefineRegex.match(1);
  3576. cmSystemTools::ReplaceString(line,
  3577. cmStrCat("#", indentation, "cmakedefine"),
  3578. cmStrCat("#", indentation, "define"));
  3579. output += line;
  3580. } else {
  3581. output += "/* #undef ";
  3582. output += this->cmDefineRegex.match(2);
  3583. output += " */";
  3584. }
  3585. } else if (this->cmDefine01Regex.find(line)) {
  3586. const std::string indentation = this->cmDefine01Regex.match(1);
  3587. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3588. cmSystemTools::ReplaceString(line,
  3589. cmStrCat("#", indentation, "cmakedefine01"),
  3590. cmStrCat("#", indentation, "define"));
  3591. output += line;
  3592. if (!cmIsOff(def)) {
  3593. output += " 1";
  3594. } else {
  3595. output += " 0";
  3596. }
  3597. } else {
  3598. output += line;
  3599. }
  3600. if (haveNewline) {
  3601. output += "\n";
  3602. }
  3603. // Move to the next line.
  3604. lineStart = lineEnd;
  3605. }
  3606. // Perform variable replacements.
  3607. const char* filename = nullptr;
  3608. long lineNumber = -1;
  3609. if (!this->Backtrace.Empty()) {
  3610. const auto& currentTrace = this->Backtrace.Top();
  3611. filename = currentTrace.FilePath.c_str();
  3612. lineNumber = currentTrace.Line;
  3613. }
  3614. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3615. lineNumber, true, true);
  3616. }
  3617. int cmMakefile::ConfigureFile(const std::string& infile,
  3618. const std::string& outfile, bool copyonly,
  3619. bool atOnly, bool escapeQuotes,
  3620. mode_t permissions, cmNewLineStyle newLine)
  3621. {
  3622. int res = 1;
  3623. if (!this->CanIWriteThisFile(outfile)) {
  3624. cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
  3625. " into a source directory."));
  3626. return 0;
  3627. }
  3628. if (!cmSystemTools::FileExists(infile)) {
  3629. cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
  3630. return 0;
  3631. }
  3632. std::string soutfile = outfile;
  3633. const std::string& sinfile = infile;
  3634. this->AddCMakeDependFile(sinfile);
  3635. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3636. // Re-generate if non-temporary outputs are missing.
  3637. // when we finalize the configuration we will remove all
  3638. // output files that now don't exist.
  3639. this->AddCMakeOutputFile(soutfile);
  3640. if (permissions == 0) {
  3641. cmSystemTools::GetPermissions(sinfile, permissions);
  3642. }
  3643. std::string::size_type pos = soutfile.rfind('/');
  3644. if (pos != std::string::npos) {
  3645. std::string path = soutfile.substr(0, pos);
  3646. cmSystemTools::MakeDirectory(path);
  3647. }
  3648. if (copyonly) {
  3649. if (!cmSystemTools::CopyFileIfDifferent(sinfile, soutfile)) {
  3650. this->IssueMessage(MessageType::FATAL_ERROR,
  3651. cmSystemTools::GetLastSystemError());
  3652. return 0;
  3653. }
  3654. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3655. this->IssueMessage(MessageType::FATAL_ERROR,
  3656. cmSystemTools::GetLastSystemError());
  3657. return 0;
  3658. }
  3659. } else {
  3660. std::string newLineCharacters;
  3661. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3662. if (newLine.IsValid()) {
  3663. newLineCharacters = newLine.GetCharacters();
  3664. omode |= std::ios::binary;
  3665. } else {
  3666. newLineCharacters = "\n";
  3667. }
  3668. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3669. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3670. if (!fout) {
  3671. cmSystemTools::Error("Could not open file for write in copy operation " +
  3672. tempOutputFile);
  3673. cmSystemTools::ReportLastSystemError("");
  3674. return 0;
  3675. }
  3676. cmsys::ifstream fin(sinfile.c_str());
  3677. if (!fin) {
  3678. cmSystemTools::Error("Could not open file for read in copy operation " +
  3679. sinfile);
  3680. return 0;
  3681. }
  3682. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3683. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3684. std::ostringstream e;
  3685. e << "File starts with a Byte-Order-Mark that is not UTF-8:\n "
  3686. << sinfile;
  3687. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3688. return 0;
  3689. }
  3690. // rewind to copy BOM to output file
  3691. fin.seekg(0);
  3692. // now copy input to output and expand variables in the
  3693. // input file at the same time
  3694. std::string inLine;
  3695. std::string outLine;
  3696. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3697. outLine.clear();
  3698. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3699. fout << outLine << newLineCharacters;
  3700. }
  3701. // close the files before attempting to copy
  3702. fin.close();
  3703. fout.close();
  3704. if (!cmSystemTools::CopyFileIfDifferent(tempOutputFile, soutfile)) {
  3705. this->IssueMessage(MessageType::FATAL_ERROR,
  3706. cmSystemTools::GetLastSystemError());
  3707. res = 0;
  3708. } else {
  3709. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3710. this->IssueMessage(MessageType::FATAL_ERROR,
  3711. cmSystemTools::GetLastSystemError());
  3712. res = 0;
  3713. }
  3714. }
  3715. cmSystemTools::RemoveFile(tempOutputFile);
  3716. }
  3717. return res;
  3718. }
  3719. void cmMakefile::SetProperty(const std::string& prop, cmValue value)
  3720. {
  3721. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3722. }
  3723. void cmMakefile::AppendProperty(const std::string& prop,
  3724. const std::string& value, bool asString)
  3725. {
  3726. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3727. this->Backtrace);
  3728. }
  3729. cmValue cmMakefile::GetProperty(const std::string& prop) const
  3730. {
  3731. // Check for computed properties.
  3732. static std::string output;
  3733. if (prop == "TESTS"_s) {
  3734. std::vector<std::string> keys;
  3735. // get list of keys
  3736. const auto* t = this;
  3737. std::transform(
  3738. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3739. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3740. output = cmList::to_string(keys);
  3741. return cmValue(output);
  3742. }
  3743. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3744. }
  3745. cmValue cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3746. {
  3747. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3748. }
  3749. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3750. {
  3751. return cmIsOn(this->GetProperty(prop));
  3752. }
  3753. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3754. {
  3755. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3756. }
  3757. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3758. {
  3759. auto i = this->Targets.find(name);
  3760. if (i != this->Targets.end()) {
  3761. return &i->second;
  3762. }
  3763. return nullptr;
  3764. }
  3765. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3766. {
  3767. cmTest* test = this->GetTest(testName);
  3768. if (test) {
  3769. return test;
  3770. }
  3771. auto newTest = cm::make_unique<cmTest>(this);
  3772. test = newTest.get();
  3773. newTest->SetName(testName);
  3774. this->Tests[testName] = std::move(newTest);
  3775. return test;
  3776. }
  3777. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3778. {
  3779. auto mi = this->Tests.find(testName);
  3780. if (mi != this->Tests.end()) {
  3781. return mi->second.get();
  3782. }
  3783. return nullptr;
  3784. }
  3785. void cmMakefile::GetTests(const std::string& config,
  3786. std::vector<cmTest*>& tests) const
  3787. {
  3788. for (const auto& generator : this->GetTestGenerators()) {
  3789. if (generator->TestsForConfig(config)) {
  3790. tests.push_back(generator->GetTest());
  3791. }
  3792. }
  3793. }
  3794. void cmMakefile::AddCMakeDependFilesFromUser()
  3795. {
  3796. cmList deps;
  3797. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3798. deps.assign(*deps_str);
  3799. }
  3800. for (auto const& dep : deps) {
  3801. if (cmSystemTools::FileIsFullPath(dep)) {
  3802. this->AddCMakeDependFile(dep);
  3803. } else {
  3804. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3805. this->AddCMakeDependFile(f);
  3806. }
  3807. }
  3808. }
  3809. std::string cmMakefile::FormatListFileStack() const
  3810. {
  3811. std::vector<std::string> listFiles;
  3812. cmStateSnapshot snp = this->StateSnapshot;
  3813. while (snp.IsValid()) {
  3814. listFiles.push_back(snp.GetExecutionListFile());
  3815. snp = snp.GetCallStackParent();
  3816. }
  3817. std::reverse(listFiles.begin(), listFiles.end());
  3818. std::ostringstream tmp;
  3819. size_t depth = listFiles.size();
  3820. if (depth > 0) {
  3821. auto it = listFiles.end();
  3822. do {
  3823. if (depth != listFiles.size()) {
  3824. tmp << "\n ";
  3825. }
  3826. --it;
  3827. tmp << "[";
  3828. tmp << depth;
  3829. tmp << "]\t";
  3830. tmp << *it;
  3831. depth--;
  3832. } while (it != listFiles.begin());
  3833. }
  3834. return tmp.str();
  3835. }
  3836. void cmMakefile::PushScope()
  3837. {
  3838. this->StateSnapshot =
  3839. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3840. this->PushLoopBlockBarrier();
  3841. #if !defined(CMAKE_BOOTSTRAP)
  3842. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3843. #endif
  3844. }
  3845. void cmMakefile::PopScope()
  3846. {
  3847. #if !defined(CMAKE_BOOTSTRAP)
  3848. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3849. #endif
  3850. this->PopLoopBlockBarrier();
  3851. this->PopSnapshot();
  3852. }
  3853. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3854. {
  3855. if (var.empty()) {
  3856. return;
  3857. }
  3858. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3859. std::ostringstream m;
  3860. m << "Cannot set \"" << var << "\": current scope has no parent.";
  3861. this->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  3862. return;
  3863. }
  3864. #ifndef CMAKE_BOOTSTRAP
  3865. cmVariableWatch* vv = this->GetVariableWatch();
  3866. if (vv) {
  3867. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3868. varDef, this);
  3869. }
  3870. #endif
  3871. }
  3872. void cmMakefile::RaiseScope(const std::vector<std::string>& variables)
  3873. {
  3874. for (auto const& varName : variables) {
  3875. if (this->IsNormalDefinitionSet(varName)) {
  3876. this->RaiseScope(varName, this->GetDefinition(varName));
  3877. } else {
  3878. // unset variable in parent scope
  3879. this->RaiseScope(varName, nullptr);
  3880. }
  3881. }
  3882. }
  3883. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3884. cmStateEnums::TargetType type,
  3885. bool global)
  3886. {
  3887. // Create the target.
  3888. std::unique_ptr<cmTarget> target(
  3889. new cmTarget(name, type,
  3890. global ? cmTarget::Visibility::ImportedGlobally
  3891. : cmTarget::Visibility::Imported,
  3892. this, cmTarget::PerConfig::Yes));
  3893. // Add to the set of available imported targets.
  3894. this->ImportedTargets[name] = target.get();
  3895. this->GetGlobalGenerator()->IndexTarget(target.get());
  3896. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3897. // Transfer ownership to this cmMakefile object.
  3898. this->ImportedTargetsOwned.push_back(std::move(target));
  3899. return this->ImportedTargetsOwned.back().get();
  3900. }
  3901. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3902. bool excludeAliases) const
  3903. {
  3904. // Look for an imported target. These take priority because they
  3905. // are more local in scope and do not have to be globally unique.
  3906. auto targetName = name;
  3907. if (!excludeAliases) {
  3908. // Look for local alias targets.
  3909. auto alias = this->AliasTargets.find(name);
  3910. if (alias != this->AliasTargets.end()) {
  3911. targetName = alias->second;
  3912. }
  3913. }
  3914. auto imported = this->ImportedTargets.find(targetName);
  3915. if (imported != this->ImportedTargets.end()) {
  3916. return imported->second;
  3917. }
  3918. // Look for a target built in this directory.
  3919. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3920. return t;
  3921. }
  3922. // Look for a target built in this project.
  3923. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3924. }
  3925. bool cmMakefile::IsAlias(const std::string& name) const
  3926. {
  3927. if (cm::contains(this->AliasTargets, name)) {
  3928. return true;
  3929. }
  3930. return this->GetGlobalGenerator()->IsAlias(name);
  3931. }
  3932. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3933. bool isCustom) const
  3934. {
  3935. if (this->IsAlias(name)) {
  3936. std::ostringstream e;
  3937. e << "cannot create target \"" << name
  3938. << "\" because an alias with the same name already exists.";
  3939. msg = e.str();
  3940. return false;
  3941. }
  3942. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3943. // The name given conflicts with an existing target. Produce an
  3944. // error in a compatible way.
  3945. if (existing->IsImported()) {
  3946. // Imported targets were not supported in previous versions.
  3947. // This is new code, so we can make it an error.
  3948. std::ostringstream e;
  3949. e << "cannot create target \"" << name
  3950. << "\" because an imported target with the same name already exists.";
  3951. msg = e.str();
  3952. return false;
  3953. }
  3954. // target names must be globally unique
  3955. switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
  3956. case cmPolicies::WARN:
  3957. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3958. cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
  3959. CM_FALLTHROUGH;
  3960. case cmPolicies::OLD:
  3961. return true;
  3962. case cmPolicies::REQUIRED_IF_USED:
  3963. case cmPolicies::REQUIRED_ALWAYS:
  3964. this->IssueMessage(
  3965. MessageType::FATAL_ERROR,
  3966. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
  3967. return true;
  3968. case cmPolicies::NEW:
  3969. break;
  3970. }
  3971. // The conflict is with a non-imported target.
  3972. // Allow this if the user has requested support.
  3973. cmake* cm = this->GetCMakeInstance();
  3974. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3975. this != existing->GetMakefile() &&
  3976. cm->GetState()->GetGlobalPropertyAsBool(
  3977. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3978. return true;
  3979. }
  3980. // Produce an error that tells the user how to work around the
  3981. // problem.
  3982. std::ostringstream e;
  3983. e << "cannot create target \"" << name
  3984. << "\" because another target with the same name already exists. "
  3985. << "The existing target is ";
  3986. switch (existing->GetType()) {
  3987. case cmStateEnums::EXECUTABLE:
  3988. e << "an executable ";
  3989. break;
  3990. case cmStateEnums::STATIC_LIBRARY:
  3991. e << "a static library ";
  3992. break;
  3993. case cmStateEnums::SHARED_LIBRARY:
  3994. e << "a shared library ";
  3995. break;
  3996. case cmStateEnums::MODULE_LIBRARY:
  3997. e << "a module library ";
  3998. break;
  3999. case cmStateEnums::UTILITY:
  4000. e << "a custom target ";
  4001. break;
  4002. case cmStateEnums::INTERFACE_LIBRARY:
  4003. e << "an interface library ";
  4004. break;
  4005. default:
  4006. break;
  4007. }
  4008. e << "created in source directory \""
  4009. << existing->GetMakefile()->GetCurrentSourceDirectory() << "\". "
  4010. << "See documentation for policy CMP0002 for more details.";
  4011. msg = e.str();
  4012. return false;
  4013. }
  4014. return true;
  4015. }
  4016. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  4017. const std::string& binPath) const
  4018. {
  4019. // Make sure the binary directory is unique.
  4020. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  4021. if (gg->BinaryDirectoryIsNew(binPath)) {
  4022. return true;
  4023. }
  4024. std::ostringstream e;
  4025. switch (this->GetPolicyStatus(cmPolicies::CMP0013)) {
  4026. case cmPolicies::WARN:
  4027. // Print the warning.
  4028. /* clang-format off */
  4029. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0013)
  4030. << "\n"
  4031. << "The binary directory\n"
  4032. << " " << binPath << "\n"
  4033. << "is already used to build a source directory. "
  4034. << "This command uses it to build source directory\n"
  4035. << " " << srcPath << "\n"
  4036. << "which can generate conflicting build files. "
  4037. << "CMake does not support this use case but it used "
  4038. << "to work accidentally and is being allowed for "
  4039. << "compatibility.";
  4040. /* clang-format on */
  4041. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  4042. CM_FALLTHROUGH;
  4043. case cmPolicies::OLD:
  4044. // OLD behavior does not warn.
  4045. return true;
  4046. case cmPolicies::REQUIRED_IF_USED:
  4047. case cmPolicies::REQUIRED_ALWAYS:
  4048. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0013) << "\n";
  4049. CM_FALLTHROUGH;
  4050. case cmPolicies::NEW:
  4051. // NEW behavior prints the error.
  4052. /* clang-format off */
  4053. e << "The binary directory\n"
  4054. << " " << binPath << "\n"
  4055. << "is already used to build a source directory. "
  4056. << "It cannot be used to build source directory\n"
  4057. << " " << srcPath << "\n"
  4058. << "Specify a unique binary directory name.";
  4059. /* clang-format on */
  4060. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4061. break;
  4062. }
  4063. return false;
  4064. }
  4065. static std::string const matchVariables[] = {
  4066. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  4067. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  4068. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  4069. };
  4070. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  4071. void cmMakefile::ClearMatches()
  4072. {
  4073. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  4074. if (!nMatchesStr) {
  4075. return;
  4076. }
  4077. int nMatches = atoi(nMatchesStr->c_str());
  4078. for (int i = 0; i <= nMatches; i++) {
  4079. std::string const& var = matchVariables[i];
  4080. std::string const& s = this->GetSafeDefinition(var);
  4081. if (!s.empty()) {
  4082. this->AddDefinition(var, "");
  4083. this->MarkVariableAsUsed(var);
  4084. }
  4085. }
  4086. this->AddDefinition(nMatchesVariable, "0");
  4087. this->MarkVariableAsUsed(nMatchesVariable);
  4088. }
  4089. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  4090. {
  4091. char highest = 0;
  4092. for (int i = 0; i < 10; i++) {
  4093. std::string const& m = re.match(i);
  4094. if (!m.empty()) {
  4095. std::string const& var = matchVariables[i];
  4096. this->AddDefinition(var, m);
  4097. this->MarkVariableAsUsed(var);
  4098. highest = static_cast<char>('0' + i);
  4099. }
  4100. }
  4101. char nMatches[] = { highest, '\0' };
  4102. this->AddDefinition(nMatchesVariable, nMatches);
  4103. this->MarkVariableAsUsed(nMatchesVariable);
  4104. }
  4105. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  4106. {
  4107. return this->StateSnapshot;
  4108. }
  4109. const char* cmMakefile::GetDefineFlagsCMP0059() const
  4110. {
  4111. return this->DefineFlagsOrig.c_str();
  4112. }
  4113. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  4114. bool parent_scope) const
  4115. {
  4116. return this->StateSnapshot.GetPolicy(id, parent_scope);
  4117. }
  4118. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  4119. {
  4120. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  4121. if (cmValue val = this->GetDefinition(var)) {
  4122. return cmIsOn(val);
  4123. }
  4124. // Enable optional policy warnings with --debug-output, --trace,
  4125. // or --trace-expand.
  4126. cmake* cm = this->GetCMakeInstance();
  4127. return cm->GetDebugOutput() || cm->GetTrace();
  4128. }
  4129. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  4130. {
  4131. cmPolicies::PolicyID pid;
  4132. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  4133. std::ostringstream e;
  4134. e << "Policy \"" << id << "\" is not known to this version of CMake.";
  4135. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4136. return false;
  4137. }
  4138. return this->SetPolicy(pid, status);
  4139. }
  4140. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  4141. cmPolicies::PolicyStatus status)
  4142. {
  4143. // A REQUIRED_ALWAYS policy may be set only to NEW.
  4144. if (status != cmPolicies::NEW &&
  4145. cmPolicies::GetPolicyStatus(id) == cmPolicies::REQUIRED_ALWAYS) {
  4146. std::string msg = cmPolicies::GetRequiredAlwaysPolicyError(id);
  4147. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  4148. return false;
  4149. }
  4150. // Deprecate old policies.
  4151. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0126 &&
  4152. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  4153. (
  4154. // Policies set by cmCoreTryCompile::TryCompileCode.
  4155. id == cmPolicies::CMP0065 || id == cmPolicies::CMP0083 ||
  4156. id == cmPolicies::CMP0091 || id == cmPolicies::CMP0104 ||
  4157. id == cmPolicies::CMP0123 || id == cmPolicies::CMP0126)) &&
  4158. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  4159. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  4160. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  4161. cmPolicies::GetPolicyDeprecatedWarning(id));
  4162. }
  4163. this->StateSnapshot.SetPolicy(id, status);
  4164. return true;
  4165. }
  4166. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  4167. : Makefile(m)
  4168. {
  4169. this->Makefile->PushPolicy();
  4170. }
  4171. cmMakefile::PolicyPushPop::~PolicyPushPop()
  4172. {
  4173. this->Makefile->PopPolicy();
  4174. }
  4175. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  4176. {
  4177. this->StateSnapshot.PushPolicy(pm, weak);
  4178. }
  4179. void cmMakefile::PopPolicy()
  4180. {
  4181. if (!this->StateSnapshot.PopPolicy()) {
  4182. this->IssueMessage(MessageType::FATAL_ERROR,
  4183. "cmake_policy POP without matching PUSH");
  4184. }
  4185. }
  4186. void cmMakefile::PopSnapshot(bool reportError)
  4187. {
  4188. // cmStateSnapshot manages nested policy scopes within it.
  4189. // Since the scope corresponding to the snapshot is closing,
  4190. // reject any still-open nested policy scopes with an error.
  4191. while (this->StateSnapshot.CanPopPolicyScope()) {
  4192. if (reportError) {
  4193. this->IssueMessage(MessageType::FATAL_ERROR,
  4194. "cmake_policy PUSH without matching POP");
  4195. reportError = false;
  4196. }
  4197. this->PopPolicy();
  4198. }
  4199. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  4200. assert(this->StateSnapshot.IsValid());
  4201. }
  4202. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  4203. std::string const& version_max)
  4204. {
  4205. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  4206. cmPolicies::WarnCompat::On);
  4207. }
  4208. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  4209. : Makefile(m)
  4210. {
  4211. this->Makefile->StateSnapshot =
  4212. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  4213. this->Makefile->StateSnapshot);
  4214. }
  4215. cmMakefile::VariablePushPop::~VariablePushPop()
  4216. {
  4217. this->Makefile->PopSnapshot();
  4218. }
  4219. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  4220. cmListFileContext const& context) const
  4221. {
  4222. return !this->CMP0054ReportedIds.insert(context).second;
  4223. }
  4224. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  4225. {
  4226. /* Record the setting of every policy. */
  4227. using PolicyID = cmPolicies::PolicyID;
  4228. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  4229. pid = static_cast<PolicyID>(pid + 1)) {
  4230. pm.Set(pid, this->GetPolicyStatus(pid));
  4231. }
  4232. }
  4233. bool cmMakefile::IgnoreErrorsCMP0061() const
  4234. {
  4235. bool ignoreErrors = true;
  4236. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  4237. case cmPolicies::WARN:
  4238. // No warning for this policy!
  4239. CM_FALLTHROUGH;
  4240. case cmPolicies::OLD:
  4241. break;
  4242. case cmPolicies::REQUIRED_IF_USED:
  4243. case cmPolicies::REQUIRED_ALWAYS:
  4244. case cmPolicies::NEW:
  4245. ignoreErrors = false;
  4246. break;
  4247. }
  4248. return ignoreErrors;
  4249. }
  4250. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  4251. const std::string& fileName,
  4252. cmPolicies::PolicyMap const& pm)
  4253. : Makefile(mf)
  4254. {
  4255. this->Makefile->PushFunctionScope(fileName, pm);
  4256. }
  4257. cmMakefile::FunctionPushPop::~FunctionPushPop()
  4258. {
  4259. this->Makefile->PopFunctionScope(this->ReportError);
  4260. }
  4261. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  4262. const std::string& fileName,
  4263. const cmPolicies::PolicyMap& pm)
  4264. : Makefile(mf)
  4265. {
  4266. this->Makefile->PushMacroScope(fileName, pm);
  4267. }
  4268. cmMakefile::MacroPushPop::~MacroPushPop()
  4269. {
  4270. this->Makefile->PopMacroScope(this->ReportError);
  4271. }
  4272. cmMakefile::FindPackageStackRAII::FindPackageStackRAII(cmMakefile* mf,
  4273. std::string const& name)
  4274. : Makefile(mf)
  4275. {
  4276. this->Makefile->FindPackageStack =
  4277. this->Makefile->FindPackageStack.Push(cmFindPackageCall{
  4278. name,
  4279. this->Makefile->FindPackageStackNextIndex,
  4280. });
  4281. this->Makefile->FindPackageStackNextIndex++;
  4282. }
  4283. cmMakefile::FindPackageStackRAII::~FindPackageStackRAII()
  4284. {
  4285. this->Makefile->FindPackageStackNextIndex =
  4286. this->Makefile->FindPackageStack.Top().Index + 1;
  4287. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  4288. if (!this->Makefile->FindPackageStack.Empty()) {
  4289. auto top = this->Makefile->FindPackageStack.Top();
  4290. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  4291. top.Index = this->Makefile->FindPackageStackNextIndex;
  4292. this->Makefile->FindPackageStackNextIndex++;
  4293. this->Makefile->FindPackageStack =
  4294. this->Makefile->FindPackageStack.Push(top);
  4295. }
  4296. }
  4297. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  4298. std::string const& pkg)
  4299. : Makefile(mf)
  4300. , OldValue(this->Makefile->DebugFindPkg)
  4301. {
  4302. this->Makefile->DebugFindPkg =
  4303. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  4304. }
  4305. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  4306. {
  4307. this->Makefile->DebugFindPkg = this->OldValue;
  4308. }
  4309. bool cmMakefile::GetDebugFindPkgMode() const
  4310. {
  4311. return this->DebugFindPkg;
  4312. }