cmMakefile.cxx 158 KB

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