cmMakefile.cxx 149 KB

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