cmMakefile.cxx 150 KB

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