cmMakefile.cxx 150 KB

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