cmMakefile.cxx 158 KB

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