cmMakefile.cxx 143 KB

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