cmMakefile.cxx 141 KB

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