cmMakefile.cxx 148 KB

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