cmMakefile.cxx 157 KB

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