cmMakefile.cxx 134 KB

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