cmMakefile.cxx 129 KB

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