1
0

cmMakefile.cxx 151 KB

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