cmMakefile.cxx 167 KB

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