cmMakefile.cxx 159 KB

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