cmMakefile.cxx 149 KB

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