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