cmMakefile.cxx 143 KB

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