cmMakefile.cxx 147 KB

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