cmMakefile.cxx 148 KB

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