cmMakefile.cxx 141 KB

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