cmMakefile.cxx 151 KB

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