cmMakefile.cxx 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmMakefile.h"
  4. #include "cmsys/FStream.hxx"
  5. #include "cmsys/RegularExpression.hxx"
  6. #include <algorithm>
  7. #include <assert.h>
  8. #include <cstring>
  9. #include <ctype.h>
  10. #include <iterator>
  11. #include <memory> // IWYU pragma: keep
  12. #include <sstream>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <utility>
  16. #include "cmAlgorithms.h"
  17. #include "cmCommand.h"
  18. #include "cmCommandArgumentParserHelper.h"
  19. #include "cmCustomCommand.h"
  20. #include "cmCustomCommandLines.h"
  21. #include "cmExecutionStatus.h"
  22. #include "cmExpandedCommandArgument.h" // IWYU pragma: keep
  23. #include "cmFileLockPool.h"
  24. #include "cmFunctionBlocker.h"
  25. #include "cmGeneratorExpression.h"
  26. #include "cmGeneratorExpressionEvaluationFile.h"
  27. #include "cmGlobalGenerator.h"
  28. #include "cmInstallGenerator.h" // IWYU pragma: keep
  29. #include "cmInstallSubdirectoryGenerator.h"
  30. #include "cmListFileCache.h"
  31. #include "cmMessageType.h"
  32. #include "cmRange.h"
  33. #include "cmSourceFile.h"
  34. #include "cmSourceFileLocation.h"
  35. #include "cmState.h"
  36. #include "cmStateDirectory.h"
  37. #include "cmStateTypes.h"
  38. #include "cmSystemTools.h"
  39. #include "cmTargetLinkLibraryType.h"
  40. #include "cmTest.h"
  41. #include "cmTestGenerator.h" // IWYU pragma: keep
  42. #include "cmVersion.h"
  43. #include "cmWorkingDirectory.h"
  44. #include "cm_sys_stat.h"
  45. #include "cmake.h"
  46. #include "cmConfigure.h" // IWYU pragma: keep
  47. #ifdef CMAKE_BUILD_WITH_CMAKE
  48. # include "cmVariableWatch.h"
  49. #endif
  50. class cmMessenger;
  51. cmDirectoryId::cmDirectoryId(std::string s)
  52. : String(std::move(s))
  53. {
  54. }
  55. // default is not to be building executables
  56. cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
  57. cmStateSnapshot const& snapshot)
  58. : GlobalGenerator(globalGenerator)
  59. , StateSnapshot(snapshot)
  60. , Backtrace(snapshot)
  61. {
  62. this->IsSourceFileTryCompile = false;
  63. this->WarnUnused = this->GetCMakeInstance()->GetWarnUnused();
  64. this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
  65. this->SuppressSideEffects = false;
  66. // Setup the default include complaint regular expression (match nothing).
  67. this->ComplainFileRegularExpression = "^$";
  68. this->DefineFlags = " ";
  69. this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
  70. this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  71. this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
  72. this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
  73. this->StateSnapshot =
  74. this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  75. this->StateSnapshot);
  76. this->RecursionDepth = 0;
  77. // Enter a policy level for this directory.
  78. this->PushPolicy();
  79. // push empty loop block
  80. this->PushLoopBlockBarrier();
  81. // By default the check is not done. It is enabled by
  82. // cmListFileCache in the top level if necessary.
  83. this->CheckCMP0000 = false;
  84. #if defined(CMAKE_BUILD_WITH_CMAKE)
  85. this->AddSourceGroup("", "^.*$");
  86. this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
  87. this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  88. this->AddSourceGroup("CMake Rules", "\\.rule$");
  89. this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
  90. this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
  91. this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
  92. this->SourceGroups.emplace_back("Object Libraries", "^MATCH_NO_SOURCES$");
  93. #endif
  94. }
  95. cmMakefile::~cmMakefile()
  96. {
  97. cmDeleteAll(this->InstallGenerators);
  98. cmDeleteAll(this->TestGenerators);
  99. cmDeleteAll(this->SourceFiles);
  100. cmDeleteAll(this->Tests);
  101. cmDeleteAll(this->ImportedTargetsOwned);
  102. cmDeleteAll(this->FinalPassCommands);
  103. cmDeleteAll(this->FunctionBlockers);
  104. cmDeleteAll(this->EvaluationFiles);
  105. }
  106. cmDirectoryId cmMakefile::GetDirectoryId() const
  107. {
  108. // Use the instance pointer value to uniquely identify this directory.
  109. // If we ever need to expose this to CMake language code we should
  110. // add a read-only property in cmMakefile::GetProperty.
  111. char buf[32];
  112. sprintf(buf, "<%p>",
  113. static_cast<void const*>(this)); // cast avoids format warning
  114. return std::string(buf);
  115. }
  116. void cmMakefile::IssueMessage(MessageType t, std::string const& text) const
  117. {
  118. if (!this->ExecutionStatusStack.empty()) {
  119. if ((t == MessageType::FATAL_ERROR) ||
  120. (t == MessageType::INTERNAL_ERROR)) {
  121. this->ExecutionStatusStack.back()->SetNestedError();
  122. }
  123. }
  124. this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace());
  125. }
  126. bool cmMakefile::CheckCMP0037(std::string const& targetName,
  127. cmStateEnums::TargetType targetType) const
  128. {
  129. MessageType messageType = MessageType::AUTHOR_WARNING;
  130. std::ostringstream e;
  131. bool issueMessage = false;
  132. switch (this->GetPolicyStatus(cmPolicies::CMP0037)) {
  133. case cmPolicies::WARN:
  134. if (targetType != cmStateEnums::INTERFACE_LIBRARY) {
  135. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  136. issueMessage = true;
  137. }
  138. CM_FALLTHROUGH;
  139. case cmPolicies::OLD:
  140. break;
  141. case cmPolicies::NEW:
  142. case cmPolicies::REQUIRED_IF_USED:
  143. case cmPolicies::REQUIRED_ALWAYS:
  144. issueMessage = true;
  145. messageType = MessageType::FATAL_ERROR;
  146. break;
  147. }
  148. if (issueMessage) {
  149. e << "The target name \"" << targetName
  150. << "\" is reserved or not valid for certain "
  151. "CMake features, such as generator expressions, and may result "
  152. "in undefined behavior.";
  153. this->IssueMessage(messageType, e.str());
  154. if (messageType == MessageType::FATAL_ERROR) {
  155. return false;
  156. }
  157. }
  158. return true;
  159. }
  160. void cmMakefile::MaybeWarnCMP0074(std::string const& pkg)
  161. {
  162. // Warn if a <pkg>_ROOT variable we may use is set.
  163. std::string const varName = pkg + "_ROOT";
  164. const char* var = this->GetDefinition(varName);
  165. std::string env;
  166. cmSystemTools::GetEnv(varName, env);
  167. bool const haveVar = var && *var;
  168. bool const haveEnv = !env.empty();
  169. if ((haveVar || haveEnv) && this->WarnedCMP0074.insert(varName).second) {
  170. std::ostringstream w;
  171. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0074) << "\n";
  172. if (haveVar) {
  173. w << "CMake variable " << varName << " is set to:\n"
  174. << " " << var << "\n";
  175. }
  176. if (haveEnv) {
  177. w << "Environment variable " << varName << " is set to:\n"
  178. << " " << env << "\n";
  179. }
  180. w << "For compatibility, CMake is ignoring the variable.";
  181. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  182. }
  183. }
  184. cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const
  185. {
  186. return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
  187. }
  188. cmBacktraceRange cmMakefile::GetIncludeDirectoriesBacktraces() const
  189. {
  190. return this->StateSnapshot.GetDirectory()
  191. .GetIncludeDirectoriesEntryBacktraces();
  192. }
  193. cmStringRange cmMakefile::GetCompileOptionsEntries() const
  194. {
  195. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
  196. }
  197. cmBacktraceRange cmMakefile::GetCompileOptionsBacktraces() const
  198. {
  199. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntryBacktraces();
  200. }
  201. cmStringRange cmMakefile::GetCompileDefinitionsEntries() const
  202. {
  203. return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
  204. }
  205. cmBacktraceRange cmMakefile::GetCompileDefinitionsBacktraces() const
  206. {
  207. return this->StateSnapshot.GetDirectory()
  208. .GetCompileDefinitionsEntryBacktraces();
  209. }
  210. cmStringRange cmMakefile::GetLinkOptionsEntries() const
  211. {
  212. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
  213. }
  214. cmBacktraceRange cmMakefile::GetLinkOptionsBacktraces() const
  215. {
  216. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntryBacktraces();
  217. }
  218. cmStringRange cmMakefile::GetLinkDirectoriesEntries() const
  219. {
  220. return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
  221. }
  222. cmBacktraceRange cmMakefile::GetLinkDirectoriesBacktraces() const
  223. {
  224. return this->StateSnapshot.GetDirectory()
  225. .GetLinkDirectoriesEntryBacktraces();
  226. }
  227. cmListFileBacktrace cmMakefile::GetBacktrace() const
  228. {
  229. return this->Backtrace;
  230. }
  231. cmListFileBacktrace cmMakefile::GetBacktrace(cmCommandContext const& cc) const
  232. {
  233. cmListFileContext lfc;
  234. lfc.Name = cc.Name.Original;
  235. lfc.Line = cc.Line;
  236. lfc.FilePath = this->StateSnapshot.GetExecutionListFile();
  237. return this->Backtrace.Push(lfc);
  238. }
  239. cmListFileContext cmMakefile::GetExecutionContext() const
  240. {
  241. cmListFileContext const& cur = this->Backtrace.Top();
  242. cmListFileContext lfc;
  243. lfc.Name = cur.Name;
  244. lfc.Line = cur.Line;
  245. lfc.FilePath = this->StateSnapshot.GetExecutionListFile();
  246. return lfc;
  247. }
  248. void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
  249. {
  250. // Check if current file in the list of requested to trace...
  251. std::vector<std::string> const& trace_only_this_files =
  252. this->GetCMakeInstance()->GetTraceSources();
  253. std::string const& full_path = this->GetExecutionFilePath();
  254. std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
  255. bool trace = trace_only_this_files.empty();
  256. if (!trace) {
  257. for (std::string const& file : trace_only_this_files) {
  258. std::string::size_type const pos = full_path.rfind(file);
  259. trace = (pos != std::string::npos) &&
  260. ((pos + file.size()) == full_path.size()) &&
  261. (only_filename == cmSystemTools::GetFilenameName(file));
  262. if (trace) {
  263. break;
  264. }
  265. }
  266. // Do nothing if current file wasn't requested for trace...
  267. if (!trace) {
  268. return;
  269. }
  270. }
  271. std::ostringstream msg;
  272. msg << full_path << "(" << lff.Line << "): ";
  273. msg << lff.Name.Original << "(";
  274. bool expand = this->GetCMakeInstance()->GetTraceExpand();
  275. std::string temp;
  276. for (cmListFileArgument const& arg : lff.Arguments) {
  277. if (expand) {
  278. temp = arg.Value;
  279. this->ExpandVariablesInString(temp);
  280. msg << temp;
  281. } else {
  282. msg << arg.Value;
  283. }
  284. msg << " ";
  285. }
  286. msg << ")";
  287. cmSystemTools::Message(msg.str());
  288. }
  289. // Helper class to make sure the call stack is valid.
  290. class cmMakefileCall
  291. {
  292. public:
  293. cmMakefileCall(cmMakefile* mf, cmCommandContext const& cc,
  294. cmExecutionStatus& status)
  295. : Makefile(mf)
  296. {
  297. cmListFileContext const& lfc = cmListFileContext::FromCommandContext(
  298. cc, this->Makefile->StateSnapshot.GetExecutionListFile());
  299. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  300. ++this->Makefile->RecursionDepth;
  301. this->Makefile->ExecutionStatusStack.push_back(&status);
  302. }
  303. ~cmMakefileCall()
  304. {
  305. this->Makefile->ExecutionStatusStack.pop_back();
  306. --this->Makefile->RecursionDepth;
  307. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  308. }
  309. cmMakefileCall(const cmMakefileCall&) = delete;
  310. cmMakefileCall& operator=(const cmMakefileCall&) = delete;
  311. private:
  312. cmMakefile* Makefile;
  313. };
  314. bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
  315. cmExecutionStatus& status)
  316. {
  317. bool result = true;
  318. // quick return if blocked
  319. if (this->IsFunctionBlocked(lff, status)) {
  320. // No error.
  321. return result;
  322. }
  323. // Place this call on the call stack.
  324. cmMakefileCall stack_manager(this, lff, status);
  325. static_cast<void>(stack_manager);
  326. // Check for maximum recursion depth.
  327. int depth = CMake_DEFAULT_RECURSION_LIMIT;
  328. const char* depthStr = this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  329. if (depthStr) {
  330. std::istringstream s(depthStr);
  331. int d;
  332. if (s >> d) {
  333. depth = d;
  334. }
  335. }
  336. if (this->RecursionDepth > depth) {
  337. std::ostringstream e;
  338. e << "Maximum recursion depth of " << depth << " exceeded";
  339. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  340. cmSystemTools::SetFatalErrorOccured();
  341. return false;
  342. }
  343. // Lookup the command prototype.
  344. if (cmCommand* proto =
  345. this->GetState()->GetCommandByExactName(lff.Name.Lower)) {
  346. // Clone the prototype.
  347. std::unique_ptr<cmCommand> pcmd(proto->Clone());
  348. pcmd->SetMakefile(this);
  349. // Decide whether to invoke the command.
  350. if (!cmSystemTools::GetFatalErrorOccured()) {
  351. // if trace is enabled, print out invoke information
  352. if (this->GetCMakeInstance()->GetTrace()) {
  353. this->PrintCommandTrace(lff);
  354. }
  355. // Try invoking the command.
  356. bool invokeSucceeded = pcmd->InvokeInitialPass(lff.Arguments, status);
  357. bool hadNestedError = status.GetNestedError();
  358. if (!invokeSucceeded || hadNestedError) {
  359. if (!hadNestedError) {
  360. // The command invocation requested that we report an error.
  361. std::string const error =
  362. std::string(lff.Name.Original) + " " + pcmd->GetError();
  363. this->IssueMessage(MessageType::FATAL_ERROR, error);
  364. }
  365. result = false;
  366. if (this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE) {
  367. cmSystemTools::SetFatalErrorOccured();
  368. }
  369. } else if (pcmd->HasFinalPass()) {
  370. // use the command
  371. this->FinalPassCommands.push_back(pcmd.release());
  372. }
  373. }
  374. } else {
  375. if (!cmSystemTools::GetFatalErrorOccured()) {
  376. std::string error = "Unknown CMake command \"";
  377. error += lff.Name.Original;
  378. error += "\".";
  379. this->IssueMessage(MessageType::FATAL_ERROR, error);
  380. result = false;
  381. cmSystemTools::SetFatalErrorOccured();
  382. }
  383. }
  384. return result;
  385. }
  386. class cmMakefile::IncludeScope
  387. {
  388. public:
  389. IncludeScope(cmMakefile* mf, std::string const& filenametoread,
  390. bool noPolicyScope);
  391. ~IncludeScope();
  392. void Quiet() { this->ReportError = false; }
  393. IncludeScope(const IncludeScope&) = delete;
  394. IncludeScope& operator=(const IncludeScope&) = delete;
  395. private:
  396. cmMakefile* Makefile;
  397. bool NoPolicyScope;
  398. bool CheckCMP0011;
  399. bool ReportError;
  400. void EnforceCMP0011();
  401. };
  402. cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
  403. std::string const& filenametoread,
  404. bool noPolicyScope)
  405. : Makefile(mf)
  406. , NoPolicyScope(noPolicyScope)
  407. , CheckCMP0011(false)
  408. , ReportError(true)
  409. {
  410. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(filenametoread);
  411. this->Makefile->PushFunctionBlockerBarrier();
  412. this->Makefile->StateSnapshot =
  413. this->Makefile->GetState()->CreateIncludeFileSnapshot(
  414. this->Makefile->StateSnapshot, filenametoread);
  415. if (!this->NoPolicyScope) {
  416. // Check CMP0011 to determine the policy scope type.
  417. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  418. case cmPolicies::WARN:
  419. // We need to push a scope to detect whether the script sets
  420. // any policies that would affect the includer and therefore
  421. // requires a warning. We use a weak scope to simulate OLD
  422. // behavior by allowing policy changes to affect the includer.
  423. this->Makefile->PushPolicy(true);
  424. this->CheckCMP0011 = true;
  425. break;
  426. case cmPolicies::OLD:
  427. // OLD behavior is to not push a scope at all.
  428. this->NoPolicyScope = true;
  429. break;
  430. case cmPolicies::REQUIRED_IF_USED:
  431. case cmPolicies::REQUIRED_ALWAYS:
  432. // We should never make this policy required, but we handle it
  433. // here just in case.
  434. this->CheckCMP0011 = true;
  435. CM_FALLTHROUGH;
  436. case cmPolicies::NEW:
  437. // NEW behavior is to push a (strong) scope.
  438. this->Makefile->PushPolicy();
  439. break;
  440. }
  441. }
  442. }
  443. cmMakefile::IncludeScope::~IncludeScope()
  444. {
  445. if (!this->NoPolicyScope) {
  446. // If we need to enforce policy CMP0011 then the top entry is the
  447. // one we pushed above. If the entry is empty, then the included
  448. // script did not set any policies that might affect the includer so
  449. // we do not need to enforce the policy.
  450. if (this->CheckCMP0011 &&
  451. !this->Makefile->StateSnapshot.HasDefinedPolicyCMP0011()) {
  452. this->CheckCMP0011 = false;
  453. }
  454. // Pop the scope we pushed for the script.
  455. this->Makefile->PopPolicy();
  456. // We enforce the policy after the script's policy stack entry has
  457. // been removed.
  458. if (this->CheckCMP0011) {
  459. this->EnforceCMP0011();
  460. }
  461. }
  462. this->Makefile->PopSnapshot(this->ReportError);
  463. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  464. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  465. }
  466. void cmMakefile::IncludeScope::EnforceCMP0011()
  467. {
  468. // We check the setting of this policy again because the included
  469. // script might actually set this policy for its includer.
  470. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  471. case cmPolicies::WARN:
  472. // Warn because the user did not set this policy.
  473. {
  474. std::ostringstream w;
  475. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
  476. << "The included script\n "
  477. << this->Makefile->GetExecutionFilePath() << "\n"
  478. << "affects policy settings. "
  479. << "CMake is implying the NO_POLICY_SCOPE option for compatibility, "
  480. << "so the effects are applied to the including context.";
  481. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  482. }
  483. break;
  484. case cmPolicies::REQUIRED_IF_USED:
  485. case cmPolicies::REQUIRED_ALWAYS: {
  486. std::ostringstream e;
  487. /* clang-format off */
  488. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
  489. << "The included script\n "
  490. << this->Makefile->GetExecutionFilePath() << "\n"
  491. << "affects policy settings, so it requires this policy to be set.";
  492. /* clang-format on */
  493. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  494. } break;
  495. case cmPolicies::OLD:
  496. case cmPolicies::NEW:
  497. // The script set this policy. We assume the purpose of the
  498. // script is to initialize policies for its includer, and since
  499. // the policy is now set for later scripts, we do not warn.
  500. break;
  501. }
  502. }
  503. bool cmMakefile::ReadDependentFile(const std::string& filename,
  504. bool noPolicyScope)
  505. {
  506. this->AddDefinition("CMAKE_PARENT_LIST_FILE",
  507. this->GetDefinition("CMAKE_CURRENT_LIST_FILE"));
  508. std::string filenametoread = cmSystemTools::CollapseFullPath(
  509. filename, this->GetCurrentSourceDirectory());
  510. IncludeScope incScope(this, filenametoread, noPolicyScope);
  511. cmListFile listFile;
  512. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  513. this->Backtrace)) {
  514. return false;
  515. }
  516. this->ReadListFile(listFile, filenametoread);
  517. if (cmSystemTools::GetFatalErrorOccured()) {
  518. incScope.Quiet();
  519. }
  520. return true;
  521. }
  522. class cmMakefile::ListFileScope
  523. {
  524. public:
  525. ListFileScope(cmMakefile* mf, std::string const& filenametoread)
  526. : Makefile(mf)
  527. , ReportError(true)
  528. {
  529. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(filenametoread);
  530. this->Makefile->StateSnapshot =
  531. this->Makefile->GetState()->CreateInlineListFileSnapshot(
  532. this->Makefile->StateSnapshot, filenametoread);
  533. assert(this->Makefile->StateSnapshot.IsValid());
  534. this->Makefile->PushFunctionBlockerBarrier();
  535. }
  536. ~ListFileScope()
  537. {
  538. this->Makefile->PopSnapshot(this->ReportError);
  539. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  540. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  541. }
  542. void Quiet() { this->ReportError = false; }
  543. ListFileScope(const ListFileScope&) = delete;
  544. ListFileScope& operator=(const ListFileScope&) = delete;
  545. private:
  546. cmMakefile* Makefile;
  547. bool ReportError;
  548. };
  549. bool cmMakefile::ReadListFile(const std::string& filename)
  550. {
  551. std::string filenametoread = cmSystemTools::CollapseFullPath(
  552. filename, this->GetCurrentSourceDirectory());
  553. ListFileScope scope(this, filenametoread);
  554. cmListFile listFile;
  555. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  556. this->Backtrace)) {
  557. return false;
  558. }
  559. this->ReadListFile(listFile, filenametoread);
  560. if (cmSystemTools::GetFatalErrorOccured()) {
  561. scope.Quiet();
  562. }
  563. return true;
  564. }
  565. void cmMakefile::ReadListFile(cmListFile const& listFile,
  566. std::string const& filenametoread)
  567. {
  568. // add this list file to the list of dependencies
  569. this->ListFiles.push_back(filenametoread);
  570. std::string currentParentFile =
  571. this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
  572. std::string currentFile = this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");
  573. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread.c_str());
  574. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  575. cmSystemTools::GetFilenamePath(filenametoread).c_str());
  576. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  577. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  578. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  579. // Run the parsed commands.
  580. const size_t numberFunctions = listFile.Functions.size();
  581. for (size_t i = 0; i < numberFunctions; ++i) {
  582. cmExecutionStatus status;
  583. this->ExecuteCommand(listFile.Functions[i], status);
  584. if (cmSystemTools::GetFatalErrorOccured()) {
  585. break;
  586. }
  587. if (status.GetReturnInvoked()) {
  588. // Exit early due to return command.
  589. break;
  590. }
  591. }
  592. this->CheckForUnusedVariables();
  593. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile.c_str());
  594. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile.c_str());
  595. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  596. cmSystemTools::GetFilenamePath(currentFile).c_str());
  597. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  598. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  599. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  600. }
  601. void cmMakefile::EnforceDirectoryLevelRules() const
  602. {
  603. // Diagnose a violation of CMP0000 if necessary.
  604. if (this->CheckCMP0000) {
  605. std::ostringstream msg;
  606. msg << "No cmake_minimum_required command is present. "
  607. << "A line of code such as\n"
  608. << " cmake_minimum_required(VERSION " << cmVersion::GetMajorVersion()
  609. << "." << cmVersion::GetMinorVersion() << ")\n"
  610. << "should be added at the top of the file. "
  611. << "The version specified may be lower if you wish to "
  612. << "support older CMake versions for this project. "
  613. << "For more information run "
  614. << "\"cmake --help-policy CMP0000\".";
  615. switch (this->GetPolicyStatus(cmPolicies::CMP0000)) {
  616. case cmPolicies::WARN:
  617. // Warn because the user did not provide a minimum required
  618. // version.
  619. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  620. msg.str(), this->Backtrace);
  621. case cmPolicies::OLD:
  622. // OLD behavior is to use policy version 2.4 set in
  623. // cmListFileCache.
  624. break;
  625. case cmPolicies::REQUIRED_IF_USED:
  626. case cmPolicies::REQUIRED_ALWAYS:
  627. case cmPolicies::NEW:
  628. // NEW behavior is to issue an error.
  629. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  630. msg.str(), this->Backtrace);
  631. cmSystemTools::SetFatalErrorOccured();
  632. return;
  633. }
  634. }
  635. }
  636. void cmMakefile::AddEvaluationFile(
  637. const std::string& inputFile,
  638. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  639. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  640. bool inputIsContent)
  641. {
  642. this->EvaluationFiles.push_back(new cmGeneratorExpressionEvaluationFile(
  643. inputFile, std::move(outputName), std::move(condition), inputIsContent,
  644. this->GetPolicyStatus(cmPolicies::CMP0070)));
  645. }
  646. std::vector<cmGeneratorExpressionEvaluationFile*>
  647. cmMakefile::GetEvaluationFiles() const
  648. {
  649. return this->EvaluationFiles;
  650. }
  651. std::vector<cmExportBuildFileGenerator*>
  652. cmMakefile::GetExportBuildFileGenerators() const
  653. {
  654. return this->ExportBuildFileGenerators;
  655. }
  656. void cmMakefile::RemoveExportBuildFileGeneratorCMP0024(
  657. cmExportBuildFileGenerator* gen)
  658. {
  659. std::vector<cmExportBuildFileGenerator*>::iterator it =
  660. std::find(this->ExportBuildFileGenerators.begin(),
  661. this->ExportBuildFileGenerators.end(), gen);
  662. if (it != this->ExportBuildFileGenerators.end()) {
  663. this->ExportBuildFileGenerators.erase(it);
  664. }
  665. }
  666. void cmMakefile::AddExportBuildFileGenerator(cmExportBuildFileGenerator* gen)
  667. {
  668. this->ExportBuildFileGenerators.push_back(gen);
  669. }
  670. namespace {
  671. struct file_not_persistent
  672. {
  673. bool operator()(const std::string& path) const
  674. {
  675. return !(path.find("CMakeTmp") == std::string::npos &&
  676. cmSystemTools::FileExists(path));
  677. }
  678. };
  679. }
  680. void cmMakefile::FinalPass()
  681. {
  682. // do all the variable expansions here
  683. this->ExpandVariablesCMP0019();
  684. // give all the commands a chance to do something
  685. // after the file has been parsed before generation
  686. for (cmCommand* fpCommand : this->FinalPassCommands) {
  687. fpCommand->FinalPass();
  688. }
  689. // go through all configured files and see which ones still exist.
  690. // we don't want cmake to re-run if a configured file is created and deleted
  691. // during processing as that would make it a transient file that can't
  692. // influence the build process
  693. cmEraseIf(this->OutputFiles, file_not_persistent());
  694. // if a configured file is used as input for another configured file,
  695. // and then deleted it will show up in the input list files so we
  696. // need to scan those too
  697. cmEraseIf(this->ListFiles, file_not_persistent());
  698. }
  699. // Generate the output file
  700. void cmMakefile::ConfigureFinalPass()
  701. {
  702. this->FinalPass();
  703. const char* oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
  704. if (oldValue &&
  705. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, oldValue, "2.4")) {
  706. this->GetCMakeInstance()->IssueMessage(
  707. MessageType::FATAL_ERROR,
  708. "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
  709. "than 2.4. This version of CMake only supports backwards compatibility "
  710. "with CMake 2.4 or later. For compatibility with older versions please "
  711. "use any CMake 2.8.x release or lower.",
  712. this->Backtrace);
  713. }
  714. }
  715. void cmMakefile::AddCustomCommandToTarget(
  716. const std::string& target, const std::vector<std::string>& byproducts,
  717. const std::vector<std::string>& depends,
  718. const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
  719. const char* comment, const char* workingDir, bool escapeOldStyle,
  720. bool uses_terminal, const std::string& depfile, bool command_expand_lists,
  721. ObjectLibraryCommands objLibraryCommands)
  722. {
  723. // Find the target to which to add the custom command.
  724. cmTargets::iterator ti = this->Targets.find(target);
  725. if (ti == this->Targets.end()) {
  726. MessageType messageType = MessageType::AUTHOR_WARNING;
  727. bool issueMessage = false;
  728. std::ostringstream e;
  729. switch (this->GetPolicyStatus(cmPolicies::CMP0040)) {
  730. case cmPolicies::WARN:
  731. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
  732. issueMessage = true;
  733. case cmPolicies::OLD:
  734. break;
  735. case cmPolicies::NEW:
  736. case cmPolicies::REQUIRED_IF_USED:
  737. case cmPolicies::REQUIRED_ALWAYS:
  738. issueMessage = true;
  739. messageType = MessageType::FATAL_ERROR;
  740. }
  741. if (issueMessage) {
  742. if (cmTarget const* t = this->FindTargetToUse(target)) {
  743. if (t->IsImported()) {
  744. e << "TARGET '" << target
  745. << "' is IMPORTED and does not build here.";
  746. } else {
  747. e << "TARGET '" << target << "' was not created in this directory.";
  748. }
  749. } else {
  750. e << "No TARGET '" << target
  751. << "' has been created in this directory.";
  752. }
  753. IssueMessage(messageType, e.str());
  754. }
  755. return;
  756. }
  757. cmTarget& t = ti->second;
  758. if (objLibraryCommands == RejectObjectLibraryCommands &&
  759. t.GetType() == cmStateEnums::OBJECT_LIBRARY) {
  760. std::ostringstream e;
  761. e << "Target \"" << target
  762. << "\" is an OBJECT library "
  763. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  764. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  765. return;
  766. }
  767. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  768. std::ostringstream e;
  769. e << "Target \"" << target
  770. << "\" is an INTERFACE library "
  771. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  772. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  773. return;
  774. }
  775. // Always create the byproduct sources and mark them generated.
  776. for (std::string const& o : byproducts) {
  777. if (cmSourceFile* out = this->GetOrCreateSource(o, true)) {
  778. out->SetProperty("GENERATED", "1");
  779. }
  780. }
  781. // Add the command to the appropriate build step for the target.
  782. std::vector<std::string> no_output;
  783. cmCustomCommand cc(this, no_output, byproducts, depends, commandLines,
  784. comment, workingDir);
  785. cc.SetEscapeOldStyle(escapeOldStyle);
  786. cc.SetEscapeAllowMakeVars(true);
  787. cc.SetUsesTerminal(uses_terminal);
  788. cc.SetCommandExpandLists(command_expand_lists);
  789. cc.SetDepfile(depfile);
  790. switch (type) {
  791. case cmTarget::PRE_BUILD:
  792. t.AddPreBuildCommand(cc);
  793. break;
  794. case cmTarget::PRE_LINK:
  795. t.AddPreLinkCommand(cc);
  796. break;
  797. case cmTarget::POST_BUILD:
  798. t.AddPostBuildCommand(cc);
  799. break;
  800. }
  801. }
  802. cmSourceFile* cmMakefile::AddCustomCommandToOutput(
  803. const std::vector<std::string>& outputs,
  804. const std::vector<std::string>& byproducts,
  805. const std::vector<std::string>& depends, const std::string& main_dependency,
  806. const cmCustomCommandLines& commandLines, const char* comment,
  807. const char* workingDir, bool replace, bool escapeOldStyle,
  808. bool uses_terminal, bool command_expand_lists, const std::string& depfile)
  809. {
  810. // Make sure there is at least one output.
  811. if (outputs.empty()) {
  812. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  813. return nullptr;
  814. }
  815. // Validate custom commands. TODO: More strict?
  816. for (cmCustomCommandLine const& cl : commandLines) {
  817. if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') {
  818. std::ostringstream e;
  819. e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
  820. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  821. return nullptr;
  822. }
  823. }
  824. // Choose a source file on which to store the custom command.
  825. cmSourceFile* file = nullptr;
  826. if (!commandLines.empty() && !main_dependency.empty()) {
  827. // The main dependency was specified. Use it unless a different
  828. // custom command already used it.
  829. file = this->GetSource(main_dependency);
  830. if (file && file->GetCustomCommand() && !replace) {
  831. // The main dependency already has a custom command.
  832. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  833. // The existing custom command is identical. Silently ignore
  834. // the duplicate.
  835. return file;
  836. }
  837. // The existing custom command is different. We need to
  838. // generate a rule file for this new command.
  839. file = nullptr;
  840. } else if (!file) {
  841. file = this->CreateSource(main_dependency);
  842. }
  843. }
  844. // Generate a rule file if the main dependency is not available.
  845. if (!file) {
  846. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  847. // Construct a rule file associated with the first output produced.
  848. std::string outName = gg->GenerateRuleFile(outputs[0]);
  849. // Check if the rule file already exists.
  850. file = this->GetSource(outName, cmSourceFileLocationKind::Known);
  851. if (file && file->GetCustomCommand() && !replace) {
  852. // The rule file already exists.
  853. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  854. cmSystemTools::Error("Attempt to add a custom rule to output \"",
  855. outName.c_str(),
  856. "\" which already has a custom rule.");
  857. }
  858. return file;
  859. }
  860. // Create a cmSourceFile for the rule file.
  861. if (!file) {
  862. file =
  863. this->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  864. }
  865. file->SetProperty("__CMAKE_RULE", "1");
  866. }
  867. // Always create the output sources and mark them generated.
  868. for (std::string const& o : outputs) {
  869. if (cmSourceFile* out =
  870. this->GetOrCreateSource(o, true, cmSourceFileLocationKind::Known)) {
  871. out->SetProperty("GENERATED", "1");
  872. }
  873. }
  874. for (std::string const& o : byproducts) {
  875. if (cmSourceFile* out =
  876. this->GetOrCreateSource(o, true, cmSourceFileLocationKind::Known)) {
  877. out->SetProperty("GENERATED", "1");
  878. }
  879. }
  880. // Attach the custom command to the file.
  881. if (file) {
  882. // Construct a complete list of dependencies.
  883. std::vector<std::string> depends2(depends);
  884. if (!main_dependency.empty()) {
  885. depends2.push_back(main_dependency);
  886. }
  887. cmCustomCommand* cc = new cmCustomCommand(
  888. this, outputs, byproducts, depends2, commandLines, comment, workingDir);
  889. cc->SetEscapeOldStyle(escapeOldStyle);
  890. cc->SetEscapeAllowMakeVars(true);
  891. cc->SetUsesTerminal(uses_terminal);
  892. cc->SetCommandExpandLists(command_expand_lists);
  893. cc->SetDepfile(depfile);
  894. file->SetCustomCommand(cc);
  895. this->UpdateOutputToSourceMap(outputs, file);
  896. }
  897. return file;
  898. }
  899. void cmMakefile::UpdateOutputToSourceMap(
  900. std::vector<std::string> const& outputs, cmSourceFile* source)
  901. {
  902. for (std::string const& o : outputs) {
  903. this->UpdateOutputToSourceMap(o, source);
  904. }
  905. }
  906. void cmMakefile::UpdateOutputToSourceMap(std::string const& output,
  907. cmSourceFile* source)
  908. {
  909. OutputToSourceMap::iterator i = this->OutputToSource.find(output);
  910. if (i != this->OutputToSource.end()) {
  911. // Multiple custom commands produce the same output but may
  912. // be attached to a different source file (MAIN_DEPENDENCY).
  913. // LinearGetSourceFileWithOutput would return the first one,
  914. // so keep the mapping for the first one.
  915. //
  916. // TODO: Warn the user about this case. However, the VS 8 generator
  917. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  918. // individual targets.
  919. return;
  920. }
  921. this->OutputToSource[output] = source;
  922. }
  923. cmSourceFile* cmMakefile::AddCustomCommandToOutput(
  924. const std::string& output, const std::vector<std::string>& depends,
  925. const std::string& main_dependency, const cmCustomCommandLines& commandLines,
  926. const char* comment, const char* workingDir, bool replace,
  927. bool escapeOldStyle, bool uses_terminal, bool command_expand_lists,
  928. const std::string& depfile)
  929. {
  930. std::vector<std::string> outputs;
  931. outputs.push_back(output);
  932. std::vector<std::string> no_byproducts;
  933. return this->AddCustomCommandToOutput(
  934. outputs, no_byproducts, depends, main_dependency, commandLines, comment,
  935. workingDir, replace, escapeOldStyle, uses_terminal, command_expand_lists,
  936. depfile);
  937. }
  938. void cmMakefile::AddCustomCommandOldStyle(
  939. const std::string& target, const std::vector<std::string>& outputs,
  940. const std::vector<std::string>& depends, const std::string& source,
  941. const cmCustomCommandLines& commandLines, const char* comment)
  942. {
  943. // Translate the old-style signature to one of the new-style
  944. // signatures.
  945. if (source == target) {
  946. // In the old-style signature if the source and target were the
  947. // same then it added a post-build rule to the target. Preserve
  948. // this behavior.
  949. std::vector<std::string> no_byproducts;
  950. this->AddCustomCommandToTarget(target, no_byproducts, depends,
  951. commandLines, cmTarget::POST_BUILD, comment,
  952. nullptr);
  953. return;
  954. }
  955. // Each output must get its own copy of this rule.
  956. cmsys::RegularExpression sourceFiles("\\.(C|M|c|c\\+\\+|cc|cpp|cxx|cu|m|mm|"
  957. "rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
  958. "hm|hpp|hxx|in|txx|inl)$");
  959. for (std::string const& oi : outputs) {
  960. // Get the name of this output.
  961. const char* output = oi.c_str();
  962. cmSourceFile* sf;
  963. // Choose whether to use a main dependency.
  964. if (sourceFiles.find(source)) {
  965. // The source looks like a real file. Use it as the main dependency.
  966. sf = this->AddCustomCommandToOutput(output, depends, source,
  967. commandLines, comment, nullptr);
  968. } else {
  969. // The source may not be a real file. Do not use a main dependency.
  970. std::string no_main_dependency;
  971. std::vector<std::string> depends2 = depends;
  972. depends2.push_back(source);
  973. sf = this->AddCustomCommandToOutput(output, depends2, no_main_dependency,
  974. commandLines, comment, nullptr);
  975. }
  976. // If the rule was added to the source (and not a .rule file),
  977. // then add the source to the target to make sure the rule is
  978. // included.
  979. if (sf && !sf->GetPropertyAsBool("__CMAKE_RULE")) {
  980. cmTargets::iterator ti = this->Targets.find(target);
  981. if (ti != this->Targets.end()) {
  982. ti->second.AddSource(sf->GetFullPath());
  983. } else {
  984. cmSystemTools::Error("Attempt to add a custom rule to a target "
  985. "that does not exist yet for target ",
  986. target.c_str());
  987. return;
  988. }
  989. }
  990. }
  991. }
  992. cmTarget* cmMakefile::AddUtilityCommand(
  993. const std::string& utilityName, TargetOrigin origin, bool excludeFromAll,
  994. const std::vector<std::string>& depends, const char* workingDirectory,
  995. const char* command, const char* arg1, const char* arg2, const char* arg3,
  996. const char* arg4)
  997. {
  998. // Construct the command line for the custom command.
  999. cmCustomCommandLine commandLine;
  1000. commandLine.push_back(command);
  1001. if (arg1) {
  1002. commandLine.push_back(arg1);
  1003. }
  1004. if (arg2) {
  1005. commandLine.push_back(arg2);
  1006. }
  1007. if (arg3) {
  1008. commandLine.push_back(arg3);
  1009. }
  1010. if (arg4) {
  1011. commandLine.push_back(arg4);
  1012. }
  1013. cmCustomCommandLines commandLines;
  1014. commandLines.push_back(std::move(commandLine));
  1015. // Call the real signature of this method.
  1016. return this->AddUtilityCommand(utilityName, origin, excludeFromAll,
  1017. workingDirectory, depends, commandLines);
  1018. }
  1019. cmTarget* cmMakefile::AddUtilityCommand(
  1020. const std::string& utilityName, TargetOrigin origin, bool excludeFromAll,
  1021. const char* workingDirectory, const std::vector<std::string>& depends,
  1022. const cmCustomCommandLines& commandLines, bool escapeOldStyle,
  1023. const char* comment, bool uses_terminal, bool command_expand_lists)
  1024. {
  1025. std::vector<std::string> no_byproducts;
  1026. return this->AddUtilityCommand(utilityName, origin, excludeFromAll,
  1027. workingDirectory, no_byproducts, depends,
  1028. commandLines, escapeOldStyle, comment,
  1029. uses_terminal, command_expand_lists);
  1030. }
  1031. cmTarget* cmMakefile::AddUtilityCommand(
  1032. const std::string& utilityName, TargetOrigin origin, bool excludeFromAll,
  1033. const char* workingDirectory, const std::vector<std::string>& byproducts,
  1034. const std::vector<std::string>& depends,
  1035. const cmCustomCommandLines& commandLines, bool escapeOldStyle,
  1036. const char* comment, bool uses_terminal, bool command_expand_lists)
  1037. {
  1038. // Create a target instance for this utility.
  1039. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1040. target->SetIsGeneratorProvided(origin == TargetOrigin::Generator);
  1041. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1042. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1043. }
  1044. if (!comment) {
  1045. // Use an empty comment to avoid generation of default comment.
  1046. comment = "";
  1047. }
  1048. // Store the custom command in the target.
  1049. if (!commandLines.empty() || !depends.empty()) {
  1050. std::string force = this->GetCurrentBinaryDirectory();
  1051. force += "/CMakeFiles";
  1052. force += "/";
  1053. force += utilityName;
  1054. std::vector<std::string> forced;
  1055. forced.push_back(force);
  1056. std::string no_main_dependency;
  1057. bool no_replace = false;
  1058. this->AddCustomCommandToOutput(
  1059. forced, byproducts, depends, no_main_dependency, commandLines, comment,
  1060. workingDirectory, no_replace, escapeOldStyle, uses_terminal,
  1061. command_expand_lists);
  1062. cmSourceFile* sf = target->AddSourceCMP0049(force);
  1063. // The output is not actually created so mark it symbolic.
  1064. if (sf) {
  1065. sf->SetProperty("SYMBOLIC", "1");
  1066. } else {
  1067. cmSystemTools::Error("Could not get source file entry for ",
  1068. force.c_str());
  1069. }
  1070. // Always create the byproduct sources and mark them generated.
  1071. for (std::string const& byproduct : byproducts) {
  1072. if (cmSourceFile* out = this->GetOrCreateSource(
  1073. byproduct, true, cmSourceFileLocationKind::Known)) {
  1074. out->SetProperty("GENERATED", "1");
  1075. }
  1076. }
  1077. }
  1078. return target;
  1079. }
  1080. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1081. {
  1082. // remove any \n\r
  1083. std::string::size_type initSize = dflags.size();
  1084. dflags += ' ';
  1085. dflags += flag;
  1086. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1087. std::replace(flagStart, dflags.end(), '\n', ' ');
  1088. std::replace(flagStart, dflags.end(), '\r', ' ');
  1089. }
  1090. void cmMakefile::AddDefineFlag(std::string const& flag)
  1091. {
  1092. if (flag.empty()) {
  1093. return;
  1094. }
  1095. // Update the string used for the old DEFINITIONS property.
  1096. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1097. // If this is really a definition, update COMPILE_DEFINITIONS.
  1098. if (this->ParseDefineFlag(flag, false)) {
  1099. return;
  1100. }
  1101. // Add this flag that does not look like a definition.
  1102. s_AddDefineFlag(flag, this->DefineFlags);
  1103. }
  1104. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1105. {
  1106. std::string::size_type const len = flag.length();
  1107. // Remove all instances of the flag that are surrounded by
  1108. // whitespace or the beginning/end of the string.
  1109. for (std::string::size_type lpos = dflags.find(flag, 0);
  1110. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1111. std::string::size_type rpos = lpos + len;
  1112. if ((lpos <= 0 || isspace(dflags[lpos - 1])) &&
  1113. (rpos >= dflags.size() || isspace(dflags[rpos]))) {
  1114. dflags.erase(lpos, len);
  1115. } else {
  1116. ++lpos;
  1117. }
  1118. }
  1119. }
  1120. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1121. {
  1122. // Check the length of the flag to remove.
  1123. if (flag.empty()) {
  1124. return;
  1125. }
  1126. // Update the string used for the old DEFINITIONS property.
  1127. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1128. // If this is really a definition, update COMPILE_DEFINITIONS.
  1129. if (this->ParseDefineFlag(flag, true)) {
  1130. return;
  1131. }
  1132. // Remove this flag that does not look like a definition.
  1133. s_RemoveDefineFlag(flag, this->DefineFlags);
  1134. }
  1135. void cmMakefile::AddCompileDefinition(std::string const& option)
  1136. {
  1137. this->AppendProperty("COMPILE_DEFINITIONS", option.c_str());
  1138. }
  1139. void cmMakefile::AddCompileOption(std::string const& option)
  1140. {
  1141. this->AppendProperty("COMPILE_OPTIONS", option.c_str());
  1142. }
  1143. void cmMakefile::AddLinkOption(std::string const& option)
  1144. {
  1145. this->AppendProperty("LINK_OPTIONS", option.c_str());
  1146. }
  1147. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1148. {
  1149. cmListFileBacktrace lfbt = this->GetBacktrace();
  1150. if (before) {
  1151. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(directory,
  1152. lfbt);
  1153. } else {
  1154. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(directory,
  1155. lfbt);
  1156. }
  1157. }
  1158. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1159. {
  1160. // Create a regular expression to match valid definitions.
  1161. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1162. // Make sure the definition matches.
  1163. if (!valid.find(def)) {
  1164. return false;
  1165. }
  1166. // Definitions with non-trivial values require a policy check.
  1167. static cmsys::RegularExpression trivial(
  1168. "^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
  1169. if (!trivial.find(def)) {
  1170. // This definition has a non-trivial value.
  1171. switch (this->GetPolicyStatus(cmPolicies::CMP0005)) {
  1172. case cmPolicies::WARN:
  1173. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1174. cmPolicies::GetPolicyWarning(cmPolicies::CMP0005));
  1175. CM_FALLTHROUGH;
  1176. case cmPolicies::OLD:
  1177. // OLD behavior is to not escape the value. We should not
  1178. // convert the definition to use the property.
  1179. return false;
  1180. case cmPolicies::REQUIRED_IF_USED:
  1181. case cmPolicies::REQUIRED_ALWAYS:
  1182. this->IssueMessage(
  1183. MessageType::FATAL_ERROR,
  1184. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005));
  1185. return false;
  1186. case cmPolicies::NEW:
  1187. // NEW behavior is to escape the value. Proceed to convert it
  1188. // to an entry in the property.
  1189. break;
  1190. }
  1191. }
  1192. // Get the definition part after the flag.
  1193. const char* define = def.c_str() + 2;
  1194. if (remove) {
  1195. if (const char* cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1196. // Expand the list.
  1197. std::vector<std::string> defs;
  1198. cmSystemTools::ExpandListArgument(cdefs, defs);
  1199. // Recompose the list without the definition.
  1200. std::vector<std::string>::const_iterator defEnd =
  1201. std::remove(defs.begin(), defs.end(), define);
  1202. std::vector<std::string>::const_iterator defBegin = defs.begin();
  1203. std::string ndefs = cmJoin(cmMakeRange(defBegin, defEnd), ";");
  1204. // Store the new list.
  1205. this->SetProperty("COMPILE_DEFINITIONS", ndefs.c_str());
  1206. }
  1207. } else {
  1208. // Append the definition to the directory property.
  1209. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1210. }
  1211. return true;
  1212. }
  1213. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1214. {
  1215. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1216. // define flags
  1217. this->DefineFlags = parent->DefineFlags;
  1218. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1219. // Include transform property. There is no per-config version.
  1220. {
  1221. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1222. this->SetProperty(prop, parent->GetProperty(prop));
  1223. }
  1224. // compile definitions property and per-config versions
  1225. cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
  1226. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1227. this->SetProperty("COMPILE_DEFINITIONS",
  1228. parent->GetProperty("COMPILE_DEFINITIONS"));
  1229. std::vector<std::string> configs;
  1230. this->GetConfigurations(configs);
  1231. for (std::string const& config : configs) {
  1232. std::string defPropName = "COMPILE_DEFINITIONS_";
  1233. defPropName += cmSystemTools::UpperCase(config);
  1234. const char* prop = parent->GetProperty(defPropName);
  1235. this->SetProperty(defPropName, prop);
  1236. }
  1237. }
  1238. // labels
  1239. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1240. // link libraries
  1241. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1242. // the initial project name
  1243. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1244. // Copy include regular expressions.
  1245. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1246. // Imported targets.
  1247. this->ImportedTargets = parent->ImportedTargets;
  1248. // Recursion depth.
  1249. this->RecursionDepth = parent->RecursionDepth;
  1250. }
  1251. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1252. const cmPolicies::PolicyMap& pm)
  1253. {
  1254. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1255. this->StateSnapshot, fileName);
  1256. assert(this->StateSnapshot.IsValid());
  1257. this->PushLoopBlockBarrier();
  1258. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1259. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1260. #endif
  1261. this->PushFunctionBlockerBarrier();
  1262. this->PushPolicy(true, pm);
  1263. }
  1264. void cmMakefile::PopFunctionScope(bool reportError)
  1265. {
  1266. this->PopPolicy();
  1267. this->PopSnapshot(reportError);
  1268. this->PopFunctionBlockerBarrier(reportError);
  1269. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1270. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1271. #endif
  1272. this->PopLoopBlockBarrier();
  1273. this->CheckForUnusedVariables();
  1274. }
  1275. void cmMakefile::PushMacroScope(std::string const& fileName,
  1276. const cmPolicies::PolicyMap& pm)
  1277. {
  1278. this->StateSnapshot =
  1279. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1280. assert(this->StateSnapshot.IsValid());
  1281. this->PushFunctionBlockerBarrier();
  1282. this->PushPolicy(true, pm);
  1283. }
  1284. void cmMakefile::PopMacroScope(bool reportError)
  1285. {
  1286. this->PopPolicy();
  1287. this->PopSnapshot(reportError);
  1288. this->PopFunctionBlockerBarrier(reportError);
  1289. }
  1290. bool cmMakefile::IsRootMakefile() const
  1291. {
  1292. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1293. }
  1294. class cmMakefile::BuildsystemFileScope
  1295. {
  1296. public:
  1297. BuildsystemFileScope(cmMakefile* mf)
  1298. : Makefile(mf)
  1299. , ReportError(true)
  1300. {
  1301. std::string currentStart =
  1302. this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource();
  1303. currentStart += "/CMakeLists.txt";
  1304. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1305. this->Makefile->StateSnapshot =
  1306. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1307. this->Makefile->StateSnapshot);
  1308. this->Makefile->PushFunctionBlockerBarrier();
  1309. this->GG = mf->GetGlobalGenerator();
  1310. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1311. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1312. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1313. this->GG->SetCurrentMakefile(mf);
  1314. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1315. this->GG->GetFileLockPool().PushFileScope();
  1316. #endif
  1317. }
  1318. ~BuildsystemFileScope()
  1319. {
  1320. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1321. this->Makefile->PopSnapshot(this->ReportError);
  1322. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1323. this->GG->GetFileLockPool().PopFileScope();
  1324. #endif
  1325. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1326. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1327. }
  1328. void Quiet() { this->ReportError = false; }
  1329. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1330. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1331. private:
  1332. cmMakefile* Makefile;
  1333. cmGlobalGenerator* GG;
  1334. cmMakefile* CurrentMakefile;
  1335. cmStateSnapshot Snapshot;
  1336. bool ReportError;
  1337. };
  1338. void cmMakefile::Configure()
  1339. {
  1340. std::string currentStart =
  1341. this->StateSnapshot.GetDirectory().GetCurrentSource();
  1342. currentStart += "/CMakeLists.txt";
  1343. // Add the bottom of all backtraces within this directory.
  1344. // We will never pop this scope because it should be available
  1345. // for messages during the generate step too.
  1346. this->Backtrace = this->Backtrace.Push(currentStart);
  1347. BuildsystemFileScope scope(this);
  1348. // make sure the CMakeFiles dir is there
  1349. std::string filesDir = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1350. filesDir += "/CMakeFiles";
  1351. cmSystemTools::MakeDirectory(filesDir);
  1352. assert(cmSystemTools::FileExists(currentStart, true));
  1353. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart.c_str());
  1354. cmListFile listFile;
  1355. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1356. this->Backtrace)) {
  1357. return;
  1358. }
  1359. if (this->IsRootMakefile()) {
  1360. bool hasVersion = false;
  1361. // search for the right policy command
  1362. for (cmListFileFunction const& func : listFile.Functions) {
  1363. if (func.Name.Lower == "cmake_minimum_required") {
  1364. hasVersion = true;
  1365. break;
  1366. }
  1367. }
  1368. // if no policy command is found this is an error if they use any
  1369. // non advanced functions or a lot of functions
  1370. if (!hasVersion) {
  1371. bool isProblem = true;
  1372. if (listFile.Functions.size() < 30) {
  1373. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1374. // these commands must have backwards compatibility forever and
  1375. // and that is a lot longer than your tiny mind can comprehend mortal
  1376. std::set<std::string> allowedCommands;
  1377. allowedCommands.insert("project");
  1378. allowedCommands.insert("set");
  1379. allowedCommands.insert("if");
  1380. allowedCommands.insert("endif");
  1381. allowedCommands.insert("else");
  1382. allowedCommands.insert("elseif");
  1383. allowedCommands.insert("add_executable");
  1384. allowedCommands.insert("add_library");
  1385. allowedCommands.insert("target_link_libraries");
  1386. allowedCommands.insert("option");
  1387. allowedCommands.insert("message");
  1388. isProblem = false;
  1389. for (cmListFileFunction const& func : listFile.Functions) {
  1390. if (allowedCommands.find(func.Name.Lower) == allowedCommands.end()) {
  1391. isProblem = true;
  1392. break;
  1393. }
  1394. }
  1395. }
  1396. if (isProblem) {
  1397. // Tell the top level cmMakefile to diagnose
  1398. // this violation of CMP0000.
  1399. this->SetCheckCMP0000(true);
  1400. // Implicitly set the version for the user.
  1401. this->SetPolicyVersion("2.4", std::string());
  1402. }
  1403. }
  1404. bool hasProject = false;
  1405. // search for a project command
  1406. for (cmListFileFunction const& func : listFile.Functions) {
  1407. if (func.Name.Lower == "project") {
  1408. hasProject = true;
  1409. break;
  1410. }
  1411. }
  1412. // if no project command is found, add one
  1413. if (!hasProject) {
  1414. cmListFileFunction project;
  1415. project.Name.Lower = "project";
  1416. project.Arguments.emplace_back("Project", cmListFileArgument::Unquoted,
  1417. 0);
  1418. project.Arguments.emplace_back("__CMAKE_INJECTED_PROJECT_COMMAND__",
  1419. cmListFileArgument::Unquoted, 0);
  1420. listFile.Functions.insert(listFile.Functions.begin(), project);
  1421. }
  1422. }
  1423. this->ReadListFile(listFile, currentStart);
  1424. if (cmSystemTools::GetFatalErrorOccured()) {
  1425. scope.Quiet();
  1426. }
  1427. // at the end handle any old style subdirs
  1428. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1429. // for each subdir recurse
  1430. std::vector<cmMakefile*>::iterator sdi = subdirs.begin();
  1431. for (; sdi != subdirs.end(); ++sdi) {
  1432. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1433. this->ConfigureSubDirectory(*sdi);
  1434. }
  1435. this->AddCMakeDependFilesFromUser();
  1436. }
  1437. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1438. {
  1439. mf->InitializeFromParent(this);
  1440. std::string currentStart = mf->GetCurrentSourceDirectory();
  1441. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1442. std::string msg = " Entering ";
  1443. msg += currentStart;
  1444. cmSystemTools::Message(msg);
  1445. }
  1446. std::string const currentStartFile = currentStart + "/CMakeLists.txt";
  1447. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1448. // The file is missing. Check policy CMP0014.
  1449. std::ostringstream e;
  1450. /* clang-format off */
  1451. e << "The source directory\n"
  1452. << " " << currentStart << "\n"
  1453. << "does not contain a CMakeLists.txt file.";
  1454. /* clang-format on */
  1455. switch (this->GetPolicyStatus(cmPolicies::CMP0014)) {
  1456. case cmPolicies::WARN:
  1457. // Print the warning.
  1458. /* clang-format off */
  1459. e << "\n"
  1460. << "CMake does not support this case but it used "
  1461. << "to work accidentally and is being allowed for "
  1462. << "compatibility."
  1463. << "\n"
  1464. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
  1465. /* clang-format on */
  1466. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1467. case cmPolicies::OLD:
  1468. // OLD behavior does not warn.
  1469. break;
  1470. case cmPolicies::REQUIRED_IF_USED:
  1471. case cmPolicies::REQUIRED_ALWAYS:
  1472. e << "\n" << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
  1473. CM_FALLTHROUGH;
  1474. case cmPolicies::NEW:
  1475. // NEW behavior prints the error.
  1476. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1477. }
  1478. return;
  1479. }
  1480. // finally configure the subdir
  1481. mf->Configure();
  1482. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1483. std::string msg = " Returning to ";
  1484. msg += this->GetCurrentSourceDirectory();
  1485. cmSystemTools::Message(msg);
  1486. }
  1487. }
  1488. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1489. const std::string& binPath,
  1490. bool excludeFromAll, bool immediate)
  1491. {
  1492. // Make sure the binary directory is unique.
  1493. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1494. return;
  1495. }
  1496. cmStateSnapshot newSnapshot =
  1497. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1498. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1499. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1500. cmSystemTools::MakeDirectory(binPath);
  1501. cmMakefile* subMf = new cmMakefile(this->GlobalGenerator, newSnapshot);
  1502. this->GetGlobalGenerator()->AddMakefile(subMf);
  1503. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1504. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1505. }
  1506. if (immediate) {
  1507. this->ConfigureSubDirectory(subMf);
  1508. } else {
  1509. this->UnConfiguredDirectories.push_back(subMf);
  1510. }
  1511. this->AddInstallGenerator(new cmInstallSubdirectoryGenerator(
  1512. subMf, binPath.c_str(), excludeFromAll));
  1513. }
  1514. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1515. {
  1516. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1517. }
  1518. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1519. {
  1520. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1521. }
  1522. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1523. {
  1524. std::vector<cmTarget*> tgts;
  1525. tgts.reserve(this->ImportedTargets.size());
  1526. for (auto const& impTarget : this->ImportedTargets) {
  1527. tgts.push_back(impTarget.second);
  1528. }
  1529. return tgts;
  1530. }
  1531. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1532. bool before)
  1533. {
  1534. if (incs.empty()) {
  1535. return;
  1536. }
  1537. cmListFileBacktrace lfbt = this->GetBacktrace();
  1538. std::string entryString = cmJoin(incs, ";");
  1539. if (before) {
  1540. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1541. entryString, lfbt);
  1542. } else {
  1543. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1544. entryString, lfbt);
  1545. }
  1546. // Property on each target:
  1547. for (auto& target : this->Targets) {
  1548. cmTarget& t = target.second;
  1549. t.InsertInclude(entryString, lfbt, before);
  1550. }
  1551. }
  1552. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1553. {
  1554. if (incs.empty()) {
  1555. return;
  1556. }
  1557. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1558. for (auto& target : this->Targets) {
  1559. cmTarget& t = target.second;
  1560. t.AddSystemIncludeDirectories(incs);
  1561. }
  1562. }
  1563. void cmMakefile::AddDefinition(const std::string& name, const char* value)
  1564. {
  1565. if (!value) {
  1566. return;
  1567. }
  1568. if (this->VariableInitialized(name)) {
  1569. this->LogUnused("changing definition", name);
  1570. }
  1571. this->StateSnapshot.SetDefinition(name, value);
  1572. #ifdef CMAKE_BUILD_WITH_CMAKE
  1573. cmVariableWatch* vv = this->GetVariableWatch();
  1574. if (vv) {
  1575. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1576. value, this);
  1577. }
  1578. #endif
  1579. }
  1580. void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
  1581. const char* doc,
  1582. cmStateEnums::CacheEntryType type,
  1583. bool force)
  1584. {
  1585. const std::string* existingValue =
  1586. this->GetState()->GetInitializedCacheValue(name);
  1587. // must be outside the following if() to keep it alive long enough
  1588. std::string nvalue;
  1589. if (existingValue &&
  1590. (this->GetState()->GetCacheEntryType(name) ==
  1591. cmStateEnums::UNINITIALIZED)) {
  1592. // if this is not a force, then use the value from the cache
  1593. // if it is a force, then use the value being passed in
  1594. if (!force) {
  1595. value = existingValue->c_str();
  1596. }
  1597. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1598. std::vector<std::string>::size_type cc;
  1599. std::vector<std::string> files;
  1600. nvalue = value ? value : "";
  1601. cmSystemTools::ExpandListArgument(nvalue, files);
  1602. nvalue.clear();
  1603. for (cc = 0; cc < files.size(); cc++) {
  1604. if (!cmSystemTools::IsOff(files[cc])) {
  1605. files[cc] = cmSystemTools::CollapseFullPath(files[cc]);
  1606. }
  1607. if (cc > 0) {
  1608. nvalue += ";";
  1609. }
  1610. nvalue += files[cc];
  1611. }
  1612. this->GetCMakeInstance()->AddCacheEntry(name, nvalue.c_str(), doc, type);
  1613. nvalue = *this->GetState()->GetInitializedCacheValue(name);
  1614. value = nvalue.c_str();
  1615. }
  1616. }
  1617. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1618. // if there was a definition then remove it
  1619. this->StateSnapshot.RemoveDefinition(name);
  1620. }
  1621. void cmMakefile::AddDefinition(const std::string& name, bool value)
  1622. {
  1623. if (this->VariableInitialized(name)) {
  1624. this->LogUnused("changing definition", name);
  1625. }
  1626. this->StateSnapshot.SetDefinition(name, value ? "ON" : "OFF");
  1627. #ifdef CMAKE_BUILD_WITH_CMAKE
  1628. cmVariableWatch* vv = this->GetVariableWatch();
  1629. if (vv) {
  1630. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1631. value ? "ON" : "OFF", this);
  1632. }
  1633. #endif
  1634. }
  1635. void cmMakefile::CheckForUnusedVariables() const
  1636. {
  1637. if (!this->WarnUnused) {
  1638. return;
  1639. }
  1640. for (const std::string& key : this->StateSnapshot.UnusedKeys()) {
  1641. this->LogUnused("out of scope", key);
  1642. }
  1643. }
  1644. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1645. {
  1646. this->StateSnapshot.GetDefinition(var);
  1647. }
  1648. bool cmMakefile::VariableInitialized(const std::string& var) const
  1649. {
  1650. return this->StateSnapshot.IsInitialized(var);
  1651. }
  1652. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1653. const char* sourceFilename) const
  1654. {
  1655. // check to see if we need to print a warning
  1656. // if strict mode is on and the variable has
  1657. // not been "cleared"/initialized with a set(foo ) call
  1658. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1659. !this->VariableInitialized(variable)) {
  1660. if (this->CheckSystemVars ||
  1661. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1662. std::ostringstream msg;
  1663. msg << "uninitialized variable \'" << variable << "\'";
  1664. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1665. }
  1666. }
  1667. }
  1668. void cmMakefile::LogUnused(const char* reason, const std::string& name) const
  1669. {
  1670. if (this->WarnUnused) {
  1671. std::string path;
  1672. if (!this->ExecutionStatusStack.empty()) {
  1673. path = this->GetExecutionContext().FilePath;
  1674. } else {
  1675. path = this->GetCurrentSourceDirectory();
  1676. path += "/CMakeLists.txt";
  1677. }
  1678. if (this->CheckSystemVars || this->IsProjectFile(path.c_str())) {
  1679. std::ostringstream msg;
  1680. msg << "unused variable (" << reason << ") \'" << name << "\'";
  1681. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1682. }
  1683. }
  1684. }
  1685. void cmMakefile::RemoveDefinition(const std::string& name)
  1686. {
  1687. if (this->VariableInitialized(name)) {
  1688. this->LogUnused("unsetting", name);
  1689. }
  1690. this->StateSnapshot.RemoveDefinition(name);
  1691. #ifdef CMAKE_BUILD_WITH_CMAKE
  1692. cmVariableWatch* vv = this->GetVariableWatch();
  1693. if (vv) {
  1694. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1695. nullptr, this);
  1696. }
  1697. #endif
  1698. }
  1699. void cmMakefile::RemoveCacheDefinition(const std::string& name)
  1700. {
  1701. this->GetState()->RemoveCacheEntry(name);
  1702. }
  1703. void cmMakefile::SetProjectName(std::string const& p)
  1704. {
  1705. this->StateSnapshot.SetProjectName(p);
  1706. }
  1707. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1708. {
  1709. // for these targets do not add anything
  1710. switch (target.GetType()) {
  1711. case cmStateEnums::UTILITY:
  1712. case cmStateEnums::GLOBAL_TARGET:
  1713. case cmStateEnums::INTERFACE_LIBRARY:
  1714. return;
  1715. default:;
  1716. }
  1717. if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1718. std::vector<std::string> linkLibs;
  1719. cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs);
  1720. for (std::vector<std::string>::iterator j = linkLibs.begin();
  1721. j != linkLibs.end(); ++j) {
  1722. std::string libraryName = *j;
  1723. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1724. if (libraryName == "optimized") {
  1725. libType = OPTIMIZED_LibraryType;
  1726. ++j;
  1727. libraryName = *j;
  1728. } else if (libraryName == "debug") {
  1729. libType = DEBUG_LibraryType;
  1730. ++j;
  1731. libraryName = *j;
  1732. }
  1733. // This is equivalent to the target_link_libraries plain signature.
  1734. target.AddLinkLibrary(*this, libraryName, libType);
  1735. target.AppendProperty(
  1736. "INTERFACE_LINK_LIBRARIES",
  1737. target.GetDebugGeneratorExpressions(libraryName, libType).c_str());
  1738. }
  1739. }
  1740. }
  1741. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName)
  1742. {
  1743. this->AliasTargets[lname] = tgtName;
  1744. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1745. }
  1746. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1747. cmStateEnums::TargetType type,
  1748. const std::vector<std::string>& srcs,
  1749. bool excludeFromAll)
  1750. {
  1751. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1752. type == cmStateEnums::SHARED_LIBRARY ||
  1753. type == cmStateEnums::MODULE_LIBRARY ||
  1754. type == cmStateEnums::OBJECT_LIBRARY ||
  1755. type == cmStateEnums::INTERFACE_LIBRARY);
  1756. cmTarget* target = this->AddNewTarget(type, lname);
  1757. // Clear its dependencies. Otherwise, dependencies might persist
  1758. // over changes in CMakeLists.txt, making the information stale and
  1759. // hence useless.
  1760. target->ClearDependencyInformation(*this);
  1761. if (excludeFromAll ||
  1762. (type != cmStateEnums::INTERFACE_LIBRARY &&
  1763. this->GetPropertyAsBool("EXCLUDE_FROM_ALL"))) {
  1764. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1765. }
  1766. target->AddSources(srcs);
  1767. this->AddGlobalLinkInformation(*target);
  1768. return target;
  1769. }
  1770. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1771. const std::vector<std::string>& srcs,
  1772. bool excludeFromAll)
  1773. {
  1774. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1775. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1776. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1777. }
  1778. target->AddSources(srcs);
  1779. this->AddGlobalLinkInformation(*target);
  1780. return target;
  1781. }
  1782. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1783. const std::string& name)
  1784. {
  1785. cmTargets::iterator it =
  1786. this->Targets
  1787. .insert(cmTargets::value_type(
  1788. name, cmTarget(name, type, cmTarget::VisibilityNormal, this)))
  1789. .first;
  1790. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1791. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1792. return &it->second;
  1793. }
  1794. cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput(
  1795. const std::string& name) const
  1796. {
  1797. std::string out;
  1798. // look through all the source files that have custom commands
  1799. // and see if the custom command has the passed source file as an output
  1800. for (cmSourceFile* src : this->SourceFiles) {
  1801. // does this source file have a custom command?
  1802. if (src->GetCustomCommand()) {
  1803. // Does the output of the custom command match the source file name?
  1804. const std::vector<std::string>& outputs =
  1805. src->GetCustomCommand()->GetOutputs();
  1806. for (std::string const& output : outputs) {
  1807. out = output;
  1808. std::string::size_type pos = out.rfind(name);
  1809. // If the output matches exactly
  1810. if (pos != std::string::npos && pos == out.size() - name.size() &&
  1811. (pos == 0 || out[pos - 1] == '/')) {
  1812. return src;
  1813. }
  1814. }
  1815. }
  1816. }
  1817. // otherwise return NULL
  1818. return nullptr;
  1819. }
  1820. cmSourceFile* cmMakefile::GetSourceFileWithOutput(
  1821. const std::string& name) const
  1822. {
  1823. // If the queried path is not absolute we use the backward compatible
  1824. // linear-time search for an output with a matching suffix.
  1825. if (!cmSystemTools::FileIsFullPath(name)) {
  1826. return this->LinearGetSourceFileWithOutput(name);
  1827. }
  1828. // Otherwise we use an efficient lookup map.
  1829. OutputToSourceMap::const_iterator o = this->OutputToSource.find(name);
  1830. if (o != this->OutputToSource.end()) {
  1831. return (*o).second;
  1832. }
  1833. return nullptr;
  1834. }
  1835. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1836. cmSourceGroup* cmMakefile::GetSourceGroup(
  1837. const std::vector<std::string>& name) const
  1838. {
  1839. cmSourceGroup* sg = nullptr;
  1840. // first look for source group starting with the same as the one we want
  1841. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1842. std::string const& sgName = srcGroup.GetName();
  1843. if (sgName == name[0]) {
  1844. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1845. break;
  1846. }
  1847. }
  1848. if (sg != nullptr) {
  1849. // iterate through its children to find match source group
  1850. for (unsigned int i = 1; i < name.size(); ++i) {
  1851. sg = sg->LookupChild(name[i]);
  1852. if (sg == nullptr) {
  1853. break;
  1854. }
  1855. }
  1856. }
  1857. return sg;
  1858. }
  1859. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  1860. {
  1861. std::vector<std::string> nameVector;
  1862. nameVector.push_back(name);
  1863. this->AddSourceGroup(nameVector, regex);
  1864. }
  1865. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  1866. const char* regex)
  1867. {
  1868. cmSourceGroup* sg = nullptr;
  1869. std::vector<std::string> currentName;
  1870. int i = 0;
  1871. const int lastElement = static_cast<int>(name.size() - 1);
  1872. for (i = lastElement; i >= 0; --i) {
  1873. currentName.assign(name.begin(), name.begin() + i + 1);
  1874. sg = this->GetSourceGroup(currentName);
  1875. if (sg != nullptr) {
  1876. break;
  1877. }
  1878. }
  1879. // i now contains the index of the last found component
  1880. if (i == lastElement) {
  1881. // group already exists, replace its regular expression
  1882. if (regex && sg) {
  1883. // We only want to set the regular expression. If there are already
  1884. // source files in the group, we don't want to remove them.
  1885. sg->SetGroupRegex(regex);
  1886. }
  1887. return;
  1888. }
  1889. if (i == -1) {
  1890. // group does not exist nor belong to any existing group
  1891. // add its first component
  1892. this->SourceGroups.emplace_back(name[0], regex);
  1893. sg = this->GetSourceGroup(currentName);
  1894. i = 0; // last component found
  1895. }
  1896. if (!sg) {
  1897. cmSystemTools::Error("Could not create source group ");
  1898. return;
  1899. }
  1900. // build the whole source group path
  1901. for (++i; i <= lastElement; ++i) {
  1902. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  1903. sg = sg->LookupChild(name[i]);
  1904. }
  1905. sg->SetGroupRegex(regex);
  1906. }
  1907. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  1908. const std::vector<std::string>& folders)
  1909. {
  1910. cmSourceGroup* sg = this->GetSourceGroup(folders);
  1911. if (sg == nullptr) {
  1912. this->AddSourceGroup(folders);
  1913. sg = this->GetSourceGroup(folders);
  1914. }
  1915. return sg;
  1916. }
  1917. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  1918. {
  1919. const char* delimiter = this->GetDefinition("SOURCE_GROUP_DELIMITER");
  1920. if (delimiter == nullptr) {
  1921. delimiter = "\\";
  1922. }
  1923. return this->GetOrCreateSourceGroup(
  1924. cmSystemTools::tokenize(name, delimiter));
  1925. }
  1926. /**
  1927. * Find a source group whose regular expression matches the filename
  1928. * part of the given source name. Search backward through the list of
  1929. * source groups, and take the first matching group found. This way
  1930. * non-inherited SOURCE_GROUP commands will have precedence over
  1931. * inherited ones.
  1932. */
  1933. cmSourceGroup* cmMakefile::FindSourceGroup(
  1934. const std::string& source, std::vector<cmSourceGroup>& groups) const
  1935. {
  1936. // First search for a group that lists the file explicitly.
  1937. for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
  1938. sg != groups.rend(); ++sg) {
  1939. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  1940. if (result) {
  1941. return result;
  1942. }
  1943. }
  1944. // Now search for a group whose regex matches the file.
  1945. for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
  1946. sg != groups.rend(); ++sg) {
  1947. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  1948. if (result) {
  1949. return result;
  1950. }
  1951. }
  1952. // Shouldn't get here, but just in case, return the default group.
  1953. return groups.data();
  1954. }
  1955. #endif
  1956. static bool mightExpandVariablesCMP0019(const char* s)
  1957. {
  1958. return s && *s && strstr(s, "${") && strchr(s, '}');
  1959. }
  1960. void cmMakefile::ExpandVariablesCMP0019()
  1961. {
  1962. // Drop this ancient compatibility behavior with a policy.
  1963. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  1964. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  1965. return;
  1966. }
  1967. std::ostringstream w;
  1968. const char* includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  1969. if (mightExpandVariablesCMP0019(includeDirs)) {
  1970. std::string dirs = includeDirs;
  1971. this->ExpandVariablesInString(dirs, true, true);
  1972. if (pol == cmPolicies::WARN && dirs != includeDirs) {
  1973. /* clang-format off */
  1974. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  1975. << " " << includeDirs << "\n"
  1976. << "as\n"
  1977. << " " << dirs << "\n";
  1978. /* clang-format on */
  1979. }
  1980. this->SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
  1981. }
  1982. // Also for each target's INCLUDE_DIRECTORIES property:
  1983. for (auto& target : this->Targets) {
  1984. cmTarget& t = target.second;
  1985. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  1986. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  1987. continue;
  1988. }
  1989. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  1990. if (mightExpandVariablesCMP0019(includeDirs)) {
  1991. std::string dirs = includeDirs;
  1992. this->ExpandVariablesInString(dirs, true, true);
  1993. if (pol == cmPolicies::WARN && dirs != includeDirs) {
  1994. /* clang-format off */
  1995. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  1996. << " " << includeDirs << "\n"
  1997. << "as\n"
  1998. << " " << dirs << "\n";
  1999. /* clang-format on */
  2000. }
  2001. t.SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
  2002. }
  2003. }
  2004. if (const char* linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2005. if (mightExpandVariablesCMP0019(linkDirsProp)) {
  2006. std::string d = linkDirsProp;
  2007. std::string orig = linkDirsProp;
  2008. this->ExpandVariablesInString(d, true, true);
  2009. if (pol == cmPolicies::WARN && d != orig) {
  2010. /* clang-format off */
  2011. w << "Evaluated link directories\n"
  2012. << " " << orig << "\n"
  2013. << "as\n"
  2014. << " " << d << "\n";
  2015. /* clang-format on */
  2016. }
  2017. }
  2018. }
  2019. if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2020. std::vector<std::string> linkLibs;
  2021. cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs);
  2022. for (std::vector<std::string>::iterator l = linkLibs.begin();
  2023. l != linkLibs.end(); ++l) {
  2024. std::string libName = *l;
  2025. if (libName == "optimized") {
  2026. ++l;
  2027. libName = *l;
  2028. } else if (libName == "debug") {
  2029. ++l;
  2030. libName = *l;
  2031. }
  2032. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2033. std::string orig = libName;
  2034. this->ExpandVariablesInString(libName, true, true);
  2035. if (pol == cmPolicies::WARN && libName != orig) {
  2036. /* clang-format off */
  2037. w << "Evaluated link library\n"
  2038. << " " << orig << "\n"
  2039. << "as\n"
  2040. << " " << libName << "\n";
  2041. /* clang-format on */
  2042. }
  2043. }
  2044. }
  2045. }
  2046. if (!w.str().empty()) {
  2047. std::ostringstream m;
  2048. /* clang-format off */
  2049. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2050. << "\n"
  2051. << "The following variable evaluations were encountered:\n"
  2052. << w.str();
  2053. /* clang-format on */
  2054. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2055. m.str(), this->Backtrace);
  2056. }
  2057. }
  2058. bool cmMakefile::IsOn(const std::string& name) const
  2059. {
  2060. const char* value = this->GetDefinition(name);
  2061. return cmSystemTools::IsOn(value);
  2062. }
  2063. bool cmMakefile::IsSet(const std::string& name) const
  2064. {
  2065. const char* value = this->GetDefinition(name);
  2066. if (!value) {
  2067. return false;
  2068. }
  2069. if (!*value) {
  2070. return false;
  2071. }
  2072. if (cmSystemTools::IsNOTFOUND(value)) {
  2073. return false;
  2074. }
  2075. return true;
  2076. }
  2077. bool cmMakefile::PlatformIs32Bit() const
  2078. {
  2079. if (const char* plat_abi =
  2080. this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2081. if (strcmp(plat_abi, "ELF X32") == 0) {
  2082. return false;
  2083. }
  2084. }
  2085. if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2086. return atoi(sizeof_dptr) == 4;
  2087. }
  2088. return false;
  2089. }
  2090. bool cmMakefile::PlatformIs64Bit() const
  2091. {
  2092. if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2093. return atoi(sizeof_dptr) == 8;
  2094. }
  2095. return false;
  2096. }
  2097. bool cmMakefile::PlatformIsx32() const
  2098. {
  2099. if (const char* plat_abi =
  2100. this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2101. if (strcmp(plat_abi, "ELF X32") == 0) {
  2102. return true;
  2103. }
  2104. }
  2105. return false;
  2106. }
  2107. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2108. {
  2109. std::string sdkRoot;
  2110. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2111. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2112. struct
  2113. {
  2114. std::string name;
  2115. AppleSDK sdk;
  2116. } const sdkDatabase[]{
  2117. { "appletvos", AppleSDK::AppleTVOS },
  2118. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2119. { "iphoneos", AppleSDK::IPhoneOS },
  2120. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2121. { "watchos", AppleSDK::WatchOS },
  2122. { "watchsimulator", AppleSDK::WatchSimulator },
  2123. };
  2124. for (auto const& entry : sdkDatabase) {
  2125. if (sdkRoot.find(entry.name) == 0 ||
  2126. sdkRoot.find(std::string("/") + entry.name) != std::string::npos) {
  2127. return entry.sdk;
  2128. }
  2129. }
  2130. return AppleSDK::MacOS;
  2131. }
  2132. bool cmMakefile::PlatformIsAppleEmbedded() const
  2133. {
  2134. return GetAppleSDKType() != AppleSDK::MacOS;
  2135. }
  2136. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2137. {
  2138. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2139. if (!language.empty()) {
  2140. name += "_";
  2141. name += language;
  2142. }
  2143. name += "_FLAG";
  2144. return GetDefinition(name);
  2145. }
  2146. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2147. {
  2148. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2149. return true;
  2150. }
  2151. // If we are doing an in-source build, then the test will always fail
  2152. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2153. this->GetHomeOutputDirectory())) {
  2154. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2155. }
  2156. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2157. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2158. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2159. }
  2160. const std::string& cmMakefile::GetRequiredDefinition(
  2161. const std::string& name) const
  2162. {
  2163. static std::string const empty;
  2164. const std::string* def = GetDef(name);
  2165. if (!def) {
  2166. cmSystemTools::Error("Error required internal CMake variable not "
  2167. "set, cmake may not be built correctly.\n",
  2168. "Missing variable is:\n", name.c_str());
  2169. return empty;
  2170. }
  2171. return *def;
  2172. }
  2173. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2174. {
  2175. const std::string* def = this->StateSnapshot.GetDefinition(name);
  2176. if (!def) {
  2177. def = this->GetState()->GetInitializedCacheValue(name);
  2178. }
  2179. #ifdef CMAKE_BUILD_WITH_CMAKE
  2180. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2181. if (!def) {
  2182. vv->VariableAccessed(
  2183. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2184. }
  2185. }
  2186. #endif
  2187. return def != nullptr;
  2188. }
  2189. const std::string* cmMakefile::GetDef(const std::string& name) const
  2190. {
  2191. const std::string* def = this->StateSnapshot.GetDefinition(name);
  2192. if (!def) {
  2193. def = this->GetState()->GetInitializedCacheValue(name);
  2194. }
  2195. #ifdef CMAKE_BUILD_WITH_CMAKE
  2196. cmVariableWatch* vv = this->GetVariableWatch();
  2197. if (vv && !this->SuppressSideEffects) {
  2198. bool const watch_function_executed =
  2199. vv->VariableAccessed(name,
  2200. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2201. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2202. (def ? def->c_str() : nullptr), this);
  2203. if (watch_function_executed) {
  2204. // A callback was executed and may have caused re-allocation of the
  2205. // variable storage. Look it up again for now.
  2206. // FIXME: Refactor variable storage to avoid this problem.
  2207. def = this->StateSnapshot.GetDefinition(name);
  2208. if (!def) {
  2209. def = this->GetState()->GetInitializedCacheValue(name);
  2210. }
  2211. }
  2212. }
  2213. #endif
  2214. return def;
  2215. }
  2216. const char* cmMakefile::GetDefinition(const std::string& name) const
  2217. {
  2218. const std::string* def = GetDef(name);
  2219. if (!def) {
  2220. return nullptr;
  2221. }
  2222. return def->c_str();
  2223. }
  2224. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2225. {
  2226. static std::string const empty;
  2227. const std::string* def = GetDef(name);
  2228. if (!def) {
  2229. return empty;
  2230. }
  2231. return *def;
  2232. }
  2233. std::vector<std::string> cmMakefile::GetDefinitions() const
  2234. {
  2235. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2236. std::vector<std::string> cacheKeys = this->GetState()->GetCacheEntryKeys();
  2237. res.insert(res.end(), cacheKeys.begin(), cacheKeys.end());
  2238. std::sort(res.begin(), res.end());
  2239. return res;
  2240. }
  2241. const std::string& cmMakefile::ExpandVariablesInString(
  2242. std::string& source) const
  2243. {
  2244. return this->ExpandVariablesInString(source, false, false);
  2245. }
  2246. const std::string& cmMakefile::ExpandVariablesInString(
  2247. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2248. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2249. {
  2250. bool compareResults = false;
  2251. MessageType mtype = MessageType::LOG;
  2252. std::string errorstr;
  2253. std::string original;
  2254. // Sanity check the @ONLY mode.
  2255. if (atOnly && (!noEscapes || !removeEmpty)) {
  2256. // This case should never be called. At-only is for
  2257. // configure-file/string which always does no escapes.
  2258. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2259. "ExpandVariablesInString @ONLY called "
  2260. "on something with escapes.");
  2261. return source;
  2262. }
  2263. // Variables used in the WARN case.
  2264. std::string newResult;
  2265. std::string newErrorstr;
  2266. MessageType newError = MessageType::LOG;
  2267. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2268. case cmPolicies::WARN: {
  2269. // Save the original string for the warning.
  2270. original = source;
  2271. newResult = source;
  2272. compareResults = true;
  2273. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2274. // dereferences since the OLD behavior is still what is actually used.
  2275. this->SuppressSideEffects = true;
  2276. newError = ExpandVariablesInStringNew(newErrorstr, newResult,
  2277. escapeQuotes, noEscapes, atOnly,
  2278. filename, line, replaceAt);
  2279. this->SuppressSideEffects = false;
  2280. CM_FALLTHROUGH;
  2281. }
  2282. case cmPolicies::OLD:
  2283. mtype =
  2284. ExpandVariablesInStringOld(errorstr, source, escapeQuotes, noEscapes,
  2285. atOnly, filename, line, removeEmpty, true);
  2286. break;
  2287. case cmPolicies::REQUIRED_IF_USED:
  2288. case cmPolicies::REQUIRED_ALWAYS:
  2289. // Messaging here would be *very* verbose.
  2290. case cmPolicies::NEW:
  2291. mtype =
  2292. ExpandVariablesInStringNew(errorstr, source, escapeQuotes, noEscapes,
  2293. atOnly, filename, line, replaceAt);
  2294. break;
  2295. }
  2296. // If it's an error in either case, just report the error...
  2297. if (mtype != MessageType::LOG) {
  2298. if (mtype == MessageType::FATAL_ERROR) {
  2299. cmSystemTools::SetFatalErrorOccured();
  2300. }
  2301. this->IssueMessage(mtype, errorstr);
  2302. }
  2303. // ...otherwise, see if there's a difference that needs to be warned about.
  2304. else if (compareResults && (newResult != source || newError != mtype)) {
  2305. std::string msg = cmPolicies::GetPolicyWarning(cmPolicies::CMP0053);
  2306. msg += "\n";
  2307. std::string msg_input = original;
  2308. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2309. msg += "For input:\n '";
  2310. msg += msg_input;
  2311. msg += "'\n";
  2312. std::string msg_old = source;
  2313. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2314. msg += "the old evaluation rules produce:\n '";
  2315. msg += msg_old;
  2316. msg += "'\n";
  2317. if (newError == mtype) {
  2318. std::string msg_new = newResult;
  2319. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2320. msg += "but the new evaluation rules produce:\n '";
  2321. msg += msg_new;
  2322. msg += "'\n";
  2323. } else {
  2324. std::string msg_err = newErrorstr;
  2325. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2326. msg += "but the new evaluation rules produce an error:\n ";
  2327. msg += msg_err;
  2328. msg += "\n";
  2329. }
  2330. msg +=
  2331. "Using the old result for compatibility since the policy is not set.";
  2332. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2333. }
  2334. return source;
  2335. }
  2336. MessageType cmMakefile::ExpandVariablesInStringOld(
  2337. std::string& errorstr, std::string& source, bool escapeQuotes,
  2338. bool noEscapes, bool atOnly, const char* filename, long line,
  2339. bool removeEmpty, bool replaceAt) const
  2340. {
  2341. // Fast path strings without any special characters.
  2342. if (source.find_first_of("$@\\") == std::string::npos) {
  2343. return MessageType::LOG;
  2344. }
  2345. // Special-case the @ONLY mode.
  2346. if (atOnly) {
  2347. // Store an original copy of the input.
  2348. std::string input = source;
  2349. // Start with empty output.
  2350. source.clear();
  2351. // Look for one @VAR@ at a time.
  2352. const char* in = input.c_str();
  2353. while (this->cmAtVarRegex.find(in)) {
  2354. // Get the range of the string to replace.
  2355. const char* first = in + this->cmAtVarRegex.start();
  2356. const char* last = in + this->cmAtVarRegex.end();
  2357. // Store the unchanged part of the string now.
  2358. source.append(in, first - in);
  2359. // Lookup the definition of VAR.
  2360. std::string var(first + 1, last - first - 2);
  2361. if (const char* val = this->GetDefinition(var)) {
  2362. // Store the value in the output escaping as requested.
  2363. if (escapeQuotes) {
  2364. source.append(cmSystemTools::EscapeQuotes(val));
  2365. } else {
  2366. source.append(val);
  2367. }
  2368. }
  2369. // Continue looking for @VAR@ further along the string.
  2370. in = last;
  2371. }
  2372. // Append the rest of the unchanged part of the string.
  2373. source.append(in);
  2374. return MessageType::LOG;
  2375. }
  2376. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2377. // with GetDefinition(), if not found in the map, nothing is expanded.
  2378. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2379. // the current environment variables.
  2380. cmCommandArgumentParserHelper parser;
  2381. parser.SetMakefile(this);
  2382. parser.SetLineFile(line, filename);
  2383. parser.SetEscapeQuotes(escapeQuotes);
  2384. parser.SetNoEscapeMode(noEscapes);
  2385. parser.SetReplaceAtSyntax(replaceAt);
  2386. parser.SetRemoveEmpty(removeEmpty);
  2387. int res = parser.ParseString(source.c_str(), 0);
  2388. const char* emsg = parser.GetError();
  2389. MessageType mtype = MessageType::LOG;
  2390. if (res && !emsg[0]) {
  2391. source = parser.GetResult();
  2392. } else {
  2393. // Construct the main error message.
  2394. std::ostringstream error;
  2395. error << "Syntax error in cmake code ";
  2396. if (filename && line > 0) {
  2397. // This filename and line number may be more specific than the
  2398. // command context because one command invocation can have
  2399. // arguments on multiple lines.
  2400. error << "at\n"
  2401. << " " << filename << ":" << line << "\n";
  2402. }
  2403. error << "when parsing string\n"
  2404. << " " << source << "\n";
  2405. error << emsg;
  2406. // If the parser failed ("res" is false) then this is a real
  2407. // argument parsing error, so the policy applies. Otherwise the
  2408. // parser reported an error message without failing because the
  2409. // helper implementation is unhappy, which has always reported an
  2410. // error.
  2411. mtype = MessageType::FATAL_ERROR;
  2412. if (!res) {
  2413. // This is a real argument parsing error. Use policy CMP0010 to
  2414. // decide whether it is an error.
  2415. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2416. case cmPolicies::WARN:
  2417. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2418. CM_FALLTHROUGH;
  2419. case cmPolicies::OLD:
  2420. // OLD behavior is to just warn and continue.
  2421. mtype = MessageType::AUTHOR_WARNING;
  2422. break;
  2423. case cmPolicies::REQUIRED_IF_USED:
  2424. case cmPolicies::REQUIRED_ALWAYS:
  2425. error << "\n"
  2426. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2427. case cmPolicies::NEW:
  2428. // NEW behavior is to report the error.
  2429. break;
  2430. }
  2431. }
  2432. errorstr = error.str();
  2433. }
  2434. return mtype;
  2435. }
  2436. typedef enum
  2437. {
  2438. NORMAL,
  2439. ENVIRONMENT,
  2440. CACHE
  2441. } t_domain;
  2442. struct t_lookup
  2443. {
  2444. t_domain domain = NORMAL;
  2445. size_t loc = 0;
  2446. };
  2447. bool cmMakefile::IsProjectFile(const char* filename) const
  2448. {
  2449. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2450. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2451. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2452. }
  2453. int cmMakefile::GetRecursionDepth() const
  2454. {
  2455. return this->RecursionDepth;
  2456. }
  2457. void cmMakefile::SetRecursionDepth(int recursionDepth)
  2458. {
  2459. this->RecursionDepth = recursionDepth;
  2460. }
  2461. MessageType cmMakefile::ExpandVariablesInStringNew(
  2462. std::string& errorstr, std::string& source, bool escapeQuotes,
  2463. bool noEscapes, bool atOnly, const char* filename, long line,
  2464. bool replaceAt) const
  2465. {
  2466. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2467. // with GetDefinition(), if not found in the map, nothing is expanded.
  2468. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2469. // the current environment variables.
  2470. const char* in = source.c_str();
  2471. const char* last = in;
  2472. std::string result;
  2473. result.reserve(source.size());
  2474. std::vector<t_lookup> openstack;
  2475. bool error = false;
  2476. bool done = false;
  2477. MessageType mtype = MessageType::LOG;
  2478. cmState* state = this->GetCMakeInstance()->GetState();
  2479. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2480. do {
  2481. char inc = *in;
  2482. switch (inc) {
  2483. case '}':
  2484. if (!openstack.empty()) {
  2485. t_lookup var = openstack.back();
  2486. openstack.pop_back();
  2487. result.append(last, in - last);
  2488. std::string const& lookup = result.substr(var.loc);
  2489. const char* value = nullptr;
  2490. std::string varresult;
  2491. std::string svalue;
  2492. switch (var.domain) {
  2493. case NORMAL:
  2494. if (filename && lookup == lineVar) {
  2495. std::ostringstream ostr;
  2496. ostr << line;
  2497. varresult = ostr.str();
  2498. } else {
  2499. value = this->GetDefinition(lookup);
  2500. }
  2501. break;
  2502. case ENVIRONMENT:
  2503. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2504. value = svalue.c_str();
  2505. }
  2506. break;
  2507. case CACHE:
  2508. value = state->GetCacheEntryValue(lookup);
  2509. break;
  2510. }
  2511. // Get the string we're meant to append to.
  2512. if (value) {
  2513. if (escapeQuotes) {
  2514. varresult = cmSystemTools::EscapeQuotes(value);
  2515. } else {
  2516. varresult = value;
  2517. }
  2518. } else if (!this->SuppressSideEffects) {
  2519. this->MaybeWarnUninitialized(lookup, filename);
  2520. }
  2521. result.replace(var.loc, result.size() - var.loc, varresult);
  2522. // Start looking from here on out.
  2523. last = in + 1;
  2524. }
  2525. break;
  2526. case '$':
  2527. if (!atOnly) {
  2528. t_lookup lookup;
  2529. const char* next = in + 1;
  2530. const char* start = nullptr;
  2531. char nextc = *next;
  2532. if (nextc == '{') {
  2533. // Looking for a variable.
  2534. start = in + 2;
  2535. lookup.domain = NORMAL;
  2536. } else if (nextc == '<') {
  2537. } else if (!nextc) {
  2538. result.append(last, next - last);
  2539. last = next;
  2540. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2541. // Looking for an environment variable.
  2542. start = in + 5;
  2543. lookup.domain = ENVIRONMENT;
  2544. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2545. // Looking for a cache variable.
  2546. start = in + 7;
  2547. lookup.domain = CACHE;
  2548. } else {
  2549. if (this->cmNamedCurly.find(next)) {
  2550. errorstr = "Syntax $" +
  2551. std::string(next, this->cmNamedCurly.end()) +
  2552. "{} is not supported. Only ${}, $ENV{}, "
  2553. "and $CACHE{} are allowed.";
  2554. mtype = MessageType::FATAL_ERROR;
  2555. error = true;
  2556. }
  2557. }
  2558. if (start) {
  2559. result.append(last, in - last);
  2560. last = start;
  2561. in = start - 1;
  2562. lookup.loc = result.size();
  2563. openstack.push_back(lookup);
  2564. }
  2565. break;
  2566. }
  2567. CM_FALLTHROUGH;
  2568. case '\\':
  2569. if (!noEscapes) {
  2570. const char* next = in + 1;
  2571. char nextc = *next;
  2572. if (nextc == 't') {
  2573. result.append(last, in - last);
  2574. result.append("\t");
  2575. last = next + 1;
  2576. } else if (nextc == 'n') {
  2577. result.append(last, in - last);
  2578. result.append("\n");
  2579. last = next + 1;
  2580. } else if (nextc == 'r') {
  2581. result.append(last, in - last);
  2582. result.append("\r");
  2583. last = next + 1;
  2584. } else if (nextc == ';' && openstack.empty()) {
  2585. // Handled in ExpandListArgument; pass the backslash literally.
  2586. } else if (isalnum(nextc) || nextc == '\0') {
  2587. errorstr += "Invalid character escape '\\";
  2588. if (nextc) {
  2589. errorstr += nextc;
  2590. errorstr += "'.";
  2591. } else {
  2592. errorstr += "' (at end of input).";
  2593. }
  2594. error = true;
  2595. } else {
  2596. // Take what we've found so far, skipping the escape character.
  2597. result.append(last, in - last);
  2598. // Start tracking from the next character.
  2599. last = in + 1;
  2600. }
  2601. // Skip the next character since it was escaped, but don't read past
  2602. // the end of the string.
  2603. if (*last) {
  2604. ++in;
  2605. }
  2606. }
  2607. break;
  2608. case '\n':
  2609. // Onto the next line.
  2610. ++line;
  2611. break;
  2612. case '\0':
  2613. done = true;
  2614. break;
  2615. case '@':
  2616. if (replaceAt) {
  2617. const char* nextAt = strchr(in + 1, '@');
  2618. if (nextAt && nextAt != in + 1 &&
  2619. nextAt ==
  2620. in + 1 +
  2621. strspn(in + 1,
  2622. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2623. "abcdefghijklmnopqrstuvwxyz"
  2624. "0123456789/_.+-")) {
  2625. std::string variable(in + 1, nextAt - in - 1);
  2626. std::string varresult;
  2627. if (filename && variable == lineVar) {
  2628. varresult = std::to_string(line);
  2629. } else {
  2630. const std::string* def = this->GetDef(variable);
  2631. if (def) {
  2632. varresult = *def;
  2633. } else if (!this->SuppressSideEffects) {
  2634. this->MaybeWarnUninitialized(variable, filename);
  2635. }
  2636. }
  2637. if (escapeQuotes) {
  2638. varresult = cmSystemTools::EscapeQuotes(varresult);
  2639. }
  2640. // Skip over the variable.
  2641. result.append(last, in - last);
  2642. result.append(varresult);
  2643. in = nextAt;
  2644. last = in + 1;
  2645. break;
  2646. }
  2647. }
  2648. // Failed to find a valid @ expansion; treat it as literal.
  2649. /* FALLTHROUGH */
  2650. default: {
  2651. if (!openstack.empty() &&
  2652. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2653. inc == '+' || inc == '-')) {
  2654. errorstr += "Invalid character (\'";
  2655. errorstr += inc;
  2656. result.append(last, in - last);
  2657. errorstr += "\') in a variable name: "
  2658. "'" +
  2659. result.substr(openstack.back().loc) + "'";
  2660. mtype = MessageType::FATAL_ERROR;
  2661. error = true;
  2662. }
  2663. break;
  2664. }
  2665. }
  2666. // Look at the next character.
  2667. } while (!error && !done && *++in);
  2668. // Check for open variable references yet.
  2669. if (!error && !openstack.empty()) {
  2670. // There's an open variable reference waiting. Policy CMP0010 flags
  2671. // whether this is an error or not. The new parser now enforces
  2672. // CMP0010 as well.
  2673. errorstr += "There is an unterminated variable reference.";
  2674. error = true;
  2675. }
  2676. if (error) {
  2677. std::ostringstream emsg;
  2678. emsg << "Syntax error in cmake code ";
  2679. if (filename) {
  2680. // This filename and line number may be more specific than the
  2681. // command context because one command invocation can have
  2682. // arguments on multiple lines.
  2683. emsg << "at\n"
  2684. << " " << filename << ":" << line << "\n";
  2685. }
  2686. emsg << "when parsing string\n"
  2687. << " " << source << "\n";
  2688. emsg << errorstr;
  2689. mtype = MessageType::FATAL_ERROR;
  2690. errorstr = emsg.str();
  2691. } else {
  2692. // Append the rest of the unchanged part of the string.
  2693. result.append(last);
  2694. source = result;
  2695. }
  2696. return mtype;
  2697. }
  2698. void cmMakefile::RemoveVariablesInString(std::string& source,
  2699. bool atOnly) const
  2700. {
  2701. if (!atOnly) {
  2702. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2703. while (var.find(source)) {
  2704. source.erase(var.start(), var.end() - var.start());
  2705. }
  2706. }
  2707. if (!atOnly) {
  2708. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2709. while (varb.find(source)) {
  2710. source.erase(varb.start(), varb.end() - varb.start());
  2711. }
  2712. }
  2713. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2714. while (var2.find(source)) {
  2715. source.erase(var2.start(), var2.end() - var2.start());
  2716. }
  2717. }
  2718. std::string cmMakefile::GetConfigurations(std::vector<std::string>& configs,
  2719. bool singleConfig) const
  2720. {
  2721. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2722. if (const char* configTypes =
  2723. this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2724. cmSystemTools::ExpandListArgument(configTypes, configs);
  2725. }
  2726. return "";
  2727. }
  2728. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2729. if (singleConfig && !buildType.empty()) {
  2730. configs.push_back(buildType);
  2731. }
  2732. return buildType;
  2733. }
  2734. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  2735. cmExecutionStatus& status)
  2736. {
  2737. // if there are no blockers get out of here
  2738. if (this->FunctionBlockers.begin() == this->FunctionBlockers.end()) {
  2739. return false;
  2740. }
  2741. // loop over all function blockers to see if any block this command
  2742. // evaluate in reverse, this is critical for balanced IF statements etc
  2743. for (cmFunctionBlocker* pos : cmReverseRange(this->FunctionBlockers)) {
  2744. if (pos->IsFunctionBlocked(lff, *this, status)) {
  2745. return true;
  2746. }
  2747. }
  2748. return false;
  2749. }
  2750. void cmMakefile::PushFunctionBlockerBarrier()
  2751. {
  2752. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2753. }
  2754. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2755. {
  2756. // Remove any extra entries pushed on the barrier.
  2757. FunctionBlockersType::size_type barrier =
  2758. this->FunctionBlockerBarriers.back();
  2759. while (this->FunctionBlockers.size() > barrier) {
  2760. std::unique_ptr<cmFunctionBlocker> fb(this->FunctionBlockers.back());
  2761. this->FunctionBlockers.pop_back();
  2762. if (reportError) {
  2763. // Report the context in which the unclosed block was opened.
  2764. cmListFileContext const& lfc = fb->GetStartingContext();
  2765. std::ostringstream e;
  2766. /* clang-format off */
  2767. e << "A logical block opening on the line\n"
  2768. << " " << lfc << "\n"
  2769. << "is not closed.";
  2770. /* clang-format on */
  2771. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2772. reportError = false;
  2773. }
  2774. }
  2775. // Remove the barrier.
  2776. this->FunctionBlockerBarriers.pop_back();
  2777. }
  2778. void cmMakefile::PushLoopBlock()
  2779. {
  2780. assert(!this->LoopBlockCounter.empty());
  2781. this->LoopBlockCounter.top()++;
  2782. }
  2783. void cmMakefile::PopLoopBlock()
  2784. {
  2785. assert(!this->LoopBlockCounter.empty());
  2786. assert(this->LoopBlockCounter.top() > 0);
  2787. this->LoopBlockCounter.top()--;
  2788. }
  2789. void cmMakefile::PushLoopBlockBarrier()
  2790. {
  2791. this->LoopBlockCounter.push(0);
  2792. }
  2793. void cmMakefile::PopLoopBlockBarrier()
  2794. {
  2795. assert(!this->LoopBlockCounter.empty());
  2796. assert(this->LoopBlockCounter.top() == 0);
  2797. this->LoopBlockCounter.pop();
  2798. }
  2799. bool cmMakefile::IsLoopBlock() const
  2800. {
  2801. assert(!this->LoopBlockCounter.empty());
  2802. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  2803. }
  2804. std::string cmMakefile::GetExecutionFilePath() const
  2805. {
  2806. assert(this->StateSnapshot.IsValid());
  2807. return this->StateSnapshot.GetExecutionListFile();
  2808. }
  2809. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  2810. std::vector<std::string>& outArgs,
  2811. const char* filename) const
  2812. {
  2813. std::string efp = this->GetExecutionFilePath();
  2814. if (!filename) {
  2815. filename = efp.c_str();
  2816. }
  2817. std::string value;
  2818. outArgs.reserve(inArgs.size());
  2819. for (cmListFileArgument const& i : inArgs) {
  2820. // No expansion in a bracket argument.
  2821. if (i.Delim == cmListFileArgument::Bracket) {
  2822. outArgs.push_back(i.Value);
  2823. continue;
  2824. }
  2825. // Expand the variables in the argument.
  2826. value = i.Value;
  2827. this->ExpandVariablesInString(value, false, false, false, filename, i.Line,
  2828. false, false);
  2829. // If the argument is quoted, it should be one argument.
  2830. // Otherwise, it may be a list of arguments.
  2831. if (i.Delim == cmListFileArgument::Quoted) {
  2832. outArgs.push_back(value);
  2833. } else {
  2834. cmSystemTools::ExpandListArgument(value, outArgs);
  2835. }
  2836. }
  2837. return !cmSystemTools::GetFatalErrorOccured();
  2838. }
  2839. bool cmMakefile::ExpandArguments(
  2840. std::vector<cmListFileArgument> const& inArgs,
  2841. std::vector<cmExpandedCommandArgument>& outArgs, const char* filename) const
  2842. {
  2843. std::string efp = this->GetExecutionFilePath();
  2844. if (!filename) {
  2845. filename = efp.c_str();
  2846. }
  2847. std::string value;
  2848. outArgs.reserve(inArgs.size());
  2849. for (cmListFileArgument const& i : inArgs) {
  2850. // No expansion in a bracket argument.
  2851. if (i.Delim == cmListFileArgument::Bracket) {
  2852. outArgs.emplace_back(i.Value, true);
  2853. continue;
  2854. }
  2855. // Expand the variables in the argument.
  2856. value = i.Value;
  2857. this->ExpandVariablesInString(value, false, false, false, filename, i.Line,
  2858. false, false);
  2859. // If the argument is quoted, it should be one argument.
  2860. // Otherwise, it may be a list of arguments.
  2861. if (i.Delim == cmListFileArgument::Quoted) {
  2862. outArgs.emplace_back(value, true);
  2863. } else {
  2864. std::vector<std::string> stringArgs;
  2865. cmSystemTools::ExpandListArgument(value, stringArgs);
  2866. for (std::string const& stringArg : stringArgs) {
  2867. outArgs.emplace_back(stringArg, false);
  2868. }
  2869. }
  2870. }
  2871. return !cmSystemTools::GetFatalErrorOccured();
  2872. }
  2873. void cmMakefile::AddFunctionBlocker(cmFunctionBlocker* fb)
  2874. {
  2875. if (!this->ExecutionStatusStack.empty()) {
  2876. // Record the context in which the blocker is created.
  2877. fb->SetStartingContext(this->GetExecutionContext());
  2878. }
  2879. this->FunctionBlockers.push_back(fb);
  2880. }
  2881. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
  2882. cmFunctionBlocker* fb, const cmListFileFunction& lff)
  2883. {
  2884. // Find the function blocker stack barrier for the current scope.
  2885. // We only remove a blocker whose index is not less than the barrier.
  2886. FunctionBlockersType::size_type barrier = 0;
  2887. if (!this->FunctionBlockerBarriers.empty()) {
  2888. barrier = this->FunctionBlockerBarriers.back();
  2889. }
  2890. // Search for the function blocker whose scope this command ends.
  2891. for (FunctionBlockersType::size_type i = this->FunctionBlockers.size();
  2892. i > barrier; --i) {
  2893. std::vector<cmFunctionBlocker*>::iterator pos =
  2894. this->FunctionBlockers.begin() + (i - 1);
  2895. if (*pos == fb) {
  2896. // Warn if the arguments do not match, but always remove.
  2897. if (!(*pos)->ShouldRemove(lff, *this)) {
  2898. cmListFileContext const& lfc = fb->GetStartingContext();
  2899. cmListFileContext closingContext =
  2900. cmListFileContext::FromCommandContext(lff, lfc.FilePath);
  2901. std::ostringstream e;
  2902. /* clang-format off */
  2903. e << "A logical block opening on the line\n"
  2904. << " " << lfc << "\n"
  2905. << "closes on the line\n"
  2906. << " " << closingContext << "\n"
  2907. << "with mis-matching arguments.";
  2908. /* clang-format on */
  2909. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2910. }
  2911. cmFunctionBlocker* b = *pos;
  2912. this->FunctionBlockers.erase(pos);
  2913. return std::unique_ptr<cmFunctionBlocker>(b);
  2914. }
  2915. }
  2916. return std::unique_ptr<cmFunctionBlocker>();
  2917. }
  2918. std::string const& cmMakefile::GetHomeDirectory() const
  2919. {
  2920. return this->GetCMakeInstance()->GetHomeDirectory();
  2921. }
  2922. std::string const& cmMakefile::GetHomeOutputDirectory() const
  2923. {
  2924. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2925. }
  2926. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  2927. {
  2928. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile.c_str());
  2929. }
  2930. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  2931. {
  2932. std::ostringstream strStream;
  2933. strStream << args.size();
  2934. this->AddDefinition("CMAKE_ARGC", strStream.str().c_str());
  2935. // this->MarkVariableAsUsed("CMAKE_ARGC");
  2936. for (unsigned int t = 0; t < args.size(); ++t) {
  2937. std::ostringstream tmpStream;
  2938. tmpStream << "CMAKE_ARGV" << t;
  2939. this->AddDefinition(tmpStream.str(), args[t].c_str());
  2940. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  2941. }
  2942. }
  2943. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  2944. cmSourceFileLocationKind kind) const
  2945. {
  2946. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  2947. if (kind == cmSourceFileLocationKind::Known) {
  2948. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  2949. if (sfsi != this->KnownFileSearchIndex.end()) {
  2950. return sfsi->second;
  2951. }
  2952. }
  2953. cmSourceFileLocation sfl(this, sourceName, kind);
  2954. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  2955. #if defined(_WIN32) || defined(__APPLE__)
  2956. name = cmSystemTools::LowerCase(name);
  2957. #endif
  2958. auto sfsi = this->SourceFileSearchIndex.find(name);
  2959. if (sfsi != this->SourceFileSearchIndex.end()) {
  2960. for (auto sf : sfsi->second) {
  2961. if (sf->Matches(sfl)) {
  2962. return sf;
  2963. }
  2964. }
  2965. }
  2966. return nullptr;
  2967. }
  2968. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  2969. bool generated,
  2970. cmSourceFileLocationKind kind)
  2971. {
  2972. cmSourceFile* sf = new cmSourceFile(this, sourceName, kind);
  2973. if (generated) {
  2974. sf->SetProperty("GENERATED", "1");
  2975. }
  2976. this->SourceFiles.push_back(sf);
  2977. auto name =
  2978. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  2979. #if defined(_WIN32) || defined(__APPLE__)
  2980. name = cmSystemTools::LowerCase(name);
  2981. #endif
  2982. this->SourceFileSearchIndex[name].push_back(sf);
  2983. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  2984. if (kind == cmSourceFileLocationKind::Known) {
  2985. this->KnownFileSearchIndex[sourceName] = sf;
  2986. }
  2987. return sf;
  2988. }
  2989. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  2990. bool generated,
  2991. cmSourceFileLocationKind kind)
  2992. {
  2993. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  2994. return esf;
  2995. }
  2996. return this->CreateSource(sourceName, generated, kind);
  2997. }
  2998. void cmMakefile::AddTargetObject(std::string const& tgtName,
  2999. std::string const& objFile)
  3000. {
  3001. cmSourceFile* sf = this->GetOrCreateSource(objFile, true);
  3002. sf->SetObjectLibrary(tgtName);
  3003. sf->SetProperty("EXTERNAL_OBJECT", "1");
  3004. #if defined(CMAKE_BUILD_WITH_CMAKE)
  3005. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  3006. sf->GetFullPath());
  3007. #endif
  3008. }
  3009. void cmMakefile::EnableLanguage(std::vector<std::string> const& lang,
  3010. bool optional)
  3011. {
  3012. this->AddDefinition("CMAKE_CFG_INTDIR",
  3013. this->GetGlobalGenerator()->GetCMakeCFGIntDir());
  3014. // If RC is explicitly listed we need to do it after other languages.
  3015. // On some platforms we enable RC implicitly while enabling others.
  3016. // Do not let that look like recursive enable_language(RC).
  3017. std::vector<std::string> langs;
  3018. std::vector<std::string> langsRC;
  3019. langs.reserve(lang.size());
  3020. for (std::string const& i : lang) {
  3021. if (i == "RC") {
  3022. langsRC.push_back(i);
  3023. } else {
  3024. langs.push_back(i);
  3025. }
  3026. }
  3027. if (!langs.empty()) {
  3028. this->GetGlobalGenerator()->EnableLanguage(langs, this, optional);
  3029. }
  3030. if (!langsRC.empty()) {
  3031. this->GetGlobalGenerator()->EnableLanguage(langsRC, this, optional);
  3032. }
  3033. }
  3034. int cmMakefile::TryCompile(const std::string& srcdir,
  3035. const std::string& bindir,
  3036. const std::string& projectName,
  3037. const std::string& targetName, bool fast, int jobs,
  3038. const std::vector<std::string>* cmakeArgs,
  3039. std::string& output)
  3040. {
  3041. this->IsSourceFileTryCompile = fast;
  3042. // does the binary directory exist ? If not create it...
  3043. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3044. cmSystemTools::MakeDirectory(bindir);
  3045. }
  3046. // change to the tests directory and run cmake
  3047. // use the cmake object instead of calling cmake
  3048. cmWorkingDirectory workdir(bindir);
  3049. if (workdir.Failed()) {
  3050. this->IssueMessage(MessageType::FATAL_ERROR,
  3051. "Failed to set working directory to " + bindir + " : " +
  3052. std::strerror(workdir.GetLastResult()));
  3053. cmSystemTools::SetFatalErrorOccured();
  3054. this->IsSourceFileTryCompile = false;
  3055. return 1;
  3056. }
  3057. // make sure the same generator is used
  3058. // use this program as the cmake to be run, it should not
  3059. // be run that way but the cmake object requires a vailid path
  3060. cmake cm(cmake::RoleProject, cmState::Project);
  3061. cm.SetIsInTryCompile(true);
  3062. cmGlobalGenerator* gg =
  3063. cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3064. if (!gg) {
  3065. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3066. "Global generator '" +
  3067. this->GetGlobalGenerator()->GetName() +
  3068. "' could not be created.");
  3069. cmSystemTools::SetFatalErrorOccured();
  3070. this->IsSourceFileTryCompile = false;
  3071. return 1;
  3072. }
  3073. gg->RecursionDepth = this->RecursionDepth;
  3074. cm.SetGlobalGenerator(gg);
  3075. // do a configure
  3076. cm.SetHomeDirectory(srcdir);
  3077. cm.SetHomeOutputDirectory(bindir);
  3078. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3079. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3080. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3081. cm.LoadCache();
  3082. if (!gg->IsMultiConfig()) {
  3083. if (const char* config =
  3084. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3085. // Tell the single-configuration generator which one to use.
  3086. // Add this before the user-provided CMake arguments in case
  3087. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3088. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3089. cmStateEnums::STRING);
  3090. }
  3091. }
  3092. const char* recursionDepth =
  3093. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3094. if (recursionDepth) {
  3095. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3096. "Maximum recursion depth", cmStateEnums::STRING);
  3097. }
  3098. // if cmake args were provided then pass them in
  3099. if (cmakeArgs) {
  3100. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3101. //
  3102. // Ideally we should use SetArgs to honor options like --warn-unused-vars.
  3103. // However, there is a subtle problem when certain arguments are passed to
  3104. // a macro wrapping around try_compile or try_run that does not escape
  3105. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3106. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3107. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3108. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3109. // the try_compile or try_run does not get the proper value of VAR. If we
  3110. // call SetArgs here then it would treat "b" as the source directory and
  3111. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3112. // does not exist", thus breaking the try_compile or try_run completely.
  3113. //
  3114. // Strictly speaking the bug is in the wrapper macro because the CMake
  3115. // language has always flattened nested lists and the macro should escape
  3116. // the semicolons in its arguments before forwarding them. However, this
  3117. // bug is so subtle that projects typically work anyway, usually because
  3118. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3119. // correct result. Calling SetArgs here would break such projects that
  3120. // previously built. Instead we work around the issue by never reporting
  3121. // unused arguments and ignoring options such as --warn-unused-vars.
  3122. cm.SetWarnUnusedCli(false);
  3123. // cm.SetArgs(*cmakeArgs, true);
  3124. cm.SetCacheArgs(*cmakeArgs);
  3125. }
  3126. // to save time we pass the EnableLanguage info directly
  3127. gg->EnableLanguagesFromGenerator(this->GetGlobalGenerator(), this);
  3128. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3129. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3130. cmStateEnums::INTERNAL);
  3131. } else {
  3132. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3133. cmStateEnums::INTERNAL);
  3134. }
  3135. if (cm.Configure() != 0) {
  3136. this->IssueMessage(MessageType::FATAL_ERROR,
  3137. "Failed to configure test project build system.");
  3138. cmSystemTools::SetFatalErrorOccured();
  3139. this->IsSourceFileTryCompile = false;
  3140. return 1;
  3141. }
  3142. if (cm.Generate() != 0) {
  3143. this->IssueMessage(MessageType::FATAL_ERROR,
  3144. "Failed to generate test project build system.");
  3145. cmSystemTools::SetFatalErrorOccured();
  3146. this->IsSourceFileTryCompile = false;
  3147. return 1;
  3148. }
  3149. // finally call the generator to actually build the resulting project
  3150. int ret = this->GetGlobalGenerator()->TryCompile(
  3151. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3152. this->IsSourceFileTryCompile = false;
  3153. return ret;
  3154. }
  3155. bool cmMakefile::GetIsSourceFileTryCompile() const
  3156. {
  3157. return this->IsSourceFileTryCompile;
  3158. }
  3159. cmake* cmMakefile::GetCMakeInstance() const
  3160. {
  3161. return this->GlobalGenerator->GetCMakeInstance();
  3162. }
  3163. cmMessenger* cmMakefile::GetMessenger() const
  3164. {
  3165. return this->GetCMakeInstance()->GetMessenger();
  3166. }
  3167. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3168. {
  3169. return this->GlobalGenerator;
  3170. }
  3171. #ifdef CMAKE_BUILD_WITH_CMAKE
  3172. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3173. {
  3174. if (this->GetCMakeInstance() &&
  3175. this->GetCMakeInstance()->GetVariableWatch()) {
  3176. return this->GetCMakeInstance()->GetVariableWatch();
  3177. }
  3178. return nullptr;
  3179. }
  3180. #endif
  3181. cmState* cmMakefile::GetState() const
  3182. {
  3183. return this->GetCMakeInstance()->GetState();
  3184. }
  3185. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3186. {
  3187. cmake* cm = this->GetCMakeInstance();
  3188. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3189. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3190. // directly be fed to the compiler, which will be confused.
  3191. return;
  3192. }
  3193. cm->UpdateProgress(message, s);
  3194. }
  3195. std::string cmMakefile::GetModulesFile(const std::string& filename,
  3196. bool& system) const
  3197. {
  3198. std::string result;
  3199. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3200. // and then decide based on the policy setting which one to return.
  3201. // See CMP0017 for more details.
  3202. // The specific problem was that KDE 4.5.0 installs a
  3203. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3204. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3205. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3206. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3207. // new features, which were not there in the version from kdelibs, and so
  3208. // failed ("
  3209. std::string moduleInCMakeRoot;
  3210. std::string moduleInCMakeModulePath;
  3211. // Always search in CMAKE_MODULE_PATH:
  3212. const char* cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3213. if (cmakeModulePath) {
  3214. std::vector<std::string> modulePath;
  3215. cmSystemTools::ExpandListArgument(cmakeModulePath, modulePath);
  3216. // Look through the possible module directories.
  3217. for (std::string itempl : modulePath) {
  3218. cmSystemTools::ConvertToUnixSlashes(itempl);
  3219. itempl += "/";
  3220. itempl += filename;
  3221. if (cmSystemTools::FileExists(itempl)) {
  3222. moduleInCMakeModulePath = itempl;
  3223. break;
  3224. }
  3225. }
  3226. }
  3227. // Always search in the standard modules location.
  3228. moduleInCMakeRoot = cmSystemTools::GetCMakeRoot();
  3229. moduleInCMakeRoot += "/Modules/";
  3230. moduleInCMakeRoot += filename;
  3231. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3232. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3233. moduleInCMakeRoot.clear();
  3234. }
  3235. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3236. // from which we are being called is located itself in CMAKE_ROOT, then
  3237. // prefer results from CMAKE_ROOT depending on the policy setting.
  3238. system = false;
  3239. result = moduleInCMakeModulePath;
  3240. if (result.empty()) {
  3241. system = true;
  3242. result = moduleInCMakeRoot;
  3243. }
  3244. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3245. const char* currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3246. std::string mods = cmSystemTools::GetCMakeRoot() + "/Modules/";
  3247. if (currentFile && cmSystemTools::IsSubDirectory(currentFile, mods)) {
  3248. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3249. case cmPolicies::WARN: {
  3250. std::ostringstream e;
  3251. /* clang-format off */
  3252. e << "File " << currentFile << " includes "
  3253. << moduleInCMakeModulePath
  3254. << " (found via CMAKE_MODULE_PATH) which shadows "
  3255. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3256. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3257. /* clang-format on */
  3258. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3259. CM_FALLTHROUGH;
  3260. }
  3261. case cmPolicies::OLD:
  3262. system = false;
  3263. result = moduleInCMakeModulePath;
  3264. break;
  3265. case cmPolicies::REQUIRED_IF_USED:
  3266. case cmPolicies::REQUIRED_ALWAYS:
  3267. case cmPolicies::NEW:
  3268. system = true;
  3269. result = moduleInCMakeRoot;
  3270. break;
  3271. }
  3272. }
  3273. }
  3274. return result;
  3275. }
  3276. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3277. bool atOnly, bool escapeQuotes) const
  3278. {
  3279. // Split input to handle one line at a time.
  3280. std::string::const_iterator lineStart = input.begin();
  3281. while (lineStart != input.end()) {
  3282. // Find the end of this line.
  3283. std::string::const_iterator lineEnd = lineStart;
  3284. while (lineEnd != input.end() && *lineEnd != '\n') {
  3285. ++lineEnd;
  3286. }
  3287. // Copy the line.
  3288. std::string line(lineStart, lineEnd);
  3289. // Skip the newline character.
  3290. bool haveNewline = (lineEnd != input.end());
  3291. if (haveNewline) {
  3292. ++lineEnd;
  3293. }
  3294. // Replace #cmakedefine instances.
  3295. if (this->cmDefineRegex.find(line)) {
  3296. const char* def = this->GetDefinition(this->cmDefineRegex.match(2));
  3297. if (!cmSystemTools::IsOff(def)) {
  3298. const std::string indentation = this->cmDefineRegex.match(1);
  3299. cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine",
  3300. "#" + indentation + "define");
  3301. output += line;
  3302. } else {
  3303. output += "/* #undef ";
  3304. output += this->cmDefineRegex.match(2);
  3305. output += " */";
  3306. }
  3307. } else if (this->cmDefine01Regex.find(line)) {
  3308. const std::string indentation = this->cmDefine01Regex.match(1);
  3309. const char* def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3310. cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine01",
  3311. "#" + indentation + "define");
  3312. output += line;
  3313. if (!cmSystemTools::IsOff(def)) {
  3314. output += " 1";
  3315. } else {
  3316. output += " 0";
  3317. }
  3318. } else {
  3319. output += line;
  3320. }
  3321. if (haveNewline) {
  3322. output += "\n";
  3323. }
  3324. // Move to the next line.
  3325. lineStart = lineEnd;
  3326. }
  3327. // Perform variable replacements.
  3328. const char* filename = nullptr;
  3329. long lineNumber = -1;
  3330. if (!this->Backtrace.Empty()) {
  3331. const auto& currentTrace = this->Backtrace.Top();
  3332. filename = currentTrace.FilePath.c_str();
  3333. lineNumber = currentTrace.Line;
  3334. }
  3335. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3336. lineNumber, true, true);
  3337. }
  3338. int cmMakefile::ConfigureFile(const char* infile, const char* outfile,
  3339. bool copyonly, 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. 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::CMP0065 &&
  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. }