cmMakefile.cxx 148 KB

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