cmMakefile.cxx 149 KB

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