cmMakefile.cxx 151 KB

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