cmMakefile.cxx 146 KB

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