cmMakefile.cxx 152 KB

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