cmMakefile.cxx 150 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789
  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::PlatformIsAppleSimulator() const
  2269. {
  2270. return std::set<AppleSDK>{
  2271. AppleSDK::AppleTVSimulator,
  2272. AppleSDK::IPhoneSimulator,
  2273. AppleSDK::WatchSimulator,
  2274. AppleSDK::XRSimulator,
  2275. }
  2276. .count(this->GetAppleSDKType());
  2277. }
  2278. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  2279. {
  2280. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  2281. }
  2282. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2283. {
  2284. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2285. if (!language.empty()) {
  2286. name += "_";
  2287. name += language;
  2288. }
  2289. name += "_FLAG";
  2290. return this->GetDefinition(name).GetCStr();
  2291. }
  2292. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2293. {
  2294. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2295. return true;
  2296. }
  2297. // If we are doing an in-source build, then the test will always fail
  2298. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2299. this->GetHomeOutputDirectory())) {
  2300. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2301. }
  2302. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2303. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2304. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2305. }
  2306. const std::string& cmMakefile::GetRequiredDefinition(
  2307. const std::string& name) const
  2308. {
  2309. static std::string const empty;
  2310. cmValue def = this->GetDefinition(name);
  2311. if (!def) {
  2312. cmSystemTools::Error("Error required internal CMake variable not "
  2313. "set, cmake may not be built correctly.\n"
  2314. "Missing variable is:\n" +
  2315. name);
  2316. return empty;
  2317. }
  2318. return *def;
  2319. }
  2320. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2321. {
  2322. cmValue def = this->StateSnapshot.GetDefinition(name);
  2323. if (!def) {
  2324. def = this->GetState()->GetInitializedCacheValue(name);
  2325. }
  2326. #ifndef CMAKE_BOOTSTRAP
  2327. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2328. if (!def) {
  2329. vv->VariableAccessed(
  2330. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2331. }
  2332. }
  2333. #endif
  2334. return def != nullptr;
  2335. }
  2336. bool cmMakefile::IsNormalDefinitionSet(const std::string& name) const
  2337. {
  2338. cmValue def = this->StateSnapshot.GetDefinition(name);
  2339. #ifndef CMAKE_BOOTSTRAP
  2340. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2341. if (!def) {
  2342. vv->VariableAccessed(
  2343. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2344. }
  2345. }
  2346. #endif
  2347. return def != nullptr;
  2348. }
  2349. cmValue cmMakefile::GetDefinition(const std::string& name) const
  2350. {
  2351. cmValue def = this->StateSnapshot.GetDefinition(name);
  2352. if (!def) {
  2353. def = this->GetState()->GetInitializedCacheValue(name);
  2354. }
  2355. #ifndef CMAKE_BOOTSTRAP
  2356. cmVariableWatch* vv = this->GetVariableWatch();
  2357. if (vv && !this->SuppressSideEffects) {
  2358. bool const watch_function_executed =
  2359. vv->VariableAccessed(name,
  2360. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2361. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2362. def.GetCStr(), this);
  2363. if (watch_function_executed) {
  2364. // A callback was executed and may have caused re-allocation of the
  2365. // variable storage. Look it up again for now.
  2366. // FIXME: Refactor variable storage to avoid this problem.
  2367. def = this->StateSnapshot.GetDefinition(name);
  2368. if (!def) {
  2369. def = this->GetState()->GetInitializedCacheValue(name);
  2370. }
  2371. }
  2372. }
  2373. #endif
  2374. return def;
  2375. }
  2376. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2377. {
  2378. return this->GetDefinition(name);
  2379. }
  2380. std::vector<std::string> cmMakefile::GetDefinitions() const
  2381. {
  2382. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2383. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2384. std::sort(res.begin(), res.end());
  2385. return res;
  2386. }
  2387. const std::string& cmMakefile::ExpandVariablesInString(
  2388. std::string& source) const
  2389. {
  2390. return this->ExpandVariablesInString(source, false, false);
  2391. }
  2392. const std::string& cmMakefile::ExpandVariablesInString(
  2393. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2394. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2395. {
  2396. bool compareResults = false;
  2397. MessageType mtype = MessageType::LOG;
  2398. std::string errorstr;
  2399. std::string original;
  2400. // Sanity check the @ONLY mode.
  2401. if (atOnly && (!noEscapes || !removeEmpty)) {
  2402. // This case should never be called. At-only is for
  2403. // configure-file/string which always does no escapes.
  2404. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2405. "ExpandVariablesInString @ONLY called "
  2406. "on something with escapes.");
  2407. return source;
  2408. }
  2409. // Variables used in the WARN case.
  2410. std::string newResult;
  2411. std::string newErrorstr;
  2412. MessageType newError = MessageType::LOG;
  2413. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2414. case cmPolicies::WARN: {
  2415. // Save the original string for the warning.
  2416. original = source;
  2417. newResult = source;
  2418. compareResults = true;
  2419. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2420. // dereferences since the OLD behavior is still what is actually used.
  2421. this->SuppressSideEffects = true;
  2422. newError = this->ExpandVariablesInStringNew(
  2423. newErrorstr, newResult, escapeQuotes, noEscapes, atOnly, filename,
  2424. line, replaceAt);
  2425. this->SuppressSideEffects = false;
  2426. CM_FALLTHROUGH;
  2427. }
  2428. case cmPolicies::OLD:
  2429. mtype = this->ExpandVariablesInStringOld(errorstr, source, escapeQuotes,
  2430. noEscapes, atOnly, filename,
  2431. line, removeEmpty, true);
  2432. break;
  2433. case cmPolicies::REQUIRED_IF_USED:
  2434. case cmPolicies::REQUIRED_ALWAYS:
  2435. // Messaging here would be *very* verbose.
  2436. case cmPolicies::NEW:
  2437. mtype = this->ExpandVariablesInStringNew(errorstr, source, escapeQuotes,
  2438. noEscapes, atOnly, filename,
  2439. line, replaceAt);
  2440. break;
  2441. }
  2442. // If it's an error in either case, just report the error...
  2443. if (mtype != MessageType::LOG) {
  2444. if (mtype == MessageType::FATAL_ERROR) {
  2445. cmSystemTools::SetFatalErrorOccurred();
  2446. }
  2447. this->IssueMessage(mtype, errorstr);
  2448. }
  2449. // ...otherwise, see if there's a difference that needs to be warned about.
  2450. else if (compareResults && (newResult != source || newError != mtype)) {
  2451. std::string msg =
  2452. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0053), '\n');
  2453. std::string msg_input = original;
  2454. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2455. msg += "For input:\n '";
  2456. msg += msg_input;
  2457. msg += "'\n";
  2458. std::string msg_old = source;
  2459. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2460. msg += "the old evaluation rules produce:\n '";
  2461. msg += msg_old;
  2462. msg += "'\n";
  2463. if (newError == mtype) {
  2464. std::string msg_new = newResult;
  2465. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2466. msg += "but the new evaluation rules produce:\n '";
  2467. msg += msg_new;
  2468. msg += "'\n";
  2469. } else {
  2470. std::string msg_err = newErrorstr;
  2471. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2472. msg += "but the new evaluation rules produce an error:\n ";
  2473. msg += msg_err;
  2474. msg += "\n";
  2475. }
  2476. msg +=
  2477. "Using the old result for compatibility since the policy is not set.";
  2478. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2479. }
  2480. return source;
  2481. }
  2482. MessageType cmMakefile::ExpandVariablesInStringOld(
  2483. std::string& errorstr, std::string& source, bool escapeQuotes,
  2484. bool noEscapes, bool atOnly, const char* filename, long line,
  2485. bool removeEmpty, bool replaceAt) const
  2486. {
  2487. // Fast path strings without any special characters.
  2488. if (source.find_first_of("$@\\") == std::string::npos) {
  2489. return MessageType::LOG;
  2490. }
  2491. // Special-case the @ONLY mode.
  2492. if (atOnly) {
  2493. // Store an original copy of the input.
  2494. std::string input = source;
  2495. // Start with empty output.
  2496. source.clear();
  2497. // Look for one @VAR@ at a time.
  2498. const char* in = input.c_str();
  2499. while (this->cmAtVarRegex.find(in)) {
  2500. // Get the range of the string to replace.
  2501. const char* first = in + this->cmAtVarRegex.start();
  2502. const char* last = in + this->cmAtVarRegex.end();
  2503. // Store the unchanged part of the string now.
  2504. source.append(in, first - in);
  2505. // Lookup the definition of VAR.
  2506. std::string var(first + 1, last - first - 2);
  2507. if (cmValue val = this->GetDefinition(var)) {
  2508. // Store the value in the output escaping as requested.
  2509. if (escapeQuotes) {
  2510. source.append(cmEscapeQuotes(*val));
  2511. } else {
  2512. source.append(*val);
  2513. }
  2514. }
  2515. // Continue looking for @VAR@ further along the string.
  2516. in = last;
  2517. }
  2518. // Append the rest of the unchanged part of the string.
  2519. source.append(in);
  2520. return MessageType::LOG;
  2521. }
  2522. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2523. // with GetDefinition(), if not found in the map, nothing is expanded.
  2524. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2525. // the current environment variables.
  2526. cmCommandArgumentParserHelper parser;
  2527. parser.SetMakefile(this);
  2528. parser.SetLineFile(line, filename);
  2529. parser.SetEscapeQuotes(escapeQuotes);
  2530. parser.SetNoEscapeMode(noEscapes);
  2531. parser.SetReplaceAtSyntax(replaceAt);
  2532. parser.SetRemoveEmpty(removeEmpty);
  2533. int res = parser.ParseString(source, 0);
  2534. const char* emsg = parser.GetError();
  2535. MessageType mtype = MessageType::LOG;
  2536. if (res && !emsg[0]) {
  2537. source = parser.GetResult();
  2538. } else {
  2539. // Construct the main error message.
  2540. std::ostringstream error;
  2541. error << "Syntax error in cmake code ";
  2542. if (filename && line > 0) {
  2543. // This filename and line number may be more specific than the
  2544. // command context because one command invocation can have
  2545. // arguments on multiple lines.
  2546. error << "at\n"
  2547. << " " << filename << ":" << line << "\n";
  2548. }
  2549. error << "when parsing string\n"
  2550. << " " << source << "\n";
  2551. error << emsg;
  2552. // If the parser failed ("res" is false) then this is a real
  2553. // argument parsing error, so the policy applies. Otherwise the
  2554. // parser reported an error message without failing because the
  2555. // helper implementation is unhappy, which has always reported an
  2556. // error.
  2557. mtype = MessageType::FATAL_ERROR;
  2558. if (!res) {
  2559. // This is a real argument parsing error. Use policy CMP0010 to
  2560. // decide whether it is an error.
  2561. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2562. case cmPolicies::WARN:
  2563. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2564. CM_FALLTHROUGH;
  2565. case cmPolicies::OLD:
  2566. // OLD behavior is to just warn and continue.
  2567. mtype = MessageType::AUTHOR_WARNING;
  2568. break;
  2569. case cmPolicies::REQUIRED_IF_USED:
  2570. case cmPolicies::REQUIRED_ALWAYS:
  2571. error << "\n"
  2572. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2573. break;
  2574. case cmPolicies::NEW:
  2575. // NEW behavior is to report the error.
  2576. break;
  2577. }
  2578. }
  2579. errorstr = error.str();
  2580. }
  2581. return mtype;
  2582. }
  2583. enum t_domain
  2584. {
  2585. NORMAL,
  2586. ENVIRONMENT,
  2587. CACHE
  2588. };
  2589. struct t_lookup
  2590. {
  2591. t_domain domain = NORMAL;
  2592. size_t loc = 0;
  2593. };
  2594. bool cmMakefile::IsProjectFile(const char* filename) const
  2595. {
  2596. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2597. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2598. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2599. }
  2600. size_t cmMakefile::GetRecursionDepthLimit() const
  2601. {
  2602. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2603. if (cmValue depthStr =
  2604. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2605. unsigned long depthUL;
  2606. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2607. depth = depthUL;
  2608. }
  2609. } else if (cm::optional<std::string> depthEnv =
  2610. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2611. unsigned long depthUL;
  2612. if (cmStrToULong(*depthEnv, &depthUL)) {
  2613. depth = depthUL;
  2614. }
  2615. }
  2616. return depth;
  2617. }
  2618. size_t cmMakefile::GetRecursionDepth() const
  2619. {
  2620. return this->RecursionDepth;
  2621. }
  2622. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2623. {
  2624. this->RecursionDepth = recursionDepth;
  2625. }
  2626. std::string cmMakefile::NewDeferId() const
  2627. {
  2628. return this->GetGlobalGenerator()->NewDeferId();
  2629. }
  2630. bool cmMakefile::DeferCall(std::string id, std::string file,
  2631. cmListFileFunction lff)
  2632. {
  2633. if (!this->Defer) {
  2634. return false;
  2635. }
  2636. this->Defer->Commands.emplace_back(
  2637. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2638. return true;
  2639. }
  2640. bool cmMakefile::DeferCancelCall(std::string const& id)
  2641. {
  2642. if (!this->Defer) {
  2643. return false;
  2644. }
  2645. for (DeferCommand& dc : this->Defer->Commands) {
  2646. if (dc.Id == id) {
  2647. dc.Id.clear();
  2648. }
  2649. }
  2650. return true;
  2651. }
  2652. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2653. {
  2654. cm::optional<std::string> ids;
  2655. if (this->Defer) {
  2656. ids = cmList::to_string(
  2657. cmMakeRange(this->Defer->Commands)
  2658. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2659. .transform(
  2660. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
  2661. }
  2662. return ids;
  2663. }
  2664. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2665. {
  2666. cm::optional<std::string> call;
  2667. if (this->Defer) {
  2668. std::string tmp;
  2669. for (DeferCommand const& dc : this->Defer->Commands) {
  2670. if (dc.Id == id) {
  2671. tmp = dc.Command.OriginalName();
  2672. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2673. tmp = cmStrCat(tmp, ';', arg.Value);
  2674. }
  2675. break;
  2676. }
  2677. }
  2678. call = std::move(tmp);
  2679. }
  2680. return call;
  2681. }
  2682. MessageType cmMakefile::ExpandVariablesInStringNew(
  2683. std::string& errorstr, std::string& source, bool escapeQuotes,
  2684. bool noEscapes, bool atOnly, const char* filename, long line,
  2685. bool replaceAt) const
  2686. {
  2687. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2688. // with GetDefinition(), if not found in the map, nothing is expanded.
  2689. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2690. // the current environment variables.
  2691. const char* in = source.c_str();
  2692. const char* last = in;
  2693. std::string result;
  2694. result.reserve(source.size());
  2695. std::vector<t_lookup> openstack;
  2696. bool error = false;
  2697. bool done = false;
  2698. MessageType mtype = MessageType::LOG;
  2699. cmState* state = this->GetCMakeInstance()->GetState();
  2700. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2701. do {
  2702. char inc = *in;
  2703. switch (inc) {
  2704. case '}':
  2705. if (!openstack.empty()) {
  2706. t_lookup var = openstack.back();
  2707. openstack.pop_back();
  2708. result.append(last, in - last);
  2709. std::string const& lookup = result.substr(var.loc);
  2710. cmValue value = nullptr;
  2711. std::string varresult;
  2712. std::string svalue;
  2713. switch (var.domain) {
  2714. case NORMAL:
  2715. if (filename && lookup == lineVar) {
  2716. cmListFileContext const& top = this->Backtrace.Top();
  2717. if (top.DeferId) {
  2718. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2719. } else {
  2720. varresult = std::to_string(line);
  2721. }
  2722. } else {
  2723. value = this->GetDefinition(lookup);
  2724. }
  2725. break;
  2726. case ENVIRONMENT:
  2727. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2728. value = cmValue(svalue);
  2729. }
  2730. break;
  2731. case CACHE:
  2732. value = state->GetCacheEntryValue(lookup);
  2733. break;
  2734. }
  2735. // Get the string we're meant to append to.
  2736. if (value) {
  2737. if (escapeQuotes) {
  2738. varresult = cmEscapeQuotes(*value);
  2739. } else {
  2740. varresult = *value;
  2741. }
  2742. } else if (!this->SuppressSideEffects) {
  2743. this->MaybeWarnUninitialized(lookup, filename);
  2744. }
  2745. result.replace(var.loc, result.size() - var.loc, varresult);
  2746. // Start looking from here on out.
  2747. last = in + 1;
  2748. }
  2749. break;
  2750. case '$':
  2751. if (!atOnly) {
  2752. t_lookup lookup;
  2753. const char* next = in + 1;
  2754. const char* start = nullptr;
  2755. char nextc = *next;
  2756. if (nextc == '{') {
  2757. // Looking for a variable.
  2758. start = in + 2;
  2759. lookup.domain = NORMAL;
  2760. } else if (nextc == '<') {
  2761. } else if (!nextc) {
  2762. result.append(last, next - last);
  2763. last = next;
  2764. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2765. // Looking for an environment variable.
  2766. start = in + 5;
  2767. lookup.domain = ENVIRONMENT;
  2768. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2769. // Looking for a cache variable.
  2770. start = in + 7;
  2771. lookup.domain = CACHE;
  2772. } else {
  2773. if (this->cmNamedCurly.find(next)) {
  2774. errorstr = "Syntax $" +
  2775. std::string(next, this->cmNamedCurly.end()) +
  2776. "{} is not supported. Only ${}, $ENV{}, "
  2777. "and $CACHE{} are allowed.";
  2778. mtype = MessageType::FATAL_ERROR;
  2779. error = true;
  2780. }
  2781. }
  2782. if (start) {
  2783. result.append(last, in - last);
  2784. last = start;
  2785. in = start - 1;
  2786. lookup.loc = result.size();
  2787. openstack.push_back(lookup);
  2788. }
  2789. break;
  2790. }
  2791. CM_FALLTHROUGH;
  2792. case '\\':
  2793. if (!noEscapes) {
  2794. const char* next = in + 1;
  2795. char nextc = *next;
  2796. if (nextc == 't') {
  2797. result.append(last, in - last);
  2798. result.push_back('\t');
  2799. last = next + 1;
  2800. } else if (nextc == 'n') {
  2801. result.append(last, in - last);
  2802. result.push_back('\n');
  2803. last = next + 1;
  2804. } else if (nextc == 'r') {
  2805. result.append(last, in - last);
  2806. result.push_back('\r');
  2807. last = next + 1;
  2808. } else if (nextc == ';' && openstack.empty()) {
  2809. // Handled in ExpandListArgument; pass the backslash literally.
  2810. } else if (isalnum(nextc) || nextc == '\0') {
  2811. errorstr += "Invalid character escape '\\";
  2812. if (nextc) {
  2813. errorstr += nextc;
  2814. errorstr += "'.";
  2815. } else {
  2816. errorstr += "' (at end of input).";
  2817. }
  2818. error = true;
  2819. } else {
  2820. // Take what we've found so far, skipping the escape character.
  2821. result.append(last, in - last);
  2822. // Start tracking from the next character.
  2823. last = in + 1;
  2824. }
  2825. // Skip the next character since it was escaped, but don't read past
  2826. // the end of the string.
  2827. if (*last) {
  2828. ++in;
  2829. }
  2830. }
  2831. break;
  2832. case '\n':
  2833. // Onto the next line.
  2834. ++line;
  2835. break;
  2836. case '\0':
  2837. done = true;
  2838. break;
  2839. case '@':
  2840. if (replaceAt) {
  2841. const char* nextAt = strchr(in + 1, '@');
  2842. if (nextAt && nextAt != in + 1 &&
  2843. nextAt ==
  2844. in + 1 +
  2845. strspn(in + 1,
  2846. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2847. "abcdefghijklmnopqrstuvwxyz"
  2848. "0123456789/_.+-")) {
  2849. std::string variable(in + 1, nextAt - in - 1);
  2850. std::string varresult;
  2851. if (filename && variable == lineVar) {
  2852. varresult = std::to_string(line);
  2853. } else {
  2854. cmValue def = this->GetDefinition(variable);
  2855. if (def) {
  2856. varresult = *def;
  2857. } else if (!this->SuppressSideEffects) {
  2858. this->MaybeWarnUninitialized(variable, filename);
  2859. }
  2860. }
  2861. if (escapeQuotes) {
  2862. varresult = cmEscapeQuotes(varresult);
  2863. }
  2864. // Skip over the variable.
  2865. result.append(last, in - last);
  2866. result.append(varresult);
  2867. in = nextAt;
  2868. last = in + 1;
  2869. break;
  2870. }
  2871. }
  2872. // Failed to find a valid @ expansion; treat it as literal.
  2873. CM_FALLTHROUGH;
  2874. default: {
  2875. if (!openstack.empty() &&
  2876. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2877. inc == '+' || inc == '-')) {
  2878. errorstr += "Invalid character (\'";
  2879. errorstr += inc;
  2880. result.append(last, in - last);
  2881. errorstr += cmStrCat("\') in a variable name: "
  2882. "'",
  2883. result.substr(openstack.back().loc), '\'');
  2884. mtype = MessageType::FATAL_ERROR;
  2885. error = true;
  2886. }
  2887. break;
  2888. }
  2889. }
  2890. // Look at the next character.
  2891. } while (!error && !done && *++in);
  2892. // Check for open variable references yet.
  2893. if (!error && !openstack.empty()) {
  2894. // There's an open variable reference waiting. Policy CMP0010 flags
  2895. // whether this is an error or not. The new parser now enforces
  2896. // CMP0010 as well.
  2897. errorstr += "There is an unterminated variable reference.";
  2898. error = true;
  2899. }
  2900. if (error) {
  2901. std::ostringstream emsg;
  2902. emsg << "Syntax error in cmake code ";
  2903. if (filename) {
  2904. // This filename and line number may be more specific than the
  2905. // command context because one command invocation can have
  2906. // arguments on multiple lines.
  2907. emsg << "at\n"
  2908. << " " << filename << ":" << line << "\n";
  2909. }
  2910. emsg << "when parsing string\n"
  2911. << " " << source << "\n";
  2912. emsg << errorstr;
  2913. mtype = MessageType::FATAL_ERROR;
  2914. errorstr = emsg.str();
  2915. } else {
  2916. // Append the rest of the unchanged part of the string.
  2917. result.append(last);
  2918. source = result;
  2919. }
  2920. return mtype;
  2921. }
  2922. void cmMakefile::RemoveVariablesInString(std::string& source,
  2923. bool atOnly) const
  2924. {
  2925. if (!atOnly) {
  2926. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2927. while (var.find(source)) {
  2928. source.erase(var.start(), var.end() - var.start());
  2929. }
  2930. }
  2931. if (!atOnly) {
  2932. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2933. while (varb.find(source)) {
  2934. source.erase(varb.start(), varb.end() - varb.start());
  2935. }
  2936. }
  2937. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2938. while (var2.find(source)) {
  2939. source.erase(var2.start(), var2.end() - var2.start());
  2940. }
  2941. }
  2942. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2943. {
  2944. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2945. return;
  2946. }
  2947. std::string initConfigs;
  2948. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2949. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2950. initConfigs = genDefault;
  2951. }
  2952. this->AddCacheDefinition(
  2953. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2954. "Semicolon separated list of supported configuration types, "
  2955. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2956. "anything else will be ignored.",
  2957. cmStateEnums::STRING);
  2958. }
  2959. std::string cmMakefile::GetDefaultConfiguration() const
  2960. {
  2961. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2962. return std::string{};
  2963. }
  2964. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2965. }
  2966. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2967. GeneratorConfigQuery mode) const
  2968. {
  2969. cmList configs;
  2970. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2971. configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
  2972. } else if (mode != cmMakefile::OnlyMultiConfig) {
  2973. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2974. if (!buildType.empty()) {
  2975. configs.emplace_back(buildType);
  2976. }
  2977. }
  2978. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  2979. configs.emplace_back();
  2980. }
  2981. return std::move(configs.data());
  2982. }
  2983. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  2984. cmExecutionStatus& status)
  2985. {
  2986. // if there are no blockers get out of here
  2987. if (this->FunctionBlockers.empty()) {
  2988. return false;
  2989. }
  2990. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  2991. }
  2992. void cmMakefile::PushFunctionBlockerBarrier()
  2993. {
  2994. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2995. }
  2996. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2997. {
  2998. // Remove any extra entries pushed on the barrier.
  2999. FunctionBlockersType::size_type barrier =
  3000. this->FunctionBlockerBarriers.back();
  3001. while (this->FunctionBlockers.size() > barrier) {
  3002. std::unique_ptr<cmFunctionBlocker> fb(
  3003. std::move(this->FunctionBlockers.top()));
  3004. this->FunctionBlockers.pop();
  3005. if (reportError) {
  3006. // Report the context in which the unclosed block was opened.
  3007. cmListFileContext const& lfc = fb->GetStartingContext();
  3008. std::ostringstream e;
  3009. /* clang-format off */
  3010. e << "A logical block opening on the line\n"
  3011. << " " << lfc << "\n"
  3012. << "is not closed.";
  3013. /* clang-format on */
  3014. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3015. reportError = false;
  3016. }
  3017. }
  3018. // Remove the barrier.
  3019. this->FunctionBlockerBarriers.pop_back();
  3020. }
  3021. void cmMakefile::PushLoopBlock()
  3022. {
  3023. assert(!this->LoopBlockCounter.empty());
  3024. this->LoopBlockCounter.top()++;
  3025. }
  3026. void cmMakefile::PopLoopBlock()
  3027. {
  3028. assert(!this->LoopBlockCounter.empty());
  3029. assert(this->LoopBlockCounter.top() > 0);
  3030. this->LoopBlockCounter.top()--;
  3031. }
  3032. void cmMakefile::PushLoopBlockBarrier()
  3033. {
  3034. this->LoopBlockCounter.push(0);
  3035. }
  3036. void cmMakefile::PopLoopBlockBarrier()
  3037. {
  3038. assert(!this->LoopBlockCounter.empty());
  3039. assert(this->LoopBlockCounter.top() == 0);
  3040. this->LoopBlockCounter.pop();
  3041. }
  3042. bool cmMakefile::IsLoopBlock() const
  3043. {
  3044. assert(!this->LoopBlockCounter.empty());
  3045. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  3046. }
  3047. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  3048. std::vector<std::string>& outArgs) const
  3049. {
  3050. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3051. std::string value;
  3052. outArgs.reserve(inArgs.size());
  3053. for (cmListFileArgument const& i : inArgs) {
  3054. // No expansion in a bracket argument.
  3055. if (i.Delim == cmListFileArgument::Bracket) {
  3056. outArgs.push_back(i.Value);
  3057. continue;
  3058. }
  3059. // Expand the variables in the argument.
  3060. value = i.Value;
  3061. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3062. i.Line, false, false);
  3063. // If the argument is quoted, it should be one argument.
  3064. // Otherwise, it may be a list of arguments.
  3065. if (i.Delim == cmListFileArgument::Quoted) {
  3066. outArgs.push_back(value);
  3067. } else {
  3068. cmExpandList(value, outArgs);
  3069. }
  3070. }
  3071. return !cmSystemTools::GetFatalErrorOccurred();
  3072. }
  3073. bool cmMakefile::ExpandArguments(
  3074. std::vector<cmListFileArgument> const& inArgs,
  3075. std::vector<cmExpandedCommandArgument>& outArgs) const
  3076. {
  3077. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3078. std::string value;
  3079. outArgs.reserve(inArgs.size());
  3080. for (cmListFileArgument const& i : inArgs) {
  3081. // No expansion in a bracket argument.
  3082. if (i.Delim == cmListFileArgument::Bracket) {
  3083. outArgs.emplace_back(i.Value, true);
  3084. continue;
  3085. }
  3086. // Expand the variables in the argument.
  3087. value = i.Value;
  3088. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3089. i.Line, false, false);
  3090. // If the argument is quoted, it should be one argument.
  3091. // Otherwise, it may be a list of arguments.
  3092. if (i.Delim == cmListFileArgument::Quoted) {
  3093. outArgs.emplace_back(value, true);
  3094. } else {
  3095. cmList stringArgs{ value };
  3096. for (std::string const& stringArg : stringArgs) {
  3097. outArgs.emplace_back(stringArg, false);
  3098. }
  3099. }
  3100. }
  3101. return !cmSystemTools::GetFatalErrorOccurred();
  3102. }
  3103. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  3104. {
  3105. if (!this->ExecutionStatusStack.empty()) {
  3106. // Record the context in which the blocker is created.
  3107. fb->SetStartingContext(this->Backtrace.Top());
  3108. }
  3109. this->FunctionBlockers.push(std::move(fb));
  3110. }
  3111. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  3112. {
  3113. assert(!this->FunctionBlockers.empty());
  3114. assert(this->FunctionBlockerBarriers.empty() ||
  3115. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  3116. auto b = std::move(this->FunctionBlockers.top());
  3117. this->FunctionBlockers.pop();
  3118. return b;
  3119. }
  3120. std::string const& cmMakefile::GetHomeDirectory() const
  3121. {
  3122. return this->GetCMakeInstance()->GetHomeDirectory();
  3123. }
  3124. std::string const& cmMakefile::GetHomeOutputDirectory() const
  3125. {
  3126. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3127. }
  3128. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  3129. {
  3130. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  3131. }
  3132. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  3133. {
  3134. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  3135. // this->MarkVariableAsUsed("CMAKE_ARGC");
  3136. for (unsigned int t = 0; t < args.size(); ++t) {
  3137. std::ostringstream tmpStream;
  3138. tmpStream << "CMAKE_ARGV" << t;
  3139. this->AddDefinition(tmpStream.str(), args[t]);
  3140. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  3141. }
  3142. }
  3143. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  3144. cmSourceFileLocationKind kind) const
  3145. {
  3146. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  3147. if (kind == cmSourceFileLocationKind::Known) {
  3148. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  3149. if (sfsi != this->KnownFileSearchIndex.end()) {
  3150. return sfsi->second;
  3151. }
  3152. }
  3153. cmSourceFileLocation sfl(this, sourceName, kind);
  3154. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  3155. #if defined(_WIN32) || defined(__APPLE__)
  3156. name = cmSystemTools::LowerCase(name);
  3157. #endif
  3158. auto sfsi = this->SourceFileSearchIndex.find(name);
  3159. if (sfsi != this->SourceFileSearchIndex.end()) {
  3160. for (auto* sf : sfsi->second) {
  3161. if (sf->Matches(sfl)) {
  3162. return sf;
  3163. }
  3164. }
  3165. }
  3166. return nullptr;
  3167. }
  3168. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  3169. bool generated,
  3170. cmSourceFileLocationKind kind)
  3171. {
  3172. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  3173. auto name =
  3174. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  3175. #if defined(_WIN32) || defined(__APPLE__)
  3176. name = cmSystemTools::LowerCase(name);
  3177. #endif
  3178. this->SourceFileSearchIndex[name].push_back(sf.get());
  3179. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  3180. if (kind == cmSourceFileLocationKind::Known) {
  3181. this->KnownFileSearchIndex[sourceName] = sf.get();
  3182. }
  3183. this->SourceFiles.push_back(std::move(sf));
  3184. return this->SourceFiles.back().get();
  3185. }
  3186. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  3187. bool generated,
  3188. cmSourceFileLocationKind kind)
  3189. {
  3190. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  3191. return esf;
  3192. }
  3193. return this->CreateSource(sourceName, generated, kind);
  3194. }
  3195. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  3196. const std::string& sourceName)
  3197. {
  3198. cmSourceFile* sf =
  3199. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  3200. sf->MarkAsGenerated(); // In case we did not create the source file.
  3201. return sf;
  3202. }
  3203. void cmMakefile::CreateGeneratedOutputs(
  3204. const std::vector<std::string>& outputs)
  3205. {
  3206. for (std::string const& o : outputs) {
  3207. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  3208. this->GetOrCreateGeneratedSource(o);
  3209. }
  3210. }
  3211. }
  3212. void cmMakefile::AddTargetObject(std::string const& tgtName,
  3213. std::string const& objFile)
  3214. {
  3215. cmSourceFile* sf =
  3216. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  3217. sf->SetObjectLibrary(tgtName);
  3218. sf->SetProperty("EXTERNAL_OBJECT", "1");
  3219. #if !defined(CMAKE_BOOTSTRAP)
  3220. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  3221. sf->ResolveFullPath());
  3222. #endif
  3223. }
  3224. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  3225. bool optional)
  3226. {
  3227. if (this->DeferRunning) {
  3228. this->IssueMessage(
  3229. MessageType::FATAL_ERROR,
  3230. "Languages may not be enabled during deferred execution.");
  3231. return;
  3232. }
  3233. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  3234. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  3235. }
  3236. std::vector<std::string> unique_languages;
  3237. {
  3238. std::vector<std::string> duplicate_languages;
  3239. for (std::string const& language : languages) {
  3240. if (!cm::contains(unique_languages, language)) {
  3241. unique_languages.push_back(language);
  3242. } else if (!cm::contains(duplicate_languages, language)) {
  3243. duplicate_languages.push_back(language);
  3244. }
  3245. }
  3246. if (!duplicate_languages.empty()) {
  3247. auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
  3248. this->IssueMessage(
  3249. MessageType::AUTHOR_WARNING,
  3250. cmStrCat("Languages to be enabled may not be specified more "
  3251. "than once at the same time. The following language",
  3252. quantity, " been specified multiple times: ",
  3253. cmJoin(duplicate_languages, ", ")));
  3254. }
  3255. }
  3256. // If RC is explicitly listed we need to do it after other languages.
  3257. // On some platforms we enable RC implicitly while enabling others.
  3258. // Do not let that look like recursive enable_language(RC).
  3259. std::vector<std::string> languages_without_RC;
  3260. std::vector<std::string> languages_for_RC;
  3261. languages_without_RC.reserve(unique_languages.size());
  3262. for (std::string const& language : unique_languages) {
  3263. if (language == "RC"_s) {
  3264. languages_for_RC.push_back(language);
  3265. } else {
  3266. languages_without_RC.push_back(language);
  3267. }
  3268. }
  3269. if (!languages_without_RC.empty()) {
  3270. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  3271. optional);
  3272. }
  3273. if (!languages_for_RC.empty()) {
  3274. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  3275. optional);
  3276. }
  3277. }
  3278. int cmMakefile::TryCompile(const std::string& srcdir,
  3279. const std::string& bindir,
  3280. const std::string& projectName,
  3281. const std::string& targetName, bool fast, int jobs,
  3282. const std::vector<std::string>* cmakeArgs,
  3283. std::string& output)
  3284. {
  3285. this->IsSourceFileTryCompile = fast;
  3286. // does the binary directory exist ? If not create it...
  3287. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3288. cmSystemTools::MakeDirectory(bindir);
  3289. }
  3290. // change to the tests directory and run cmake
  3291. // use the cmake object instead of calling cmake
  3292. cmWorkingDirectory workdir(bindir);
  3293. if (workdir.Failed()) {
  3294. this->IssueMessage(MessageType::FATAL_ERROR,
  3295. cmStrCat("Failed to set working directory to ", bindir,
  3296. " : ",
  3297. std::strerror(workdir.GetLastResult())));
  3298. cmSystemTools::SetFatalErrorOccurred();
  3299. this->IsSourceFileTryCompile = false;
  3300. return 1;
  3301. }
  3302. // make sure the same generator is used
  3303. // use this program as the cmake to be run, it should not
  3304. // be run that way but the cmake object requires a vailid path
  3305. cmake cm(cmake::RoleProject, cmState::Project,
  3306. cmState::ProjectKind::TryCompile);
  3307. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3308. if (!gg) {
  3309. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3310. "Global generator '" +
  3311. this->GetGlobalGenerator()->GetName() +
  3312. "' could not be created.");
  3313. cmSystemTools::SetFatalErrorOccurred();
  3314. this->IsSourceFileTryCompile = false;
  3315. return 1;
  3316. }
  3317. gg->RecursionDepth = this->RecursionDepth;
  3318. cm.SetGlobalGenerator(std::move(gg));
  3319. // copy trace state
  3320. cm.SetTraceRedirect(this->GetCMakeInstance());
  3321. // do a configure
  3322. cm.SetHomeDirectory(srcdir);
  3323. cm.SetHomeOutputDirectory(bindir);
  3324. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3325. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3326. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3327. cm.LoadCache();
  3328. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  3329. if (cmValue config =
  3330. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3331. // Tell the single-configuration generator which one to use.
  3332. // Add this before the user-provided CMake arguments in case
  3333. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3334. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3335. cmStateEnums::STRING);
  3336. }
  3337. }
  3338. cmValue recursionDepth =
  3339. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3340. if (recursionDepth) {
  3341. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3342. "Maximum recursion depth", cmStateEnums::STRING);
  3343. }
  3344. // if cmake args were provided then pass them in
  3345. if (cmakeArgs) {
  3346. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3347. //
  3348. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  3349. // However, there is a subtle problem when certain arguments are passed to
  3350. // a macro wrapping around try_compile or try_run that does not escape
  3351. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3352. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3353. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3354. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3355. // the try_compile or try_run does not get the proper value of VAR. If we
  3356. // call SetArgs here then it would treat "b" as the source directory and
  3357. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3358. // does not exist", thus breaking the try_compile or try_run completely.
  3359. //
  3360. // Strictly speaking the bug is in the wrapper macro because the CMake
  3361. // language has always flattened nested lists and the macro should escape
  3362. // the semicolons in its arguments before forwarding them. However, this
  3363. // bug is so subtle that projects typically work anyway, usually because
  3364. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3365. // correct result. Calling SetArgs here would break such projects that
  3366. // previously built. Instead we work around the issue by never reporting
  3367. // unused arguments and ignoring options such as --no-warn-unused-cli.
  3368. cm.SetWarnUnusedCli(false);
  3369. // cm.SetArgs(*cmakeArgs, true);
  3370. cm.SetCacheArgs(*cmakeArgs);
  3371. }
  3372. // to save time we pass the EnableLanguage info directly
  3373. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  3374. this->GetGlobalGenerator(), this);
  3375. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3376. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3377. cmStateEnums::INTERNAL);
  3378. } else {
  3379. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3380. cmStateEnums::INTERNAL);
  3381. }
  3382. if (cm.Configure() != 0) {
  3383. this->IssueMessage(MessageType::FATAL_ERROR,
  3384. "Failed to configure test project build system.");
  3385. cmSystemTools::SetFatalErrorOccurred();
  3386. this->IsSourceFileTryCompile = false;
  3387. return 1;
  3388. }
  3389. if (cm.Generate() != 0) {
  3390. this->IssueMessage(MessageType::FATAL_ERROR,
  3391. "Failed to generate test project build system.");
  3392. cmSystemTools::SetFatalErrorOccurred();
  3393. this->IsSourceFileTryCompile = false;
  3394. return 1;
  3395. }
  3396. // finally call the generator to actually build the resulting project
  3397. int ret = this->GetGlobalGenerator()->TryCompile(
  3398. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3399. this->IsSourceFileTryCompile = false;
  3400. return ret;
  3401. }
  3402. bool cmMakefile::GetIsSourceFileTryCompile() const
  3403. {
  3404. return this->IsSourceFileTryCompile;
  3405. }
  3406. cmake* cmMakefile::GetCMakeInstance() const
  3407. {
  3408. return this->GlobalGenerator->GetCMakeInstance();
  3409. }
  3410. cmMessenger* cmMakefile::GetMessenger() const
  3411. {
  3412. return this->GetCMakeInstance()->GetMessenger();
  3413. }
  3414. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3415. {
  3416. return this->GlobalGenerator;
  3417. }
  3418. #ifndef CMAKE_BOOTSTRAP
  3419. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3420. {
  3421. if (this->GetCMakeInstance() &&
  3422. this->GetCMakeInstance()->GetVariableWatch()) {
  3423. return this->GetCMakeInstance()->GetVariableWatch();
  3424. }
  3425. return nullptr;
  3426. }
  3427. #endif
  3428. cmState* cmMakefile::GetState() const
  3429. {
  3430. return this->GetCMakeInstance()->GetState();
  3431. }
  3432. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3433. {
  3434. cmake* cm = this->GetCMakeInstance();
  3435. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3436. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3437. // directly be fed to the compiler, which will be confused.
  3438. return;
  3439. }
  3440. cm->UpdateProgress(message, s);
  3441. #ifdef CMake_ENABLE_DEBUGGER
  3442. if (cm->GetDebugAdapter() != nullptr) {
  3443. cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
  3444. }
  3445. #endif
  3446. }
  3447. std::string cmMakefile::GetModulesFile(const std::string& filename,
  3448. bool& system, bool debug,
  3449. std::string& debugBuffer) const
  3450. {
  3451. std::string result;
  3452. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3453. // and then decide based on the policy setting which one to return.
  3454. // See CMP0017 for more details.
  3455. // The specific problem was that KDE 4.5.0 installs a
  3456. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3457. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3458. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3459. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3460. // new features, which were not there in the version from kdelibs, and so
  3461. // failed ("
  3462. std::string moduleInCMakeRoot;
  3463. std::string moduleInCMakeModulePath;
  3464. // Always search in CMAKE_MODULE_PATH:
  3465. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3466. if (cmakeModulePath) {
  3467. cmList modulePath{ *cmakeModulePath };
  3468. // Look through the possible module directories.
  3469. for (std::string itempl : modulePath) {
  3470. cmSystemTools::ConvertToUnixSlashes(itempl);
  3471. itempl += "/";
  3472. itempl += filename;
  3473. if (cmSystemTools::FileExists(itempl)) {
  3474. moduleInCMakeModulePath = itempl;
  3475. break;
  3476. }
  3477. if (debug) {
  3478. debugBuffer = cmStrCat(debugBuffer, " ", itempl, "\n");
  3479. }
  3480. }
  3481. }
  3482. // Always search in the standard modules location.
  3483. moduleInCMakeRoot =
  3484. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  3485. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3486. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3487. if (debug) {
  3488. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, "\n");
  3489. }
  3490. moduleInCMakeRoot.clear();
  3491. }
  3492. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3493. // from which we are being called is located itself in CMAKE_ROOT, then
  3494. // prefer results from CMAKE_ROOT depending on the policy setting.
  3495. system = false;
  3496. result = moduleInCMakeModulePath;
  3497. if (result.empty()) {
  3498. system = true;
  3499. result = moduleInCMakeRoot;
  3500. }
  3501. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3502. cmValue currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3503. std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
  3504. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  3505. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3506. case cmPolicies::WARN: {
  3507. std::ostringstream e;
  3508. /* clang-format off */
  3509. e << "File " << *currentFile << " includes "
  3510. << moduleInCMakeModulePath
  3511. << " (found via CMAKE_MODULE_PATH) which shadows "
  3512. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3513. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3514. /* clang-format on */
  3515. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3516. CM_FALLTHROUGH;
  3517. }
  3518. case cmPolicies::OLD:
  3519. system = false;
  3520. result = moduleInCMakeModulePath;
  3521. break;
  3522. case cmPolicies::REQUIRED_IF_USED:
  3523. case cmPolicies::REQUIRED_ALWAYS:
  3524. case cmPolicies::NEW:
  3525. system = true;
  3526. result = moduleInCMakeRoot;
  3527. break;
  3528. }
  3529. }
  3530. }
  3531. return result;
  3532. }
  3533. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3534. bool atOnly, bool escapeQuotes) const
  3535. {
  3536. // Split input to handle one line at a time.
  3537. std::string::const_iterator lineStart = input.begin();
  3538. while (lineStart != input.end()) {
  3539. // Find the end of this line.
  3540. std::string::const_iterator lineEnd = lineStart;
  3541. while (lineEnd != input.end() && *lineEnd != '\n') {
  3542. ++lineEnd;
  3543. }
  3544. // Copy the line.
  3545. std::string line(lineStart, lineEnd);
  3546. // Skip the newline character.
  3547. bool haveNewline = (lineEnd != input.end());
  3548. if (haveNewline) {
  3549. ++lineEnd;
  3550. }
  3551. // Replace #cmakedefine instances.
  3552. if (this->cmDefineRegex.find(line)) {
  3553. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3554. if (!cmIsOff(def)) {
  3555. const std::string indentation = this->cmDefineRegex.match(1);
  3556. cmSystemTools::ReplaceString(line,
  3557. cmStrCat("#", indentation, "cmakedefine"),
  3558. cmStrCat("#", indentation, "define"));
  3559. output += line;
  3560. } else {
  3561. output += "/* #undef ";
  3562. output += this->cmDefineRegex.match(2);
  3563. output += " */";
  3564. }
  3565. } else if (this->cmDefine01Regex.find(line)) {
  3566. const std::string indentation = this->cmDefine01Regex.match(1);
  3567. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3568. cmSystemTools::ReplaceString(line,
  3569. cmStrCat("#", indentation, "cmakedefine01"),
  3570. cmStrCat("#", indentation, "define"));
  3571. output += line;
  3572. if (!cmIsOff(def)) {
  3573. output += " 1";
  3574. } else {
  3575. output += " 0";
  3576. }
  3577. } else {
  3578. output += line;
  3579. }
  3580. if (haveNewline) {
  3581. output += "\n";
  3582. }
  3583. // Move to the next line.
  3584. lineStart = lineEnd;
  3585. }
  3586. // Perform variable replacements.
  3587. const char* filename = nullptr;
  3588. long lineNumber = -1;
  3589. if (!this->Backtrace.Empty()) {
  3590. const auto& currentTrace = this->Backtrace.Top();
  3591. filename = currentTrace.FilePath.c_str();
  3592. lineNumber = currentTrace.Line;
  3593. }
  3594. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3595. lineNumber, true, true);
  3596. }
  3597. int cmMakefile::ConfigureFile(const std::string& infile,
  3598. const std::string& outfile, bool copyonly,
  3599. bool atOnly, bool escapeQuotes,
  3600. mode_t permissions, cmNewLineStyle newLine)
  3601. {
  3602. int res = 1;
  3603. if (!this->CanIWriteThisFile(outfile)) {
  3604. cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
  3605. " into a source directory."));
  3606. return 0;
  3607. }
  3608. if (!cmSystemTools::FileExists(infile)) {
  3609. cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
  3610. return 0;
  3611. }
  3612. std::string soutfile = outfile;
  3613. const std::string& sinfile = infile;
  3614. this->AddCMakeDependFile(sinfile);
  3615. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3616. // Re-generate if non-temporary outputs are missing.
  3617. // when we finalize the configuration we will remove all
  3618. // output files that now don't exist.
  3619. this->AddCMakeOutputFile(soutfile);
  3620. if (permissions == 0) {
  3621. cmSystemTools::GetPermissions(sinfile, permissions);
  3622. }
  3623. std::string::size_type pos = soutfile.rfind('/');
  3624. if (pos != std::string::npos) {
  3625. std::string path = soutfile.substr(0, pos);
  3626. cmSystemTools::MakeDirectory(path);
  3627. }
  3628. if (copyonly) {
  3629. if (!cmSystemTools::CopyFileIfDifferent(sinfile, soutfile)) {
  3630. this->IssueMessage(MessageType::FATAL_ERROR,
  3631. cmSystemTools::GetLastSystemError());
  3632. return 0;
  3633. }
  3634. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3635. this->IssueMessage(MessageType::FATAL_ERROR,
  3636. cmSystemTools::GetLastSystemError());
  3637. return 0;
  3638. }
  3639. } else {
  3640. std::string newLineCharacters;
  3641. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3642. if (newLine.IsValid()) {
  3643. newLineCharacters = newLine.GetCharacters();
  3644. omode |= std::ios::binary;
  3645. } else {
  3646. newLineCharacters = "\n";
  3647. }
  3648. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3649. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3650. if (!fout) {
  3651. cmSystemTools::Error("Could not open file for write in copy operation " +
  3652. tempOutputFile);
  3653. cmSystemTools::ReportLastSystemError("");
  3654. return 0;
  3655. }
  3656. cmsys::ifstream fin(sinfile.c_str());
  3657. if (!fin) {
  3658. cmSystemTools::Error("Could not open file for read in copy operation " +
  3659. sinfile);
  3660. return 0;
  3661. }
  3662. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3663. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3664. std::ostringstream e;
  3665. e << "File starts with a Byte-Order-Mark that is not UTF-8:\n "
  3666. << sinfile;
  3667. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3668. return 0;
  3669. }
  3670. // rewind to copy BOM to output file
  3671. fin.seekg(0);
  3672. // now copy input to output and expand variables in the
  3673. // input file at the same time
  3674. std::string inLine;
  3675. std::string outLine;
  3676. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3677. outLine.clear();
  3678. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3679. fout << outLine << newLineCharacters;
  3680. }
  3681. // close the files before attempting to copy
  3682. fin.close();
  3683. fout.close();
  3684. if (!cmSystemTools::CopyFileIfDifferent(tempOutputFile, soutfile)) {
  3685. this->IssueMessage(MessageType::FATAL_ERROR,
  3686. cmSystemTools::GetLastSystemError());
  3687. res = 0;
  3688. } else {
  3689. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3690. this->IssueMessage(MessageType::FATAL_ERROR,
  3691. cmSystemTools::GetLastSystemError());
  3692. res = 0;
  3693. }
  3694. }
  3695. cmSystemTools::RemoveFile(tempOutputFile);
  3696. }
  3697. return res;
  3698. }
  3699. void cmMakefile::SetProperty(const std::string& prop, cmValue value)
  3700. {
  3701. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3702. }
  3703. void cmMakefile::AppendProperty(const std::string& prop,
  3704. const std::string& value, bool asString)
  3705. {
  3706. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3707. this->Backtrace);
  3708. }
  3709. cmValue cmMakefile::GetProperty(const std::string& prop) const
  3710. {
  3711. // Check for computed properties.
  3712. static std::string output;
  3713. if (prop == "TESTS"_s) {
  3714. std::vector<std::string> keys;
  3715. // get list of keys
  3716. const auto* t = this;
  3717. std::transform(
  3718. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3719. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3720. output = cmList::to_string(keys);
  3721. return cmValue(output);
  3722. }
  3723. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3724. }
  3725. cmValue cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3726. {
  3727. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3728. }
  3729. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3730. {
  3731. return cmIsOn(this->GetProperty(prop));
  3732. }
  3733. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3734. {
  3735. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3736. }
  3737. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3738. {
  3739. auto i = this->Targets.find(name);
  3740. if (i != this->Targets.end()) {
  3741. return &i->second;
  3742. }
  3743. return nullptr;
  3744. }
  3745. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3746. {
  3747. cmTest* test = this->GetTest(testName);
  3748. if (test) {
  3749. return test;
  3750. }
  3751. auto newTest = cm::make_unique<cmTest>(this);
  3752. test = newTest.get();
  3753. newTest->SetName(testName);
  3754. this->Tests[testName] = std::move(newTest);
  3755. return test;
  3756. }
  3757. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3758. {
  3759. auto mi = this->Tests.find(testName);
  3760. if (mi != this->Tests.end()) {
  3761. return mi->second.get();
  3762. }
  3763. return nullptr;
  3764. }
  3765. void cmMakefile::GetTests(const std::string& config,
  3766. std::vector<cmTest*>& tests) const
  3767. {
  3768. for (const auto& generator : this->GetTestGenerators()) {
  3769. if (generator->TestsForConfig(config)) {
  3770. tests.push_back(generator->GetTest());
  3771. }
  3772. }
  3773. }
  3774. void cmMakefile::AddCMakeDependFilesFromUser()
  3775. {
  3776. cmList deps;
  3777. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3778. deps.assign(*deps_str);
  3779. }
  3780. for (auto const& dep : deps) {
  3781. if (cmSystemTools::FileIsFullPath(dep)) {
  3782. this->AddCMakeDependFile(dep);
  3783. } else {
  3784. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3785. this->AddCMakeDependFile(f);
  3786. }
  3787. }
  3788. }
  3789. std::string cmMakefile::FormatListFileStack() const
  3790. {
  3791. std::vector<std::string> listFiles;
  3792. cmStateSnapshot snp = this->StateSnapshot;
  3793. while (snp.IsValid()) {
  3794. listFiles.push_back(snp.GetExecutionListFile());
  3795. snp = snp.GetCallStackParent();
  3796. }
  3797. std::reverse(listFiles.begin(), listFiles.end());
  3798. std::ostringstream tmp;
  3799. size_t depth = listFiles.size();
  3800. if (depth > 0) {
  3801. auto it = listFiles.end();
  3802. do {
  3803. if (depth != listFiles.size()) {
  3804. tmp << "\n ";
  3805. }
  3806. --it;
  3807. tmp << "[";
  3808. tmp << depth;
  3809. tmp << "]\t";
  3810. tmp << *it;
  3811. depth--;
  3812. } while (it != listFiles.begin());
  3813. }
  3814. return tmp.str();
  3815. }
  3816. void cmMakefile::PushScope()
  3817. {
  3818. this->StateSnapshot =
  3819. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3820. this->PushLoopBlockBarrier();
  3821. #if !defined(CMAKE_BOOTSTRAP)
  3822. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3823. #endif
  3824. }
  3825. void cmMakefile::PopScope()
  3826. {
  3827. #if !defined(CMAKE_BOOTSTRAP)
  3828. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3829. #endif
  3830. this->PopLoopBlockBarrier();
  3831. this->PopSnapshot();
  3832. }
  3833. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3834. {
  3835. if (var.empty()) {
  3836. return;
  3837. }
  3838. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3839. std::ostringstream m;
  3840. m << "Cannot set \"" << var << "\": current scope has no parent.";
  3841. this->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  3842. return;
  3843. }
  3844. #ifndef CMAKE_BOOTSTRAP
  3845. cmVariableWatch* vv = this->GetVariableWatch();
  3846. if (vv) {
  3847. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3848. varDef, this);
  3849. }
  3850. #endif
  3851. }
  3852. void cmMakefile::RaiseScope(const std::vector<std::string>& variables)
  3853. {
  3854. for (auto const& varName : variables) {
  3855. if (this->IsNormalDefinitionSet(varName)) {
  3856. this->RaiseScope(varName, this->GetDefinition(varName));
  3857. } else {
  3858. // unset variable in parent scope
  3859. this->RaiseScope(varName, nullptr);
  3860. }
  3861. }
  3862. }
  3863. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3864. cmStateEnums::TargetType type,
  3865. bool global)
  3866. {
  3867. // Create the target.
  3868. std::unique_ptr<cmTarget> target(
  3869. new cmTarget(name, type,
  3870. global ? cmTarget::Visibility::ImportedGlobally
  3871. : cmTarget::Visibility::Imported,
  3872. this, cmTarget::PerConfig::Yes));
  3873. // Add to the set of available imported targets.
  3874. this->ImportedTargets[name] = target.get();
  3875. this->GetGlobalGenerator()->IndexTarget(target.get());
  3876. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3877. // Transfer ownership to this cmMakefile object.
  3878. this->ImportedTargetsOwned.push_back(std::move(target));
  3879. return this->ImportedTargetsOwned.back().get();
  3880. }
  3881. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3882. bool excludeAliases) const
  3883. {
  3884. // Look for an imported target. These take priority because they
  3885. // are more local in scope and do not have to be globally unique.
  3886. auto targetName = name;
  3887. if (!excludeAliases) {
  3888. // Look for local alias targets.
  3889. auto alias = this->AliasTargets.find(name);
  3890. if (alias != this->AliasTargets.end()) {
  3891. targetName = alias->second;
  3892. }
  3893. }
  3894. auto imported = this->ImportedTargets.find(targetName);
  3895. if (imported != this->ImportedTargets.end()) {
  3896. return imported->second;
  3897. }
  3898. // Look for a target built in this directory.
  3899. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3900. return t;
  3901. }
  3902. // Look for a target built in this project.
  3903. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3904. }
  3905. bool cmMakefile::IsAlias(const std::string& name) const
  3906. {
  3907. if (cm::contains(this->AliasTargets, name)) {
  3908. return true;
  3909. }
  3910. return this->GetGlobalGenerator()->IsAlias(name);
  3911. }
  3912. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3913. bool isCustom) const
  3914. {
  3915. if (this->IsAlias(name)) {
  3916. std::ostringstream e;
  3917. e << "cannot create target \"" << name
  3918. << "\" because an alias with the same name already exists.";
  3919. msg = e.str();
  3920. return false;
  3921. }
  3922. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3923. // The name given conflicts with an existing target. Produce an
  3924. // error in a compatible way.
  3925. if (existing->IsImported()) {
  3926. // Imported targets were not supported in previous versions.
  3927. // This is new code, so we can make it an error.
  3928. std::ostringstream e;
  3929. e << "cannot create target \"" << name
  3930. << "\" because an imported target with the same name already exists.";
  3931. msg = e.str();
  3932. return false;
  3933. }
  3934. // target names must be globally unique
  3935. switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
  3936. case cmPolicies::WARN:
  3937. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3938. cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
  3939. CM_FALLTHROUGH;
  3940. case cmPolicies::OLD:
  3941. return true;
  3942. case cmPolicies::REQUIRED_IF_USED:
  3943. case cmPolicies::REQUIRED_ALWAYS:
  3944. this->IssueMessage(
  3945. MessageType::FATAL_ERROR,
  3946. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
  3947. return true;
  3948. case cmPolicies::NEW:
  3949. break;
  3950. }
  3951. // The conflict is with a non-imported target.
  3952. // Allow this if the user has requested support.
  3953. cmake* cm = this->GetCMakeInstance();
  3954. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3955. this != existing->GetMakefile() &&
  3956. cm->GetState()->GetGlobalPropertyAsBool(
  3957. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3958. return true;
  3959. }
  3960. // Produce an error that tells the user how to work around the
  3961. // problem.
  3962. std::ostringstream e;
  3963. e << "cannot create target \"" << name
  3964. << "\" because another target with the same name already exists. "
  3965. << "The existing target is ";
  3966. switch (existing->GetType()) {
  3967. case cmStateEnums::EXECUTABLE:
  3968. e << "an executable ";
  3969. break;
  3970. case cmStateEnums::STATIC_LIBRARY:
  3971. e << "a static library ";
  3972. break;
  3973. case cmStateEnums::SHARED_LIBRARY:
  3974. e << "a shared library ";
  3975. break;
  3976. case cmStateEnums::MODULE_LIBRARY:
  3977. e << "a module library ";
  3978. break;
  3979. case cmStateEnums::UTILITY:
  3980. e << "a custom target ";
  3981. break;
  3982. case cmStateEnums::INTERFACE_LIBRARY:
  3983. e << "an interface library ";
  3984. break;
  3985. default:
  3986. break;
  3987. }
  3988. e << "created in source directory \""
  3989. << existing->GetMakefile()->GetCurrentSourceDirectory() << "\". "
  3990. << "See documentation for policy CMP0002 for more details.";
  3991. msg = e.str();
  3992. return false;
  3993. }
  3994. return true;
  3995. }
  3996. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  3997. const std::string& binPath) const
  3998. {
  3999. // Make sure the binary directory is unique.
  4000. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  4001. if (gg->BinaryDirectoryIsNew(binPath)) {
  4002. return true;
  4003. }
  4004. std::ostringstream e;
  4005. switch (this->GetPolicyStatus(cmPolicies::CMP0013)) {
  4006. case cmPolicies::WARN:
  4007. // Print the warning.
  4008. /* clang-format off */
  4009. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0013)
  4010. << "\n"
  4011. << "The binary directory\n"
  4012. << " " << binPath << "\n"
  4013. << "is already used to build a source directory. "
  4014. << "This command uses it to build source directory\n"
  4015. << " " << srcPath << "\n"
  4016. << "which can generate conflicting build files. "
  4017. << "CMake does not support this use case but it used "
  4018. << "to work accidentally and is being allowed for "
  4019. << "compatibility.";
  4020. /* clang-format on */
  4021. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  4022. CM_FALLTHROUGH;
  4023. case cmPolicies::OLD:
  4024. // OLD behavior does not warn.
  4025. return true;
  4026. case cmPolicies::REQUIRED_IF_USED:
  4027. case cmPolicies::REQUIRED_ALWAYS:
  4028. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0013) << "\n";
  4029. CM_FALLTHROUGH;
  4030. case cmPolicies::NEW:
  4031. // NEW behavior prints the error.
  4032. /* clang-format off */
  4033. e << "The binary directory\n"
  4034. << " " << binPath << "\n"
  4035. << "is already used to build a source directory. "
  4036. << "It cannot be used to build source directory\n"
  4037. << " " << srcPath << "\n"
  4038. << "Specify a unique binary directory name.";
  4039. /* clang-format on */
  4040. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4041. break;
  4042. }
  4043. return false;
  4044. }
  4045. static std::string const matchVariables[] = {
  4046. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  4047. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  4048. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  4049. };
  4050. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  4051. void cmMakefile::ClearMatches()
  4052. {
  4053. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  4054. if (!nMatchesStr) {
  4055. return;
  4056. }
  4057. int nMatches = atoi(nMatchesStr->c_str());
  4058. for (int i = 0; i <= nMatches; i++) {
  4059. std::string const& var = matchVariables[i];
  4060. std::string const& s = this->GetSafeDefinition(var);
  4061. if (!s.empty()) {
  4062. this->AddDefinition(var, "");
  4063. this->MarkVariableAsUsed(var);
  4064. }
  4065. }
  4066. this->AddDefinition(nMatchesVariable, "0");
  4067. this->MarkVariableAsUsed(nMatchesVariable);
  4068. }
  4069. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  4070. {
  4071. char highest = 0;
  4072. for (int i = 0; i < 10; i++) {
  4073. std::string const& m = re.match(i);
  4074. if (!m.empty()) {
  4075. std::string const& var = matchVariables[i];
  4076. this->AddDefinition(var, m);
  4077. this->MarkVariableAsUsed(var);
  4078. highest = static_cast<char>('0' + i);
  4079. }
  4080. }
  4081. char nMatches[] = { highest, '\0' };
  4082. this->AddDefinition(nMatchesVariable, nMatches);
  4083. this->MarkVariableAsUsed(nMatchesVariable);
  4084. }
  4085. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  4086. {
  4087. return this->StateSnapshot;
  4088. }
  4089. const char* cmMakefile::GetDefineFlagsCMP0059() const
  4090. {
  4091. return this->DefineFlagsOrig.c_str();
  4092. }
  4093. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  4094. bool parent_scope) const
  4095. {
  4096. return this->StateSnapshot.GetPolicy(id, parent_scope);
  4097. }
  4098. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  4099. {
  4100. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  4101. if (cmValue val = this->GetDefinition(var)) {
  4102. return cmIsOn(val);
  4103. }
  4104. // Enable optional policy warnings with --debug-output, --trace,
  4105. // or --trace-expand.
  4106. cmake* cm = this->GetCMakeInstance();
  4107. return cm->GetDebugOutput() || cm->GetTrace();
  4108. }
  4109. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  4110. {
  4111. cmPolicies::PolicyID pid;
  4112. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  4113. std::ostringstream e;
  4114. e << "Policy \"" << id << "\" is not known to this version of CMake.";
  4115. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4116. return false;
  4117. }
  4118. return this->SetPolicy(pid, status);
  4119. }
  4120. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  4121. cmPolicies::PolicyStatus status)
  4122. {
  4123. // A REQUIRED_ALWAYS policy may be set only to NEW.
  4124. if (status != cmPolicies::NEW &&
  4125. cmPolicies::GetPolicyStatus(id) == cmPolicies::REQUIRED_ALWAYS) {
  4126. std::string msg = cmPolicies::GetRequiredAlwaysPolicyError(id);
  4127. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  4128. return false;
  4129. }
  4130. // Deprecate old policies.
  4131. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0126 &&
  4132. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  4133. (
  4134. // Policies set by cmCoreTryCompile::TryCompileCode.
  4135. id == cmPolicies::CMP0065 || id == cmPolicies::CMP0083 ||
  4136. id == cmPolicies::CMP0091 || id == cmPolicies::CMP0104 ||
  4137. id == cmPolicies::CMP0123 || id == cmPolicies::CMP0126)) &&
  4138. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  4139. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  4140. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  4141. cmPolicies::GetPolicyDeprecatedWarning(id));
  4142. }
  4143. this->StateSnapshot.SetPolicy(id, status);
  4144. return true;
  4145. }
  4146. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  4147. : Makefile(m)
  4148. {
  4149. this->Makefile->PushPolicy();
  4150. }
  4151. cmMakefile::PolicyPushPop::~PolicyPushPop()
  4152. {
  4153. this->Makefile->PopPolicy();
  4154. }
  4155. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  4156. {
  4157. this->StateSnapshot.PushPolicy(pm, weak);
  4158. }
  4159. void cmMakefile::PopPolicy()
  4160. {
  4161. if (!this->StateSnapshot.PopPolicy()) {
  4162. this->IssueMessage(MessageType::FATAL_ERROR,
  4163. "cmake_policy POP without matching PUSH");
  4164. }
  4165. }
  4166. void cmMakefile::PopSnapshot(bool reportError)
  4167. {
  4168. // cmStateSnapshot manages nested policy scopes within it.
  4169. // Since the scope corresponding to the snapshot is closing,
  4170. // reject any still-open nested policy scopes with an error.
  4171. while (this->StateSnapshot.CanPopPolicyScope()) {
  4172. if (reportError) {
  4173. this->IssueMessage(MessageType::FATAL_ERROR,
  4174. "cmake_policy PUSH without matching POP");
  4175. reportError = false;
  4176. }
  4177. this->PopPolicy();
  4178. }
  4179. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  4180. assert(this->StateSnapshot.IsValid());
  4181. }
  4182. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  4183. std::string const& version_max)
  4184. {
  4185. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  4186. cmPolicies::WarnCompat::On);
  4187. }
  4188. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  4189. : Makefile(m)
  4190. {
  4191. this->Makefile->StateSnapshot =
  4192. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  4193. this->Makefile->StateSnapshot);
  4194. }
  4195. cmMakefile::VariablePushPop::~VariablePushPop()
  4196. {
  4197. this->Makefile->PopSnapshot();
  4198. }
  4199. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  4200. cmListFileContext const& context) const
  4201. {
  4202. return !this->CMP0054ReportedIds.insert(context).second;
  4203. }
  4204. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  4205. {
  4206. /* Record the setting of every policy. */
  4207. using PolicyID = cmPolicies::PolicyID;
  4208. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  4209. pid = static_cast<PolicyID>(pid + 1)) {
  4210. pm.Set(pid, this->GetPolicyStatus(pid));
  4211. }
  4212. }
  4213. bool cmMakefile::IgnoreErrorsCMP0061() const
  4214. {
  4215. bool ignoreErrors = true;
  4216. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  4217. case cmPolicies::WARN:
  4218. // No warning for this policy!
  4219. CM_FALLTHROUGH;
  4220. case cmPolicies::OLD:
  4221. break;
  4222. case cmPolicies::REQUIRED_IF_USED:
  4223. case cmPolicies::REQUIRED_ALWAYS:
  4224. case cmPolicies::NEW:
  4225. ignoreErrors = false;
  4226. break;
  4227. }
  4228. return ignoreErrors;
  4229. }
  4230. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  4231. const std::string& fileName,
  4232. cmPolicies::PolicyMap const& pm)
  4233. : Makefile(mf)
  4234. {
  4235. this->Makefile->PushFunctionScope(fileName, pm);
  4236. }
  4237. cmMakefile::FunctionPushPop::~FunctionPushPop()
  4238. {
  4239. this->Makefile->PopFunctionScope(this->ReportError);
  4240. }
  4241. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  4242. const std::string& fileName,
  4243. const cmPolicies::PolicyMap& pm)
  4244. : Makefile(mf)
  4245. {
  4246. this->Makefile->PushMacroScope(fileName, pm);
  4247. }
  4248. cmMakefile::MacroPushPop::~MacroPushPop()
  4249. {
  4250. this->Makefile->PopMacroScope(this->ReportError);
  4251. }
  4252. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  4253. std::string const& pkg)
  4254. : Makefile(mf)
  4255. , OldValue(this->Makefile->DebugFindPkg)
  4256. {
  4257. this->Makefile->DebugFindPkg =
  4258. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  4259. }
  4260. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  4261. {
  4262. this->Makefile->DebugFindPkg = this->OldValue;
  4263. }
  4264. bool cmMakefile::GetDebugFindPkgMode() const
  4265. {
  4266. return this->DebugFindPkg;
  4267. }