cmMakefile.cxx 149 KB

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