cmMakefile.cxx 163 KB

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