cmMakefile.cxx 155 KB

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