cmMakefile.cxx 155 KB

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