cmMakefile.cxx 170 KB

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