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 "cmSourceFile.h"
  33. #include "cmSourceFileLocation.h"
  34. #include "cmState.h"
  35. #include "cmStateDirectory.h"
  36. #include "cmStateTypes.h"
  37. #include "cmSystemTools.h"
  38. #include "cmTargetLinkLibraryType.h"
  39. #include "cmTest.h"
  40. #include "cmTestGenerator.h" // IWYU pragma: keep
  41. #include "cmVersion.h"
  42. #include "cmWorkingDirectory.h"
  43. #include "cm_sys_stat.h"
  44. #include "cmake.h"
  45. #include "cmConfigure.h" // IWYU pragma: keep
  46. #ifdef CMAKE_BUILD_WITH_CMAKE
  47. # include "cmVariableWatch.h"
  48. #endif
  49. class cmMessenger;
  50. cmDirectoryId::cmDirectoryId(std::string s)
  51. : String(std::move(s))
  52. {
  53. }
  54. // default is not to be building executables
  55. cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
  56. cmStateSnapshot const& snapshot)
  57. : GlobalGenerator(globalGenerator)
  58. , StateSnapshot(snapshot)
  59. , Backtrace(snapshot)
  60. {
  61. this->IsSourceFileTryCompile = false;
  62. this->WarnUnused = this->GetCMakeInstance()->GetWarnUnused();
  63. this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
  64. this->SuppressSideEffects = false;
  65. // Setup the default include complaint regular expression (match nothing).
  66. this->ComplainFileRegularExpression = "^$";
  67. this->DefineFlags = " ";
  68. this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
  69. this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  70. this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
  71. this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
  72. this->StateSnapshot =
  73. this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  74. this->StateSnapshot);
  75. this->RecursionDepth = 0;
  76. // Enter a policy level for this directory.
  77. this->PushPolicy();
  78. // push empty loop block
  79. this->PushLoopBlockBarrier();
  80. // By default the check is not done. It is enabled by
  81. // cmListFileCache in the top level if necessary.
  82. this->CheckCMP0000 = false;
  83. #if defined(CMAKE_BUILD_WITH_CMAKE)
  84. this->AddSourceGroup("", "^.*$");
  85. this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
  86. this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  87. this->AddSourceGroup("CMake Rules", "\\.rule$");
  88. this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
  89. this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
  90. this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
  91. this->SourceGroups.emplace_back("Object Libraries", "^MATCH_NO_SOURCES$");
  92. #endif
  93. }
  94. cmMakefile::~cmMakefile()
  95. {
  96. cmDeleteAll(this->InstallGenerators);
  97. cmDeleteAll(this->TestGenerators);
  98. cmDeleteAll(this->SourceFiles);
  99. cmDeleteAll(this->Tests);
  100. cmDeleteAll(this->ImportedTargetsOwned);
  101. cmDeleteAll(this->FinalPassCommands);
  102. cmDeleteAll(this->FunctionBlockers);
  103. cmDeleteAll(this->EvaluationFiles);
  104. }
  105. cmDirectoryId cmMakefile::GetDirectoryId() const
  106. {
  107. // Use the instance pointer value to uniquely identify this directory.
  108. // If we ever need to expose this to CMake language code we should
  109. // add a read-only property in cmMakefile::GetProperty.
  110. char buf[32];
  111. sprintf(buf, "<%p>",
  112. static_cast<void const*>(this)); // cast avoids format warning
  113. return std::string(buf);
  114. }
  115. void cmMakefile::IssueMessage(MessageType t, std::string const& text) const
  116. {
  117. if (!this->ExecutionStatusStack.empty()) {
  118. if ((t == MessageType::FATAL_ERROR) ||
  119. (t == MessageType::INTERNAL_ERROR)) {
  120. this->ExecutionStatusStack.back()->SetNestedError();
  121. }
  122. }
  123. this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace());
  124. }
  125. bool cmMakefile::CheckCMP0037(std::string const& targetName,
  126. cmStateEnums::TargetType targetType) const
  127. {
  128. MessageType messageType = MessageType::AUTHOR_WARNING;
  129. std::ostringstream e;
  130. bool issueMessage = false;
  131. switch (this->GetPolicyStatus(cmPolicies::CMP0037)) {
  132. case cmPolicies::WARN:
  133. if (targetType != cmStateEnums::INTERFACE_LIBRARY) {
  134. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  135. issueMessage = true;
  136. }
  137. CM_FALLTHROUGH;
  138. case cmPolicies::OLD:
  139. break;
  140. case cmPolicies::NEW:
  141. case cmPolicies::REQUIRED_IF_USED:
  142. case cmPolicies::REQUIRED_ALWAYS:
  143. issueMessage = true;
  144. messageType = MessageType::FATAL_ERROR;
  145. break;
  146. }
  147. if (issueMessage) {
  148. e << "The target name \"" << targetName
  149. << "\" is reserved or not valid for certain "
  150. "CMake features, such as generator expressions, and may result "
  151. "in undefined behavior.";
  152. this->IssueMessage(messageType, e.str());
  153. if (messageType == MessageType::FATAL_ERROR) {
  154. return false;
  155. }
  156. }
  157. return true;
  158. }
  159. void cmMakefile::MaybeWarnCMP0074(std::string const& pkg)
  160. {
  161. // Warn if a <pkg>_ROOT variable we may use is set.
  162. std::string const varName = pkg + "_ROOT";
  163. const char* var = this->GetDefinition(varName);
  164. std::string env;
  165. cmSystemTools::GetEnv(varName, env);
  166. bool const haveVar = var && *var;
  167. bool const haveEnv = !env.empty();
  168. if ((haveVar || haveEnv) && this->WarnedCMP0074.insert(varName).second) {
  169. std::ostringstream w;
  170. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0074) << "\n";
  171. if (haveVar) {
  172. w << "CMake variable " << varName << " is set to:\n"
  173. << " " << var << "\n";
  174. }
  175. if (haveEnv) {
  176. w << "Environment variable " << varName << " is set to:\n"
  177. << " " << env << "\n";
  178. }
  179. w << "For compatibility, CMake is ignoring the variable.";
  180. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  181. }
  182. }
  183. cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const
  184. {
  185. return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
  186. }
  187. cmBacktraceRange cmMakefile::GetIncludeDirectoriesBacktraces() const
  188. {
  189. return this->StateSnapshot.GetDirectory()
  190. .GetIncludeDirectoriesEntryBacktraces();
  191. }
  192. cmStringRange cmMakefile::GetCompileOptionsEntries() const
  193. {
  194. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
  195. }
  196. cmBacktraceRange cmMakefile::GetCompileOptionsBacktraces() const
  197. {
  198. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntryBacktraces();
  199. }
  200. cmStringRange cmMakefile::GetCompileDefinitionsEntries() const
  201. {
  202. return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
  203. }
  204. cmBacktraceRange cmMakefile::GetCompileDefinitionsBacktraces() const
  205. {
  206. return this->StateSnapshot.GetDirectory()
  207. .GetCompileDefinitionsEntryBacktraces();
  208. }
  209. cmStringRange cmMakefile::GetLinkOptionsEntries() const
  210. {
  211. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
  212. }
  213. cmBacktraceRange cmMakefile::GetLinkOptionsBacktraces() const
  214. {
  215. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntryBacktraces();
  216. }
  217. cmStringRange cmMakefile::GetLinkDirectoriesEntries() const
  218. {
  219. return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
  220. }
  221. cmBacktraceRange cmMakefile::GetLinkDirectoriesBacktraces() const
  222. {
  223. return this->StateSnapshot.GetDirectory()
  224. .GetLinkDirectoriesEntryBacktraces();
  225. }
  226. cmListFileBacktrace cmMakefile::GetBacktrace() const
  227. {
  228. return this->Backtrace;
  229. }
  230. cmListFileBacktrace cmMakefile::GetBacktrace(cmCommandContext const& cc) const
  231. {
  232. cmListFileContext lfc;
  233. lfc.Name = cc.Name.Original;
  234. lfc.Line = cc.Line;
  235. lfc.FilePath = this->StateSnapshot.GetExecutionListFile();
  236. return this->Backtrace.Push(lfc);
  237. }
  238. cmListFileContext cmMakefile::GetExecutionContext() const
  239. {
  240. cmListFileContext const& cur = this->Backtrace.Top();
  241. cmListFileContext lfc;
  242. lfc.Name = cur.Name;
  243. lfc.Line = cur.Line;
  244. lfc.FilePath = this->StateSnapshot.GetExecutionListFile();
  245. return lfc;
  246. }
  247. void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
  248. {
  249. // Check if current file in the list of requested to trace...
  250. std::vector<std::string> const& trace_only_this_files =
  251. this->GetCMakeInstance()->GetTraceSources();
  252. std::string const& full_path = this->GetExecutionFilePath();
  253. std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
  254. bool trace = trace_only_this_files.empty();
  255. if (!trace) {
  256. for (std::string const& file : trace_only_this_files) {
  257. std::string::size_type const pos = full_path.rfind(file);
  258. trace = (pos != std::string::npos) &&
  259. ((pos + file.size()) == full_path.size()) &&
  260. (only_filename == cmSystemTools::GetFilenameName(file));
  261. if (trace) {
  262. break;
  263. }
  264. }
  265. // Do nothing if current file wasn't requested for trace...
  266. if (!trace) {
  267. return;
  268. }
  269. }
  270. std::ostringstream msg;
  271. msg << full_path << "(" << lff.Line << "): ";
  272. msg << lff.Name.Original << "(";
  273. bool expand = this->GetCMakeInstance()->GetTraceExpand();
  274. std::string temp;
  275. for (cmListFileArgument const& arg : lff.Arguments) {
  276. if (expand) {
  277. temp = arg.Value;
  278. this->ExpandVariablesInString(temp);
  279. msg << temp;
  280. } else {
  281. msg << arg.Value;
  282. }
  283. msg << " ";
  284. }
  285. msg << ")";
  286. cmSystemTools::Message(msg.str());
  287. }
  288. // Helper class to make sure the call stack is valid.
  289. class cmMakefileCall
  290. {
  291. public:
  292. cmMakefileCall(cmMakefile* mf, cmCommandContext const& cc,
  293. cmExecutionStatus& status)
  294. : Makefile(mf)
  295. {
  296. cmListFileContext const& lfc = cmListFileContext::FromCommandContext(
  297. cc, this->Makefile->StateSnapshot.GetExecutionListFile());
  298. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  299. ++this->Makefile->RecursionDepth;
  300. this->Makefile->ExecutionStatusStack.push_back(&status);
  301. }
  302. ~cmMakefileCall()
  303. {
  304. this->Makefile->ExecutionStatusStack.pop_back();
  305. --this->Makefile->RecursionDepth;
  306. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  307. }
  308. cmMakefileCall(const cmMakefileCall&) = delete;
  309. cmMakefileCall& operator=(const cmMakefileCall&) = delete;
  310. private:
  311. cmMakefile* Makefile;
  312. };
  313. bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
  314. cmExecutionStatus& status)
  315. {
  316. bool result = true;
  317. // quick return if blocked
  318. if (this->IsFunctionBlocked(lff, status)) {
  319. // No error.
  320. return result;
  321. }
  322. // Place this call on the call stack.
  323. cmMakefileCall stack_manager(this, lff, status);
  324. static_cast<void>(stack_manager);
  325. // Check for maximum recursion depth.
  326. int depth = CMake_DEFAULT_RECURSION_LIMIT;
  327. const char* depthStr = this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  328. if (depthStr) {
  329. std::istringstream s(depthStr);
  330. int d;
  331. if (s >> d) {
  332. depth = d;
  333. }
  334. }
  335. if (this->RecursionDepth > depth) {
  336. std::ostringstream e;
  337. e << "Maximum recursion depth of " << depth << " exceeded";
  338. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  339. cmSystemTools::SetFatalErrorOccured();
  340. return false;
  341. }
  342. // Lookup the command prototype.
  343. if (cmCommand* proto =
  344. this->GetState()->GetCommandByExactName(lff.Name.Lower)) {
  345. // Clone the prototype.
  346. std::unique_ptr<cmCommand> pcmd(proto->Clone());
  347. pcmd->SetMakefile(this);
  348. // Decide whether to invoke the command.
  349. if (!cmSystemTools::GetFatalErrorOccured()) {
  350. // if trace is enabled, print out invoke information
  351. if (this->GetCMakeInstance()->GetTrace()) {
  352. this->PrintCommandTrace(lff);
  353. }
  354. // Try invoking the command.
  355. bool invokeSucceeded = pcmd->InvokeInitialPass(lff.Arguments, status);
  356. bool hadNestedError = status.GetNestedError();
  357. if (!invokeSucceeded || hadNestedError) {
  358. if (!hadNestedError) {
  359. // The command invocation requested that we report an error.
  360. std::string const error =
  361. std::string(lff.Name.Original) + " " + pcmd->GetError();
  362. this->IssueMessage(MessageType::FATAL_ERROR, error);
  363. }
  364. result = false;
  365. if (this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE) {
  366. cmSystemTools::SetFatalErrorOccured();
  367. }
  368. } else if (pcmd->HasFinalPass()) {
  369. // use the command
  370. this->FinalPassCommands.push_back(pcmd.release());
  371. }
  372. }
  373. } else {
  374. if (!cmSystemTools::GetFatalErrorOccured()) {
  375. std::string error = "Unknown CMake command \"";
  376. error += lff.Name.Original;
  377. error += "\".";
  378. this->IssueMessage(MessageType::FATAL_ERROR, error);
  379. result = false;
  380. cmSystemTools::SetFatalErrorOccured();
  381. }
  382. }
  383. return result;
  384. }
  385. class cmMakefile::IncludeScope
  386. {
  387. public:
  388. IncludeScope(cmMakefile* mf, std::string const& filenametoread,
  389. bool noPolicyScope);
  390. ~IncludeScope();
  391. void Quiet() { this->ReportError = false; }
  392. IncludeScope(const IncludeScope&) = delete;
  393. IncludeScope& operator=(const IncludeScope&) = delete;
  394. private:
  395. cmMakefile* Makefile;
  396. bool NoPolicyScope;
  397. bool CheckCMP0011;
  398. bool ReportError;
  399. void EnforceCMP0011();
  400. };
  401. cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
  402. std::string const& filenametoread,
  403. bool noPolicyScope)
  404. : Makefile(mf)
  405. , NoPolicyScope(noPolicyScope)
  406. , CheckCMP0011(false)
  407. , ReportError(true)
  408. {
  409. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(filenametoread);
  410. this->Makefile->PushFunctionBlockerBarrier();
  411. this->Makefile->StateSnapshot =
  412. this->Makefile->GetState()->CreateIncludeFileSnapshot(
  413. this->Makefile->StateSnapshot, filenametoread);
  414. if (!this->NoPolicyScope) {
  415. // Check CMP0011 to determine the policy scope type.
  416. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  417. case cmPolicies::WARN:
  418. // We need to push a scope to detect whether the script sets
  419. // any policies that would affect the includer and therefore
  420. // requires a warning. We use a weak scope to simulate OLD
  421. // behavior by allowing policy changes to affect the includer.
  422. this->Makefile->PushPolicy(true);
  423. this->CheckCMP0011 = true;
  424. break;
  425. case cmPolicies::OLD:
  426. // OLD behavior is to not push a scope at all.
  427. this->NoPolicyScope = true;
  428. break;
  429. case cmPolicies::REQUIRED_IF_USED:
  430. case cmPolicies::REQUIRED_ALWAYS:
  431. // We should never make this policy required, but we handle it
  432. // here just in case.
  433. this->CheckCMP0011 = true;
  434. CM_FALLTHROUGH;
  435. case cmPolicies::NEW:
  436. // NEW behavior is to push a (strong) scope.
  437. this->Makefile->PushPolicy();
  438. break;
  439. }
  440. }
  441. }
  442. cmMakefile::IncludeScope::~IncludeScope()
  443. {
  444. if (!this->NoPolicyScope) {
  445. // If we need to enforce policy CMP0011 then the top entry is the
  446. // one we pushed above. If the entry is empty, then the included
  447. // script did not set any policies that might affect the includer so
  448. // we do not need to enforce the policy.
  449. if (this->CheckCMP0011 &&
  450. !this->Makefile->StateSnapshot.HasDefinedPolicyCMP0011()) {
  451. this->CheckCMP0011 = false;
  452. }
  453. // Pop the scope we pushed for the script.
  454. this->Makefile->PopPolicy();
  455. // We enforce the policy after the script's policy stack entry has
  456. // been removed.
  457. if (this->CheckCMP0011) {
  458. this->EnforceCMP0011();
  459. }
  460. }
  461. this->Makefile->PopSnapshot(this->ReportError);
  462. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  463. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  464. }
  465. void cmMakefile::IncludeScope::EnforceCMP0011()
  466. {
  467. // We check the setting of this policy again because the included
  468. // script might actually set this policy for its includer.
  469. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  470. case cmPolicies::WARN:
  471. // Warn because the user did not set this policy.
  472. {
  473. std::ostringstream w;
  474. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
  475. << "The included script\n "
  476. << this->Makefile->GetExecutionFilePath() << "\n"
  477. << "affects policy settings. "
  478. << "CMake is implying the NO_POLICY_SCOPE option for compatibility, "
  479. << "so the effects are applied to the including context.";
  480. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  481. }
  482. break;
  483. case cmPolicies::REQUIRED_IF_USED:
  484. case cmPolicies::REQUIRED_ALWAYS: {
  485. std::ostringstream e;
  486. /* clang-format off */
  487. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
  488. << "The included script\n "
  489. << this->Makefile->GetExecutionFilePath() << "\n"
  490. << "affects policy settings, so it requires this policy to be set.";
  491. /* clang-format on */
  492. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  493. } break;
  494. case cmPolicies::OLD:
  495. case cmPolicies::NEW:
  496. // The script set this policy. We assume the purpose of the
  497. // script is to initialize policies for its includer, and since
  498. // the policy is now set for later scripts, we do not warn.
  499. break;
  500. }
  501. }
  502. bool cmMakefile::ReadDependentFile(const std::string& filename,
  503. bool noPolicyScope)
  504. {
  505. this->AddDefinition("CMAKE_PARENT_LIST_FILE",
  506. this->GetDefinition("CMAKE_CURRENT_LIST_FILE"));
  507. std::string filenametoread = cmSystemTools::CollapseFullPath(
  508. filename, this->GetCurrentSourceDirectory());
  509. IncludeScope incScope(this, filenametoread, noPolicyScope);
  510. cmListFile listFile;
  511. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  512. this->Backtrace)) {
  513. return false;
  514. }
  515. this->ReadListFile(listFile, filenametoread);
  516. if (cmSystemTools::GetFatalErrorOccured()) {
  517. incScope.Quiet();
  518. }
  519. return true;
  520. }
  521. class cmMakefile::ListFileScope
  522. {
  523. public:
  524. ListFileScope(cmMakefile* mf, std::string const& filenametoread)
  525. : Makefile(mf)
  526. , ReportError(true)
  527. {
  528. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(filenametoread);
  529. this->Makefile->StateSnapshot =
  530. this->Makefile->GetState()->CreateInlineListFileSnapshot(
  531. this->Makefile->StateSnapshot, filenametoread);
  532. assert(this->Makefile->StateSnapshot.IsValid());
  533. this->Makefile->PushFunctionBlockerBarrier();
  534. }
  535. ~ListFileScope()
  536. {
  537. this->Makefile->PopSnapshot(this->ReportError);
  538. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  539. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  540. }
  541. void Quiet() { this->ReportError = false; }
  542. ListFileScope(const ListFileScope&) = delete;
  543. ListFileScope& operator=(const ListFileScope&) = delete;
  544. private:
  545. cmMakefile* Makefile;
  546. bool ReportError;
  547. };
  548. bool cmMakefile::ReadListFile(const std::string& filename)
  549. {
  550. std::string filenametoread = cmSystemTools::CollapseFullPath(
  551. filename, this->GetCurrentSourceDirectory());
  552. ListFileScope scope(this, filenametoread);
  553. cmListFile listFile;
  554. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  555. this->Backtrace)) {
  556. return false;
  557. }
  558. this->ReadListFile(listFile, filenametoread);
  559. if (cmSystemTools::GetFatalErrorOccured()) {
  560. scope.Quiet();
  561. }
  562. return true;
  563. }
  564. void cmMakefile::ReadListFile(cmListFile const& listFile,
  565. std::string const& filenametoread)
  566. {
  567. // add this list file to the list of dependencies
  568. this->ListFiles.push_back(filenametoread);
  569. std::string currentParentFile =
  570. this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
  571. std::string currentFile = this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");
  572. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread.c_str());
  573. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  574. cmSystemTools::GetFilenamePath(filenametoread).c_str());
  575. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  576. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  577. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  578. // Run the parsed commands.
  579. const size_t numberFunctions = listFile.Functions.size();
  580. for (size_t i = 0; i < numberFunctions; ++i) {
  581. cmExecutionStatus status;
  582. this->ExecuteCommand(listFile.Functions[i], status);
  583. if (cmSystemTools::GetFatalErrorOccured()) {
  584. break;
  585. }
  586. if (status.GetReturnInvoked()) {
  587. // Exit early due to return command.
  588. break;
  589. }
  590. }
  591. this->CheckForUnusedVariables();
  592. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile.c_str());
  593. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile.c_str());
  594. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  595. cmSystemTools::GetFilenamePath(currentFile).c_str());
  596. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  597. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  598. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  599. }
  600. void cmMakefile::EnforceDirectoryLevelRules() const
  601. {
  602. // Diagnose a violation of CMP0000 if necessary.
  603. if (this->CheckCMP0000) {
  604. std::ostringstream msg;
  605. msg << "No cmake_minimum_required command is present. "
  606. << "A line of code such as\n"
  607. << " cmake_minimum_required(VERSION " << cmVersion::GetMajorVersion()
  608. << "." << cmVersion::GetMinorVersion() << ")\n"
  609. << "should be added at the top of the file. "
  610. << "The version specified may be lower if you wish to "
  611. << "support older CMake versions for this project. "
  612. << "For more information run "
  613. << "\"cmake --help-policy CMP0000\".";
  614. switch (this->GetPolicyStatus(cmPolicies::CMP0000)) {
  615. case cmPolicies::WARN:
  616. // Warn because the user did not provide a minimum required
  617. // version.
  618. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  619. msg.str(), this->Backtrace);
  620. case cmPolicies::OLD:
  621. // OLD behavior is to use policy version 2.4 set in
  622. // cmListFileCache.
  623. break;
  624. case cmPolicies::REQUIRED_IF_USED:
  625. case cmPolicies::REQUIRED_ALWAYS:
  626. case cmPolicies::NEW:
  627. // NEW behavior is to issue an error.
  628. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  629. msg.str(), this->Backtrace);
  630. cmSystemTools::SetFatalErrorOccured();
  631. return;
  632. }
  633. }
  634. }
  635. void cmMakefile::AddEvaluationFile(
  636. const std::string& inputFile,
  637. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  638. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  639. bool inputIsContent)
  640. {
  641. this->EvaluationFiles.push_back(new cmGeneratorExpressionEvaluationFile(
  642. inputFile, std::move(outputName), std::move(condition), inputIsContent,
  643. this->GetPolicyStatus(cmPolicies::CMP0070)));
  644. }
  645. std::vector<cmGeneratorExpressionEvaluationFile*>
  646. cmMakefile::GetEvaluationFiles() const
  647. {
  648. return this->EvaluationFiles;
  649. }
  650. std::vector<cmExportBuildFileGenerator*>
  651. cmMakefile::GetExportBuildFileGenerators() const
  652. {
  653. return this->ExportBuildFileGenerators;
  654. }
  655. void cmMakefile::RemoveExportBuildFileGeneratorCMP0024(
  656. cmExportBuildFileGenerator* gen)
  657. {
  658. std::vector<cmExportBuildFileGenerator*>::iterator it =
  659. std::find(this->ExportBuildFileGenerators.begin(),
  660. this->ExportBuildFileGenerators.end(), gen);
  661. if (it != this->ExportBuildFileGenerators.end()) {
  662. this->ExportBuildFileGenerators.erase(it);
  663. }
  664. }
  665. void cmMakefile::AddExportBuildFileGenerator(cmExportBuildFileGenerator* gen)
  666. {
  667. this->ExportBuildFileGenerators.push_back(gen);
  668. }
  669. namespace {
  670. struct file_not_persistent
  671. {
  672. bool operator()(const std::string& path) const
  673. {
  674. return !(path.find("CMakeTmp") == std::string::npos &&
  675. cmSystemTools::FileExists(path));
  676. }
  677. };
  678. }
  679. void cmMakefile::FinalPass()
  680. {
  681. // do all the variable expansions here
  682. this->ExpandVariablesCMP0019();
  683. // give all the commands a chance to do something
  684. // after the file has been parsed before generation
  685. for (cmCommand* fpCommand : this->FinalPassCommands) {
  686. fpCommand->FinalPass();
  687. }
  688. // go through all configured files and see which ones still exist.
  689. // we don't want cmake to re-run if a configured file is created and deleted
  690. // during processing as that would make it a transient file that can't
  691. // influence the build process
  692. cmEraseIf(this->OutputFiles, file_not_persistent());
  693. // if a configured file is used as input for another configured file,
  694. // and then deleted it will show up in the input list files so we
  695. // need to scan those too
  696. cmEraseIf(this->ListFiles, file_not_persistent());
  697. }
  698. // Generate the output file
  699. void cmMakefile::ConfigureFinalPass()
  700. {
  701. this->FinalPass();
  702. const char* oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
  703. if (oldValue &&
  704. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, oldValue, "2.4")) {
  705. this->GetCMakeInstance()->IssueMessage(
  706. MessageType::FATAL_ERROR,
  707. "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
  708. "than 2.4. This version of CMake only supports backwards compatibility "
  709. "with CMake 2.4 or later. For compatibility with older versions please "
  710. "use any CMake 2.8.x release or lower.",
  711. this->Backtrace);
  712. }
  713. }
  714. void cmMakefile::AddCustomCommandToTarget(
  715. const std::string& target, const std::vector<std::string>& byproducts,
  716. const std::vector<std::string>& depends,
  717. const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
  718. const char* comment, const char* workingDir, bool escapeOldStyle,
  719. bool uses_terminal, const std::string& depfile, bool command_expand_lists,
  720. ObjectLibraryCommands objLibraryCommands)
  721. {
  722. // Find the target to which to add the custom command.
  723. cmTargets::iterator ti = this->Targets.find(target);
  724. if (ti == this->Targets.end()) {
  725. MessageType messageType = MessageType::AUTHOR_WARNING;
  726. bool issueMessage = false;
  727. std::ostringstream e;
  728. switch (this->GetPolicyStatus(cmPolicies::CMP0040)) {
  729. case cmPolicies::WARN:
  730. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
  731. issueMessage = true;
  732. case cmPolicies::OLD:
  733. break;
  734. case cmPolicies::NEW:
  735. case cmPolicies::REQUIRED_IF_USED:
  736. case cmPolicies::REQUIRED_ALWAYS:
  737. issueMessage = true;
  738. messageType = MessageType::FATAL_ERROR;
  739. }
  740. if (issueMessage) {
  741. if (cmTarget const* t = this->FindTargetToUse(target)) {
  742. if (t->IsImported()) {
  743. e << "TARGET '" << target
  744. << "' is IMPORTED and does not build here.";
  745. } else {
  746. e << "TARGET '" << target << "' was not created in this directory.";
  747. }
  748. } else {
  749. e << "No TARGET '" << target
  750. << "' has been created in this directory.";
  751. }
  752. IssueMessage(messageType, e.str());
  753. }
  754. return;
  755. }
  756. cmTarget& t = ti->second;
  757. if (objLibraryCommands == RejectObjectLibraryCommands &&
  758. t.GetType() == cmStateEnums::OBJECT_LIBRARY) {
  759. std::ostringstream e;
  760. e << "Target \"" << target
  761. << "\" is an OBJECT library "
  762. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  763. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  764. return;
  765. }
  766. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  767. std::ostringstream e;
  768. e << "Target \"" << target
  769. << "\" is an INTERFACE library "
  770. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  771. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  772. return;
  773. }
  774. // Always create the byproduct sources and mark them generated.
  775. for (std::string const& o : byproducts) {
  776. if (cmSourceFile* out = this->GetOrCreateSource(o, true)) {
  777. out->SetProperty("GENERATED", "1");
  778. }
  779. }
  780. // Add the command to the appropriate build step for the target.
  781. std::vector<std::string> no_output;
  782. cmCustomCommand cc(this, no_output, byproducts, depends, commandLines,
  783. comment, workingDir);
  784. cc.SetEscapeOldStyle(escapeOldStyle);
  785. cc.SetEscapeAllowMakeVars(true);
  786. cc.SetUsesTerminal(uses_terminal);
  787. cc.SetCommandExpandLists(command_expand_lists);
  788. cc.SetDepfile(depfile);
  789. switch (type) {
  790. case cmTarget::PRE_BUILD:
  791. t.AddPreBuildCommand(cc);
  792. break;
  793. case cmTarget::PRE_LINK:
  794. t.AddPreLinkCommand(cc);
  795. break;
  796. case cmTarget::POST_BUILD:
  797. t.AddPostBuildCommand(cc);
  798. break;
  799. }
  800. }
  801. cmSourceFile* cmMakefile::AddCustomCommandToOutput(
  802. const std::vector<std::string>& outputs,
  803. const std::vector<std::string>& byproducts,
  804. const std::vector<std::string>& depends, const std::string& main_dependency,
  805. const cmCustomCommandLines& commandLines, const char* comment,
  806. const char* workingDir, bool replace, bool escapeOldStyle,
  807. bool uses_terminal, bool command_expand_lists, const std::string& depfile)
  808. {
  809. // Make sure there is at least one output.
  810. if (outputs.empty()) {
  811. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  812. return nullptr;
  813. }
  814. // Validate custom commands. TODO: More strict?
  815. for (cmCustomCommandLine const& cl : commandLines) {
  816. if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') {
  817. std::ostringstream e;
  818. e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
  819. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  820. return nullptr;
  821. }
  822. }
  823. // Choose a source file on which to store the custom command.
  824. cmSourceFile* file = nullptr;
  825. if (!commandLines.empty() && !main_dependency.empty()) {
  826. // The main dependency was specified. Use it unless a different
  827. // custom command already used it.
  828. file = this->GetSource(main_dependency);
  829. if (file && file->GetCustomCommand() && !replace) {
  830. // The main dependency already has a custom command.
  831. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  832. // The existing custom command is identical. Silently ignore
  833. // the duplicate.
  834. return file;
  835. }
  836. // The existing custom command is different. We need to
  837. // generate a rule file for this new command.
  838. file = nullptr;
  839. } else if (!file) {
  840. file = this->CreateSource(main_dependency);
  841. }
  842. }
  843. // Generate a rule file if the main dependency is not available.
  844. if (!file) {
  845. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  846. // Construct a rule file associated with the first output produced.
  847. std::string outName = gg->GenerateRuleFile(outputs[0]);
  848. // Check if the rule file already exists.
  849. file = this->GetSource(outName, cmSourceFileLocationKind::Known);
  850. if (file && file->GetCustomCommand() && !replace) {
  851. // The rule file already exists.
  852. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  853. cmSystemTools::Error("Attempt to add a custom rule to output \"",
  854. outName.c_str(),
  855. "\" 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.c_str());
  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 ",
  1067. force.c_str());
  1068. }
  1069. // Always create the byproduct sources and mark them generated.
  1070. for (std::string const& byproduct : byproducts) {
  1071. if (cmSourceFile* out = this->GetOrCreateSource(
  1072. byproduct, true, cmSourceFileLocationKind::Known)) {
  1073. out->SetProperty("GENERATED", "1");
  1074. }
  1075. }
  1076. }
  1077. return target;
  1078. }
  1079. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1080. {
  1081. // remove any \n\r
  1082. std::string::size_type initSize = dflags.size();
  1083. dflags += ' ';
  1084. dflags += flag;
  1085. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1086. std::replace(flagStart, dflags.end(), '\n', ' ');
  1087. std::replace(flagStart, dflags.end(), '\r', ' ');
  1088. }
  1089. void cmMakefile::AddDefineFlag(std::string const& flag)
  1090. {
  1091. if (flag.empty()) {
  1092. return;
  1093. }
  1094. // Update the string used for the old DEFINITIONS property.
  1095. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1096. // If this is really a definition, update COMPILE_DEFINITIONS.
  1097. if (this->ParseDefineFlag(flag, false)) {
  1098. return;
  1099. }
  1100. // Add this flag that does not look like a definition.
  1101. s_AddDefineFlag(flag, this->DefineFlags);
  1102. }
  1103. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1104. {
  1105. std::string::size_type const len = flag.length();
  1106. // Remove all instances of the flag that are surrounded by
  1107. // whitespace or the beginning/end of the string.
  1108. for (std::string::size_type lpos = dflags.find(flag, 0);
  1109. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1110. std::string::size_type rpos = lpos + len;
  1111. if ((lpos <= 0 || isspace(dflags[lpos - 1])) &&
  1112. (rpos >= dflags.size() || isspace(dflags[rpos]))) {
  1113. dflags.erase(lpos, len);
  1114. } else {
  1115. ++lpos;
  1116. }
  1117. }
  1118. }
  1119. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1120. {
  1121. // Check the length of the flag to remove.
  1122. if (flag.empty()) {
  1123. return;
  1124. }
  1125. // Update the string used for the old DEFINITIONS property.
  1126. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1127. // If this is really a definition, update COMPILE_DEFINITIONS.
  1128. if (this->ParseDefineFlag(flag, true)) {
  1129. return;
  1130. }
  1131. // Remove this flag that does not look like a definition.
  1132. s_RemoveDefineFlag(flag, this->DefineFlags);
  1133. }
  1134. void cmMakefile::AddCompileDefinition(std::string const& option)
  1135. {
  1136. this->AppendProperty("COMPILE_DEFINITIONS", option.c_str());
  1137. }
  1138. void cmMakefile::AddCompileOption(std::string const& option)
  1139. {
  1140. this->AppendProperty("COMPILE_OPTIONS", option.c_str());
  1141. }
  1142. void cmMakefile::AddLinkOption(std::string const& option)
  1143. {
  1144. this->AppendProperty("LINK_OPTIONS", option.c_str());
  1145. }
  1146. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1147. {
  1148. cmListFileBacktrace lfbt = this->GetBacktrace();
  1149. if (before) {
  1150. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(directory,
  1151. lfbt);
  1152. } else {
  1153. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(directory,
  1154. lfbt);
  1155. }
  1156. }
  1157. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1158. {
  1159. // Create a regular expression to match valid definitions.
  1160. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1161. // Make sure the definition matches.
  1162. if (!valid.find(def)) {
  1163. return false;
  1164. }
  1165. // Definitions with non-trivial values require a policy check.
  1166. static cmsys::RegularExpression trivial(
  1167. "^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
  1168. if (!trivial.find(def)) {
  1169. // This definition has a non-trivial value.
  1170. switch (this->GetPolicyStatus(cmPolicies::CMP0005)) {
  1171. case cmPolicies::WARN:
  1172. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1173. cmPolicies::GetPolicyWarning(cmPolicies::CMP0005));
  1174. CM_FALLTHROUGH;
  1175. case cmPolicies::OLD:
  1176. // OLD behavior is to not escape the value. We should not
  1177. // convert the definition to use the property.
  1178. return false;
  1179. case cmPolicies::REQUIRED_IF_USED:
  1180. case cmPolicies::REQUIRED_ALWAYS:
  1181. this->IssueMessage(
  1182. MessageType::FATAL_ERROR,
  1183. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005));
  1184. return false;
  1185. case cmPolicies::NEW:
  1186. // NEW behavior is to escape the value. Proceed to convert it
  1187. // to an entry in the property.
  1188. break;
  1189. }
  1190. }
  1191. // Get the definition part after the flag.
  1192. const char* define = def.c_str() + 2;
  1193. if (remove) {
  1194. if (const char* cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1195. // Expand the list.
  1196. std::vector<std::string> defs;
  1197. cmSystemTools::ExpandListArgument(cdefs, defs);
  1198. // Recompose the list without the definition.
  1199. std::vector<std::string>::const_iterator defEnd =
  1200. std::remove(defs.begin(), defs.end(), define);
  1201. std::vector<std::string>::const_iterator defBegin = defs.begin();
  1202. std::string ndefs = cmJoin(cmMakeRange(defBegin, defEnd), ";");
  1203. // Store the new list.
  1204. this->SetProperty("COMPILE_DEFINITIONS", ndefs.c_str());
  1205. }
  1206. } else {
  1207. // Append the definition to the directory property.
  1208. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1209. }
  1210. return true;
  1211. }
  1212. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1213. {
  1214. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1215. // define flags
  1216. this->DefineFlags = parent->DefineFlags;
  1217. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1218. // Include transform property. There is no per-config version.
  1219. {
  1220. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1221. this->SetProperty(prop, parent->GetProperty(prop));
  1222. }
  1223. // compile definitions property and per-config versions
  1224. cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
  1225. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1226. this->SetProperty("COMPILE_DEFINITIONS",
  1227. parent->GetProperty("COMPILE_DEFINITIONS"));
  1228. std::vector<std::string> configs;
  1229. this->GetConfigurations(configs);
  1230. for (std::string const& config : configs) {
  1231. std::string defPropName = "COMPILE_DEFINITIONS_";
  1232. defPropName += cmSystemTools::UpperCase(config);
  1233. const char* prop = parent->GetProperty(defPropName);
  1234. this->SetProperty(defPropName, prop);
  1235. }
  1236. }
  1237. // labels
  1238. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1239. // link libraries
  1240. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1241. // the initial project name
  1242. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1243. // Copy include regular expressions.
  1244. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1245. // Imported targets.
  1246. this->ImportedTargets = parent->ImportedTargets;
  1247. // Recursion depth.
  1248. this->RecursionDepth = parent->RecursionDepth;
  1249. }
  1250. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1251. const cmPolicies::PolicyMap& pm)
  1252. {
  1253. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1254. this->StateSnapshot, fileName);
  1255. assert(this->StateSnapshot.IsValid());
  1256. this->PushLoopBlockBarrier();
  1257. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1258. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1259. #endif
  1260. this->PushFunctionBlockerBarrier();
  1261. this->PushPolicy(true, pm);
  1262. }
  1263. void cmMakefile::PopFunctionScope(bool reportError)
  1264. {
  1265. this->PopPolicy();
  1266. this->PopSnapshot(reportError);
  1267. this->PopFunctionBlockerBarrier(reportError);
  1268. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1269. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1270. #endif
  1271. this->PopLoopBlockBarrier();
  1272. this->CheckForUnusedVariables();
  1273. }
  1274. void cmMakefile::PushMacroScope(std::string const& fileName,
  1275. const cmPolicies::PolicyMap& pm)
  1276. {
  1277. this->StateSnapshot =
  1278. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1279. assert(this->StateSnapshot.IsValid());
  1280. this->PushFunctionBlockerBarrier();
  1281. this->PushPolicy(true, pm);
  1282. }
  1283. void cmMakefile::PopMacroScope(bool reportError)
  1284. {
  1285. this->PopPolicy();
  1286. this->PopSnapshot(reportError);
  1287. this->PopFunctionBlockerBarrier(reportError);
  1288. }
  1289. bool cmMakefile::IsRootMakefile() const
  1290. {
  1291. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1292. }
  1293. class cmMakefile::BuildsystemFileScope
  1294. {
  1295. public:
  1296. BuildsystemFileScope(cmMakefile* mf)
  1297. : Makefile(mf)
  1298. , ReportError(true)
  1299. {
  1300. std::string currentStart =
  1301. this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource();
  1302. currentStart += "/CMakeLists.txt";
  1303. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1304. this->Makefile->StateSnapshot =
  1305. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1306. this->Makefile->StateSnapshot);
  1307. this->Makefile->PushFunctionBlockerBarrier();
  1308. this->GG = mf->GetGlobalGenerator();
  1309. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1310. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1311. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1312. this->GG->SetCurrentMakefile(mf);
  1313. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1314. this->GG->GetFileLockPool().PushFileScope();
  1315. #endif
  1316. }
  1317. ~BuildsystemFileScope()
  1318. {
  1319. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1320. this->Makefile->PopSnapshot(this->ReportError);
  1321. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1322. this->GG->GetFileLockPool().PopFileScope();
  1323. #endif
  1324. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1325. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1326. }
  1327. void Quiet() { this->ReportError = false; }
  1328. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1329. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1330. private:
  1331. cmMakefile* Makefile;
  1332. cmGlobalGenerator* GG;
  1333. cmMakefile* CurrentMakefile;
  1334. cmStateSnapshot Snapshot;
  1335. bool ReportError;
  1336. };
  1337. void cmMakefile::Configure()
  1338. {
  1339. std::string currentStart =
  1340. this->StateSnapshot.GetDirectory().GetCurrentSource();
  1341. currentStart += "/CMakeLists.txt";
  1342. // Add the bottom of all backtraces within this directory.
  1343. // We will never pop this scope because it should be available
  1344. // for messages during the generate step too.
  1345. this->Backtrace = this->Backtrace.Push(currentStart);
  1346. BuildsystemFileScope scope(this);
  1347. // make sure the CMakeFiles dir is there
  1348. std::string filesDir = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1349. filesDir += "/CMakeFiles";
  1350. cmSystemTools::MakeDirectory(filesDir);
  1351. assert(cmSystemTools::FileExists(currentStart, true));
  1352. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart.c_str());
  1353. cmListFile listFile;
  1354. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1355. this->Backtrace)) {
  1356. return;
  1357. }
  1358. if (this->IsRootMakefile()) {
  1359. bool hasVersion = false;
  1360. // search for the right policy command
  1361. for (cmListFileFunction const& func : listFile.Functions) {
  1362. if (func.Name.Lower == "cmake_minimum_required") {
  1363. hasVersion = true;
  1364. break;
  1365. }
  1366. }
  1367. // if no policy command is found this is an error if they use any
  1368. // non advanced functions or a lot of functions
  1369. if (!hasVersion) {
  1370. bool isProblem = true;
  1371. if (listFile.Functions.size() < 30) {
  1372. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1373. // these commands must have backwards compatibility forever and
  1374. // and that is a lot longer than your tiny mind can comprehend mortal
  1375. std::set<std::string> allowedCommands;
  1376. allowedCommands.insert("project");
  1377. allowedCommands.insert("set");
  1378. allowedCommands.insert("if");
  1379. allowedCommands.insert("endif");
  1380. allowedCommands.insert("else");
  1381. allowedCommands.insert("elseif");
  1382. allowedCommands.insert("add_executable");
  1383. allowedCommands.insert("add_library");
  1384. allowedCommands.insert("target_link_libraries");
  1385. allowedCommands.insert("option");
  1386. allowedCommands.insert("message");
  1387. isProblem = false;
  1388. for (cmListFileFunction const& func : listFile.Functions) {
  1389. if (allowedCommands.find(func.Name.Lower) == allowedCommands.end()) {
  1390. isProblem = true;
  1391. break;
  1392. }
  1393. }
  1394. }
  1395. if (isProblem) {
  1396. // Tell the top level cmMakefile to diagnose
  1397. // this violation of CMP0000.
  1398. this->SetCheckCMP0000(true);
  1399. // Implicitly set the version for the user.
  1400. this->SetPolicyVersion("2.4", std::string());
  1401. }
  1402. }
  1403. bool hasProject = false;
  1404. // search for a project command
  1405. for (cmListFileFunction const& func : listFile.Functions) {
  1406. if (func.Name.Lower == "project") {
  1407. hasProject = true;
  1408. break;
  1409. }
  1410. }
  1411. // if no project command is found, add one
  1412. if (!hasProject) {
  1413. cmListFileFunction project;
  1414. project.Name.Lower = "project";
  1415. project.Arguments.emplace_back("Project", cmListFileArgument::Unquoted,
  1416. 0);
  1417. project.Arguments.emplace_back("__CMAKE_INJECTED_PROJECT_COMMAND__",
  1418. cmListFileArgument::Unquoted, 0);
  1419. listFile.Functions.insert(listFile.Functions.begin(), project);
  1420. }
  1421. }
  1422. this->ReadListFile(listFile, currentStart);
  1423. if (cmSystemTools::GetFatalErrorOccured()) {
  1424. scope.Quiet();
  1425. }
  1426. // at the end handle any old style subdirs
  1427. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1428. // for each subdir recurse
  1429. std::vector<cmMakefile*>::iterator sdi = subdirs.begin();
  1430. for (; sdi != subdirs.end(); ++sdi) {
  1431. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1432. this->ConfigureSubDirectory(*sdi);
  1433. }
  1434. this->AddCMakeDependFilesFromUser();
  1435. }
  1436. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1437. {
  1438. mf->InitializeFromParent(this);
  1439. std::string currentStart = mf->GetCurrentSourceDirectory();
  1440. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1441. std::string msg = " Entering ";
  1442. msg += currentStart;
  1443. cmSystemTools::Message(msg);
  1444. }
  1445. std::string const currentStartFile = currentStart + "/CMakeLists.txt";
  1446. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1447. // The file is missing. Check policy CMP0014.
  1448. std::ostringstream e;
  1449. /* clang-format off */
  1450. e << "The source directory\n"
  1451. << " " << currentStart << "\n"
  1452. << "does not contain a CMakeLists.txt file.";
  1453. /* clang-format on */
  1454. switch (this->GetPolicyStatus(cmPolicies::CMP0014)) {
  1455. case cmPolicies::WARN:
  1456. // Print the warning.
  1457. /* clang-format off */
  1458. e << "\n"
  1459. << "CMake does not support this case but it used "
  1460. << "to work accidentally and is being allowed for "
  1461. << "compatibility."
  1462. << "\n"
  1463. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
  1464. /* clang-format on */
  1465. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1466. case cmPolicies::OLD:
  1467. // OLD behavior does not warn.
  1468. break;
  1469. case cmPolicies::REQUIRED_IF_USED:
  1470. case cmPolicies::REQUIRED_ALWAYS:
  1471. e << "\n" << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
  1472. CM_FALLTHROUGH;
  1473. case cmPolicies::NEW:
  1474. // NEW behavior prints the error.
  1475. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1476. }
  1477. return;
  1478. }
  1479. // finally configure the subdir
  1480. mf->Configure();
  1481. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1482. std::string msg = " Returning to ";
  1483. msg += this->GetCurrentSourceDirectory();
  1484. cmSystemTools::Message(msg);
  1485. }
  1486. }
  1487. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1488. const std::string& binPath,
  1489. bool excludeFromAll, bool immediate)
  1490. {
  1491. // Make sure the binary directory is unique.
  1492. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1493. return;
  1494. }
  1495. cmStateSnapshot newSnapshot =
  1496. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1497. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1498. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1499. cmSystemTools::MakeDirectory(binPath);
  1500. cmMakefile* subMf = new cmMakefile(this->GlobalGenerator, newSnapshot);
  1501. this->GetGlobalGenerator()->AddMakefile(subMf);
  1502. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1503. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1504. }
  1505. if (immediate) {
  1506. this->ConfigureSubDirectory(subMf);
  1507. } else {
  1508. this->UnConfiguredDirectories.push_back(subMf);
  1509. }
  1510. this->AddInstallGenerator(new cmInstallSubdirectoryGenerator(
  1511. subMf, binPath.c_str(), excludeFromAll));
  1512. }
  1513. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1514. {
  1515. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1516. }
  1517. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1518. {
  1519. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1520. }
  1521. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1522. {
  1523. std::vector<cmTarget*> tgts;
  1524. tgts.reserve(this->ImportedTargets.size());
  1525. for (auto const& impTarget : this->ImportedTargets) {
  1526. tgts.push_back(impTarget.second);
  1527. }
  1528. return tgts;
  1529. }
  1530. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1531. bool before)
  1532. {
  1533. if (incs.empty()) {
  1534. return;
  1535. }
  1536. cmListFileBacktrace lfbt = this->GetBacktrace();
  1537. std::string entryString = cmJoin(incs, ";");
  1538. if (before) {
  1539. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1540. entryString, lfbt);
  1541. } else {
  1542. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1543. entryString, lfbt);
  1544. }
  1545. // Property on each target:
  1546. for (auto& target : this->Targets) {
  1547. cmTarget& t = target.second;
  1548. t.InsertInclude(entryString, lfbt, before);
  1549. }
  1550. }
  1551. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1552. {
  1553. if (incs.empty()) {
  1554. return;
  1555. }
  1556. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1557. for (auto& target : this->Targets) {
  1558. cmTarget& t = target.second;
  1559. t.AddSystemIncludeDirectories(incs);
  1560. }
  1561. }
  1562. void cmMakefile::AddDefinition(const std::string& name, const char* value)
  1563. {
  1564. if (!value) {
  1565. return;
  1566. }
  1567. if (this->VariableInitialized(name)) {
  1568. this->LogUnused("changing definition", name);
  1569. }
  1570. this->StateSnapshot.SetDefinition(name, value);
  1571. #ifdef CMAKE_BUILD_WITH_CMAKE
  1572. cmVariableWatch* vv = this->GetVariableWatch();
  1573. if (vv) {
  1574. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1575. value, this);
  1576. }
  1577. #endif
  1578. }
  1579. void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
  1580. const char* doc,
  1581. cmStateEnums::CacheEntryType type,
  1582. bool force)
  1583. {
  1584. const std::string* existingValue =
  1585. this->GetState()->GetInitializedCacheValue(name);
  1586. // must be outside the following if() to keep it alive long enough
  1587. std::string nvalue;
  1588. if (existingValue &&
  1589. (this->GetState()->GetCacheEntryType(name) ==
  1590. cmStateEnums::UNINITIALIZED)) {
  1591. // if this is not a force, then use the value from the cache
  1592. // if it is a force, then use the value being passed in
  1593. if (!force) {
  1594. value = existingValue->c_str();
  1595. }
  1596. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1597. std::vector<std::string>::size_type cc;
  1598. std::vector<std::string> files;
  1599. nvalue = value ? value : "";
  1600. cmSystemTools::ExpandListArgument(nvalue, files);
  1601. nvalue.clear();
  1602. for (cc = 0; cc < files.size(); cc++) {
  1603. if (!cmSystemTools::IsOff(files[cc])) {
  1604. files[cc] = cmSystemTools::CollapseFullPath(files[cc]);
  1605. }
  1606. if (cc > 0) {
  1607. nvalue += ";";
  1608. }
  1609. nvalue += files[cc];
  1610. }
  1611. this->GetCMakeInstance()->AddCacheEntry(name, nvalue.c_str(), doc, type);
  1612. nvalue = *this->GetState()->GetInitializedCacheValue(name);
  1613. value = nvalue.c_str();
  1614. }
  1615. }
  1616. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1617. // if there was a definition then remove it
  1618. this->StateSnapshot.RemoveDefinition(name);
  1619. }
  1620. void cmMakefile::AddDefinition(const std::string& name, bool value)
  1621. {
  1622. if (this->VariableInitialized(name)) {
  1623. this->LogUnused("changing definition", name);
  1624. }
  1625. this->StateSnapshot.SetDefinition(name, value ? "ON" : "OFF");
  1626. #ifdef CMAKE_BUILD_WITH_CMAKE
  1627. cmVariableWatch* vv = this->GetVariableWatch();
  1628. if (vv) {
  1629. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1630. value ? "ON" : "OFF", this);
  1631. }
  1632. #endif
  1633. }
  1634. void cmMakefile::CheckForUnusedVariables() const
  1635. {
  1636. if (!this->WarnUnused) {
  1637. return;
  1638. }
  1639. for (const std::string& key : this->StateSnapshot.UnusedKeys()) {
  1640. this->LogUnused("out of scope", key);
  1641. }
  1642. }
  1643. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1644. {
  1645. this->StateSnapshot.GetDefinition(var);
  1646. }
  1647. bool cmMakefile::VariableInitialized(const std::string& var) const
  1648. {
  1649. return this->StateSnapshot.IsInitialized(var);
  1650. }
  1651. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1652. const char* sourceFilename) const
  1653. {
  1654. // check to see if we need to print a warning
  1655. // if strict mode is on and the variable has
  1656. // not been "cleared"/initialized with a set(foo ) call
  1657. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1658. !this->VariableInitialized(variable)) {
  1659. if (this->CheckSystemVars ||
  1660. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1661. std::ostringstream msg;
  1662. msg << "uninitialized variable \'" << variable << "\'";
  1663. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1664. }
  1665. }
  1666. }
  1667. void cmMakefile::LogUnused(const char* reason, const std::string& name) const
  1668. {
  1669. if (this->WarnUnused) {
  1670. std::string path;
  1671. if (!this->ExecutionStatusStack.empty()) {
  1672. path = this->GetExecutionContext().FilePath;
  1673. } else {
  1674. path = this->GetCurrentSourceDirectory();
  1675. path += "/CMakeLists.txt";
  1676. }
  1677. if (this->CheckSystemVars || this->IsProjectFile(path.c_str())) {
  1678. std::ostringstream msg;
  1679. msg << "unused variable (" << reason << ") \'" << name << "\'";
  1680. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1681. }
  1682. }
  1683. }
  1684. void cmMakefile::RemoveDefinition(const std::string& name)
  1685. {
  1686. if (this->VariableInitialized(name)) {
  1687. this->LogUnused("unsetting", name);
  1688. }
  1689. this->StateSnapshot.RemoveDefinition(name);
  1690. #ifdef CMAKE_BUILD_WITH_CMAKE
  1691. cmVariableWatch* vv = this->GetVariableWatch();
  1692. if (vv) {
  1693. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1694. nullptr, this);
  1695. }
  1696. #endif
  1697. }
  1698. void cmMakefile::RemoveCacheDefinition(const std::string& name)
  1699. {
  1700. this->GetState()->RemoveCacheEntry(name);
  1701. }
  1702. void cmMakefile::SetProjectName(std::string const& p)
  1703. {
  1704. this->StateSnapshot.SetProjectName(p);
  1705. }
  1706. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1707. {
  1708. // for these targets do not add anything
  1709. switch (target.GetType()) {
  1710. case cmStateEnums::UTILITY:
  1711. case cmStateEnums::GLOBAL_TARGET:
  1712. case cmStateEnums::INTERFACE_LIBRARY:
  1713. return;
  1714. default:;
  1715. }
  1716. if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1717. std::vector<std::string> linkLibs;
  1718. cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs);
  1719. for (std::vector<std::string>::iterator j = linkLibs.begin();
  1720. j != linkLibs.end(); ++j) {
  1721. std::string libraryName = *j;
  1722. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1723. if (libraryName == "optimized") {
  1724. libType = OPTIMIZED_LibraryType;
  1725. ++j;
  1726. libraryName = *j;
  1727. } else if (libraryName == "debug") {
  1728. libType = DEBUG_LibraryType;
  1729. ++j;
  1730. libraryName = *j;
  1731. }
  1732. // This is equivalent to the target_link_libraries plain signature.
  1733. target.AddLinkLibrary(*this, libraryName, libType);
  1734. target.AppendProperty(
  1735. "INTERFACE_LINK_LIBRARIES",
  1736. target.GetDebugGeneratorExpressions(libraryName, libType).c_str());
  1737. }
  1738. }
  1739. }
  1740. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName)
  1741. {
  1742. this->AliasTargets[lname] = tgtName;
  1743. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1744. }
  1745. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1746. cmStateEnums::TargetType type,
  1747. const std::vector<std::string>& srcs,
  1748. bool excludeFromAll)
  1749. {
  1750. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1751. type == cmStateEnums::SHARED_LIBRARY ||
  1752. type == cmStateEnums::MODULE_LIBRARY ||
  1753. type == cmStateEnums::OBJECT_LIBRARY ||
  1754. type == cmStateEnums::INTERFACE_LIBRARY);
  1755. cmTarget* target = this->AddNewTarget(type, lname);
  1756. // Clear its dependencies. Otherwise, dependencies might persist
  1757. // over changes in CMakeLists.txt, making the information stale and
  1758. // hence useless.
  1759. target->ClearDependencyInformation(*this);
  1760. if (excludeFromAll ||
  1761. (type != cmStateEnums::INTERFACE_LIBRARY &&
  1762. this->GetPropertyAsBool("EXCLUDE_FROM_ALL"))) {
  1763. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1764. }
  1765. target->AddSources(srcs);
  1766. this->AddGlobalLinkInformation(*target);
  1767. return target;
  1768. }
  1769. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1770. const std::vector<std::string>& srcs,
  1771. bool excludeFromAll)
  1772. {
  1773. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1774. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1775. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1776. }
  1777. target->AddSources(srcs);
  1778. this->AddGlobalLinkInformation(*target);
  1779. return target;
  1780. }
  1781. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1782. const std::string& name)
  1783. {
  1784. cmTargets::iterator it =
  1785. this->Targets
  1786. .insert(cmTargets::value_type(
  1787. name, cmTarget(name, type, cmTarget::VisibilityNormal, this)))
  1788. .first;
  1789. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1790. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1791. return &it->second;
  1792. }
  1793. cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput(
  1794. const std::string& name) const
  1795. {
  1796. std::string out;
  1797. // look through all the source files that have custom commands
  1798. // and see if the custom command has the passed source file as an output
  1799. for (cmSourceFile* src : this->SourceFiles) {
  1800. // does this source file have a custom command?
  1801. if (src->GetCustomCommand()) {
  1802. // Does the output of the custom command match the source file name?
  1803. const std::vector<std::string>& outputs =
  1804. src->GetCustomCommand()->GetOutputs();
  1805. for (std::string const& output : outputs) {
  1806. out = output;
  1807. std::string::size_type pos = out.rfind(name);
  1808. // If the output matches exactly
  1809. if (pos != std::string::npos && pos == out.size() - name.size() &&
  1810. (pos == 0 || out[pos - 1] == '/')) {
  1811. return src;
  1812. }
  1813. }
  1814. }
  1815. }
  1816. // otherwise return NULL
  1817. return nullptr;
  1818. }
  1819. cmSourceFile* cmMakefile::GetSourceFileWithOutput(
  1820. const std::string& name) const
  1821. {
  1822. // If the queried path is not absolute we use the backward compatible
  1823. // linear-time search for an output with a matching suffix.
  1824. if (!cmSystemTools::FileIsFullPath(name)) {
  1825. return this->LinearGetSourceFileWithOutput(name);
  1826. }
  1827. // Otherwise we use an efficient lookup map.
  1828. OutputToSourceMap::const_iterator o = this->OutputToSource.find(name);
  1829. if (o != this->OutputToSource.end()) {
  1830. return (*o).second;
  1831. }
  1832. return nullptr;
  1833. }
  1834. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1835. cmSourceGroup* cmMakefile::GetSourceGroup(
  1836. const std::vector<std::string>& name) const
  1837. {
  1838. cmSourceGroup* sg = nullptr;
  1839. // first look for source group starting with the same as the one we want
  1840. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1841. std::string const& sgName = srcGroup.GetName();
  1842. if (sgName == name[0]) {
  1843. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1844. break;
  1845. }
  1846. }
  1847. if (sg != nullptr) {
  1848. // iterate through its children to find match source group
  1849. for (unsigned int i = 1; i < name.size(); ++i) {
  1850. sg = sg->LookupChild(name[i]);
  1851. if (sg == nullptr) {
  1852. break;
  1853. }
  1854. }
  1855. }
  1856. return sg;
  1857. }
  1858. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  1859. {
  1860. std::vector<std::string> nameVector;
  1861. nameVector.push_back(name);
  1862. this->AddSourceGroup(nameVector, regex);
  1863. }
  1864. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  1865. const char* regex)
  1866. {
  1867. cmSourceGroup* sg = nullptr;
  1868. std::vector<std::string> currentName;
  1869. int i = 0;
  1870. const int lastElement = static_cast<int>(name.size() - 1);
  1871. for (i = lastElement; i >= 0; --i) {
  1872. currentName.assign(name.begin(), name.begin() + i + 1);
  1873. sg = this->GetSourceGroup(currentName);
  1874. if (sg != nullptr) {
  1875. break;
  1876. }
  1877. }
  1878. // i now contains the index of the last found component
  1879. if (i == lastElement) {
  1880. // group already exists, replace its regular expression
  1881. if (regex && sg) {
  1882. // We only want to set the regular expression. If there are already
  1883. // source files in the group, we don't want to remove them.
  1884. sg->SetGroupRegex(regex);
  1885. }
  1886. return;
  1887. }
  1888. if (i == -1) {
  1889. // group does not exist nor belong to any existing group
  1890. // add its first component
  1891. this->SourceGroups.emplace_back(name[0], regex);
  1892. sg = this->GetSourceGroup(currentName);
  1893. i = 0; // last component found
  1894. }
  1895. if (!sg) {
  1896. cmSystemTools::Error("Could not create source group ");
  1897. return;
  1898. }
  1899. // build the whole source group path
  1900. for (++i; i <= lastElement; ++i) {
  1901. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  1902. sg = sg->LookupChild(name[i]);
  1903. }
  1904. sg->SetGroupRegex(regex);
  1905. }
  1906. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  1907. const std::vector<std::string>& folders)
  1908. {
  1909. cmSourceGroup* sg = this->GetSourceGroup(folders);
  1910. if (sg == nullptr) {
  1911. this->AddSourceGroup(folders);
  1912. sg = this->GetSourceGroup(folders);
  1913. }
  1914. return sg;
  1915. }
  1916. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  1917. {
  1918. const char* delimiter = this->GetDefinition("SOURCE_GROUP_DELIMITER");
  1919. if (delimiter == nullptr) {
  1920. delimiter = "\\";
  1921. }
  1922. return this->GetOrCreateSourceGroup(
  1923. cmSystemTools::tokenize(name, delimiter));
  1924. }
  1925. /**
  1926. * Find a source group whose regular expression matches the filename
  1927. * part of the given source name. Search backward through the list of
  1928. * source groups, and take the first matching group found. This way
  1929. * non-inherited SOURCE_GROUP commands will have precedence over
  1930. * inherited ones.
  1931. */
  1932. cmSourceGroup* cmMakefile::FindSourceGroup(
  1933. const std::string& source, std::vector<cmSourceGroup>& groups) const
  1934. {
  1935. // First search for a group that lists the file explicitly.
  1936. for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
  1937. sg != groups.rend(); ++sg) {
  1938. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  1939. if (result) {
  1940. return result;
  1941. }
  1942. }
  1943. // Now search for a group whose regex matches the file.
  1944. for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
  1945. sg != groups.rend(); ++sg) {
  1946. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  1947. if (result) {
  1948. return result;
  1949. }
  1950. }
  1951. // Shouldn't get here, but just in case, return the default group.
  1952. return groups.data();
  1953. }
  1954. #endif
  1955. static bool mightExpandVariablesCMP0019(const char* s)
  1956. {
  1957. return s && *s && strstr(s, "${") && strchr(s, '}');
  1958. }
  1959. void cmMakefile::ExpandVariablesCMP0019()
  1960. {
  1961. // Drop this ancient compatibility behavior with a policy.
  1962. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  1963. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  1964. return;
  1965. }
  1966. std::ostringstream w;
  1967. const char* includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  1968. if (mightExpandVariablesCMP0019(includeDirs)) {
  1969. std::string dirs = includeDirs;
  1970. this->ExpandVariablesInString(dirs, true, true);
  1971. if (pol == cmPolicies::WARN && dirs != includeDirs) {
  1972. /* clang-format off */
  1973. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  1974. << " " << includeDirs << "\n"
  1975. << "as\n"
  1976. << " " << dirs << "\n";
  1977. /* clang-format on */
  1978. }
  1979. this->SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
  1980. }
  1981. // Also for each target's INCLUDE_DIRECTORIES property:
  1982. for (auto& target : this->Targets) {
  1983. cmTarget& t = target.second;
  1984. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  1985. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  1986. continue;
  1987. }
  1988. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  1989. if (mightExpandVariablesCMP0019(includeDirs)) {
  1990. std::string dirs = includeDirs;
  1991. this->ExpandVariablesInString(dirs, true, true);
  1992. if (pol == cmPolicies::WARN && dirs != includeDirs) {
  1993. /* clang-format off */
  1994. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  1995. << " " << includeDirs << "\n"
  1996. << "as\n"
  1997. << " " << dirs << "\n";
  1998. /* clang-format on */
  1999. }
  2000. t.SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
  2001. }
  2002. }
  2003. if (const char* linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2004. if (mightExpandVariablesCMP0019(linkDirsProp)) {
  2005. std::string d = linkDirsProp;
  2006. std::string orig = linkDirsProp;
  2007. this->ExpandVariablesInString(d, true, true);
  2008. if (pol == cmPolicies::WARN && d != orig) {
  2009. /* clang-format off */
  2010. w << "Evaluated link directories\n"
  2011. << " " << orig << "\n"
  2012. << "as\n"
  2013. << " " << d << "\n";
  2014. /* clang-format on */
  2015. }
  2016. }
  2017. }
  2018. if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2019. std::vector<std::string> linkLibs;
  2020. cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs);
  2021. for (std::vector<std::string>::iterator l = linkLibs.begin();
  2022. l != linkLibs.end(); ++l) {
  2023. std::string libName = *l;
  2024. if (libName == "optimized") {
  2025. ++l;
  2026. libName = *l;
  2027. } else if (libName == "debug") {
  2028. ++l;
  2029. libName = *l;
  2030. }
  2031. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2032. std::string orig = libName;
  2033. this->ExpandVariablesInString(libName, true, true);
  2034. if (pol == cmPolicies::WARN && libName != orig) {
  2035. /* clang-format off */
  2036. w << "Evaluated link library\n"
  2037. << " " << orig << "\n"
  2038. << "as\n"
  2039. << " " << libName << "\n";
  2040. /* clang-format on */
  2041. }
  2042. }
  2043. }
  2044. }
  2045. if (!w.str().empty()) {
  2046. std::ostringstream m;
  2047. /* clang-format off */
  2048. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2049. << "\n"
  2050. << "The following variable evaluations were encountered:\n"
  2051. << w.str();
  2052. /* clang-format on */
  2053. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2054. m.str(), this->Backtrace);
  2055. }
  2056. }
  2057. bool cmMakefile::IsOn(const std::string& name) const
  2058. {
  2059. const char* value = this->GetDefinition(name);
  2060. return cmSystemTools::IsOn(value);
  2061. }
  2062. bool cmMakefile::IsSet(const std::string& name) const
  2063. {
  2064. const char* value = this->GetDefinition(name);
  2065. if (!value) {
  2066. return false;
  2067. }
  2068. if (!*value) {
  2069. return false;
  2070. }
  2071. if (cmSystemTools::IsNOTFOUND(value)) {
  2072. return false;
  2073. }
  2074. return true;
  2075. }
  2076. bool cmMakefile::PlatformIs32Bit() const
  2077. {
  2078. if (const char* plat_abi =
  2079. this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2080. if (strcmp(plat_abi, "ELF X32") == 0) {
  2081. return false;
  2082. }
  2083. }
  2084. if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2085. return atoi(sizeof_dptr) == 4;
  2086. }
  2087. return false;
  2088. }
  2089. bool cmMakefile::PlatformIs64Bit() const
  2090. {
  2091. if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2092. return atoi(sizeof_dptr) == 8;
  2093. }
  2094. return false;
  2095. }
  2096. bool cmMakefile::PlatformIsx32() const
  2097. {
  2098. if (const char* plat_abi =
  2099. this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2100. if (strcmp(plat_abi, "ELF X32") == 0) {
  2101. return true;
  2102. }
  2103. }
  2104. return false;
  2105. }
  2106. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2107. {
  2108. std::string sdkRoot;
  2109. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2110. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2111. struct
  2112. {
  2113. std::string name;
  2114. AppleSDK sdk;
  2115. } const sdkDatabase[]{
  2116. { "appletvos", AppleSDK::AppleTVOS },
  2117. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2118. { "iphoneos", AppleSDK::IPhoneOS },
  2119. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2120. { "watchos", AppleSDK::WatchOS },
  2121. { "watchsimulator", AppleSDK::WatchSimulator },
  2122. };
  2123. for (auto const& entry : sdkDatabase) {
  2124. if (sdkRoot.find(entry.name) == 0 ||
  2125. sdkRoot.find(std::string("/") + entry.name) != std::string::npos) {
  2126. return entry.sdk;
  2127. }
  2128. }
  2129. return AppleSDK::MacOS;
  2130. }
  2131. bool cmMakefile::PlatformIsAppleEmbedded() const
  2132. {
  2133. return GetAppleSDKType() != AppleSDK::MacOS;
  2134. }
  2135. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2136. {
  2137. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2138. if (!language.empty()) {
  2139. name += "_";
  2140. name += language;
  2141. }
  2142. name += "_FLAG";
  2143. return GetDefinition(name);
  2144. }
  2145. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2146. {
  2147. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2148. return true;
  2149. }
  2150. // If we are doing an in-source build, then the test will always fail
  2151. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2152. this->GetHomeOutputDirectory())) {
  2153. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2154. }
  2155. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2156. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2157. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2158. }
  2159. const std::string& cmMakefile::GetRequiredDefinition(
  2160. const std::string& name) const
  2161. {
  2162. static std::string const empty;
  2163. const std::string* def = GetDef(name);
  2164. if (!def) {
  2165. cmSystemTools::Error("Error required internal CMake variable not "
  2166. "set, cmake may not be built correctly.\n",
  2167. "Missing variable is:\n", name.c_str());
  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.c_str());
  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.c_str());
  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. }