cmMakefile.cxx 146 KB

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