cmMakefile.cxx 170 KB

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