cmMakefile.cxx 147 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700
  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, const char* value,
  1688. const char* 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->c_str();
  1702. }
  1703. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1704. std::vector<std::string>::size_type cc;
  1705. std::vector<std::string> files;
  1706. nvalue = value ? value : "";
  1707. cmExpandList(nvalue, files);
  1708. nvalue.clear();
  1709. for (cc = 0; cc < files.size(); cc++) {
  1710. if (!cmIsOff(files[cc])) {
  1711. files[cc] = cmSystemTools::CollapseFullPath(files[cc]);
  1712. }
  1713. if (cc > 0) {
  1714. nvalue += ";";
  1715. }
  1716. nvalue += files[cc];
  1717. }
  1718. this->GetCMakeInstance()->AddCacheEntry(name, nvalue, doc, type);
  1719. nvalue = *this->GetState()->GetInitializedCacheValue(name);
  1720. value = nvalue.c_str();
  1721. }
  1722. }
  1723. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1724. switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
  1725. case cmPolicies::WARN:
  1726. if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
  1727. this->IsNormalDefinitionSet(name)) {
  1728. this->IssueMessage(
  1729. MessageType::AUTHOR_WARNING,
  1730. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0126),
  1731. "\nFor compatibility with older versions of CMake, normal "
  1732. "variable \"",
  1733. name, "\" will be removed from the current scope."));
  1734. }
  1735. CM_FALLTHROUGH;
  1736. case cmPolicies::OLD:
  1737. // if there was a definition then remove it
  1738. this->StateSnapshot.RemoveDefinition(name);
  1739. break;
  1740. case cmPolicies::NEW:
  1741. case cmPolicies::REQUIRED_IF_USED:
  1742. case cmPolicies::REQUIRED_ALWAYS:
  1743. break;
  1744. }
  1745. }
  1746. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1747. {
  1748. this->StateSnapshot.GetDefinition(var);
  1749. }
  1750. bool cmMakefile::VariableInitialized(const std::string& var) const
  1751. {
  1752. return this->StateSnapshot.IsInitialized(var);
  1753. }
  1754. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1755. const char* sourceFilename) const
  1756. {
  1757. // check to see if we need to print a warning
  1758. // if strict mode is on and the variable has
  1759. // not been "cleared"/initialized with a set(foo ) call
  1760. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1761. !this->VariableInitialized(variable)) {
  1762. if (this->CheckSystemVars ||
  1763. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1764. std::ostringstream msg;
  1765. msg << "uninitialized variable \'" << variable << "\'";
  1766. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1767. }
  1768. }
  1769. }
  1770. void cmMakefile::RemoveDefinition(const std::string& name)
  1771. {
  1772. this->StateSnapshot.RemoveDefinition(name);
  1773. #ifndef CMAKE_BOOTSTRAP
  1774. cmVariableWatch* vv = this->GetVariableWatch();
  1775. if (vv) {
  1776. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1777. nullptr, this);
  1778. }
  1779. #endif
  1780. }
  1781. void cmMakefile::RemoveCacheDefinition(const std::string& name) const
  1782. {
  1783. this->GetState()->RemoveCacheEntry(name);
  1784. }
  1785. void cmMakefile::SetProjectName(std::string const& p)
  1786. {
  1787. this->StateSnapshot.SetProjectName(p);
  1788. }
  1789. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1790. {
  1791. // for these targets do not add anything
  1792. switch (target.GetType()) {
  1793. case cmStateEnums::UTILITY:
  1794. case cmStateEnums::GLOBAL_TARGET:
  1795. case cmStateEnums::INTERFACE_LIBRARY:
  1796. return;
  1797. default:;
  1798. }
  1799. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1800. cmList linkLibs{ *linkLibsProp };
  1801. for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
  1802. std::string libraryName = *j;
  1803. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1804. if (libraryName == "optimized") {
  1805. libType = OPTIMIZED_LibraryType;
  1806. ++j;
  1807. libraryName = *j;
  1808. } else if (libraryName == "debug") {
  1809. libType = DEBUG_LibraryType;
  1810. ++j;
  1811. libraryName = *j;
  1812. }
  1813. // This is equivalent to the target_link_libraries plain signature.
  1814. target.AddLinkLibrary(*this, libraryName, libType);
  1815. target.AppendProperty(
  1816. "INTERFACE_LINK_LIBRARIES",
  1817. target.GetDebugGeneratorExpressions(libraryName, libType));
  1818. }
  1819. }
  1820. }
  1821. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName,
  1822. bool globallyVisible)
  1823. {
  1824. this->AliasTargets[lname] = tgtName;
  1825. if (globallyVisible) {
  1826. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1827. }
  1828. }
  1829. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1830. cmStateEnums::TargetType type,
  1831. const std::vector<std::string>& srcs,
  1832. bool excludeFromAll)
  1833. {
  1834. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1835. type == cmStateEnums::SHARED_LIBRARY ||
  1836. type == cmStateEnums::MODULE_LIBRARY ||
  1837. type == cmStateEnums::OBJECT_LIBRARY ||
  1838. type == cmStateEnums::INTERFACE_LIBRARY);
  1839. cmTarget* target = this->AddNewTarget(type, lname);
  1840. // Clear its dependencies. Otherwise, dependencies might persist
  1841. // over changes in CMakeLists.txt, making the information stale and
  1842. // hence useless.
  1843. target->ClearDependencyInformation(*this);
  1844. if (excludeFromAll) {
  1845. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1846. }
  1847. target->AddSources(srcs);
  1848. this->AddGlobalLinkInformation(*target);
  1849. return target;
  1850. }
  1851. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1852. const std::vector<std::string>& srcs,
  1853. bool excludeFromAll)
  1854. {
  1855. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1856. if (excludeFromAll) {
  1857. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1858. }
  1859. target->AddSources(srcs);
  1860. this->AddGlobalLinkInformation(*target);
  1861. return target;
  1862. }
  1863. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1864. const std::string& name)
  1865. {
  1866. return &this->CreateNewTarget(name, type).first;
  1867. }
  1868. cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
  1869. const std::string& name)
  1870. {
  1871. return &this
  1872. ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
  1873. cmTarget::Visibility::Generated)
  1874. .first;
  1875. }
  1876. std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
  1877. const std::string& name, cmStateEnums::TargetType type,
  1878. cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
  1879. {
  1880. auto ib =
  1881. this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
  1882. auto it = ib.first;
  1883. if (!ib.second) {
  1884. return std::make_pair(std::ref(it->second), false);
  1885. }
  1886. this->OrderedTargets.push_back(&it->second);
  1887. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1888. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1889. return std::make_pair(std::ref(it->second), true);
  1890. }
  1891. cmTarget* cmMakefile::AddNewUtilityTarget(const std::string& utilityName,
  1892. bool excludeFromAll)
  1893. {
  1894. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1895. if (excludeFromAll) {
  1896. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1897. }
  1898. return target;
  1899. }
  1900. namespace {
  1901. }
  1902. #if !defined(CMAKE_BOOTSTRAP)
  1903. cmSourceGroup* cmMakefile::GetSourceGroup(
  1904. const std::vector<std::string>& name) const
  1905. {
  1906. cmSourceGroup* sg = nullptr;
  1907. // first look for source group starting with the same as the one we want
  1908. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1909. std::string const& sgName = srcGroup.GetName();
  1910. if (sgName == name[0]) {
  1911. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1912. break;
  1913. }
  1914. }
  1915. if (sg != nullptr) {
  1916. // iterate through its children to find match source group
  1917. for (unsigned int i = 1; i < name.size(); ++i) {
  1918. sg = sg->LookupChild(name[i]);
  1919. if (sg == nullptr) {
  1920. break;
  1921. }
  1922. }
  1923. }
  1924. return sg;
  1925. }
  1926. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  1927. {
  1928. std::vector<std::string> nameVector;
  1929. nameVector.push_back(name);
  1930. this->AddSourceGroup(nameVector, regex);
  1931. }
  1932. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  1933. const char* regex)
  1934. {
  1935. cmSourceGroup* sg = nullptr;
  1936. std::vector<std::string> currentName;
  1937. int i = 0;
  1938. const int lastElement = static_cast<int>(name.size() - 1);
  1939. for (i = lastElement; i >= 0; --i) {
  1940. currentName.assign(name.begin(), name.begin() + i + 1);
  1941. sg = this->GetSourceGroup(currentName);
  1942. if (sg != nullptr) {
  1943. break;
  1944. }
  1945. }
  1946. // i now contains the index of the last found component
  1947. if (i == lastElement) {
  1948. // group already exists, replace its regular expression
  1949. if (regex && sg) {
  1950. // We only want to set the regular expression. If there are already
  1951. // source files in the group, we don't want to remove them.
  1952. sg->SetGroupRegex(regex);
  1953. }
  1954. return;
  1955. }
  1956. if (i == -1) {
  1957. // group does not exist nor belong to any existing group
  1958. // add its first component
  1959. this->SourceGroups.emplace_back(name[0], regex);
  1960. sg = this->GetSourceGroup(currentName);
  1961. i = 0; // last component found
  1962. }
  1963. if (!sg) {
  1964. cmSystemTools::Error("Could not create source group ");
  1965. return;
  1966. }
  1967. // build the whole source group path
  1968. for (++i; i <= lastElement; ++i) {
  1969. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  1970. sg = sg->LookupChild(name[i]);
  1971. }
  1972. sg->SetGroupRegex(regex);
  1973. }
  1974. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  1975. const std::vector<std::string>& folders)
  1976. {
  1977. cmSourceGroup* sg = this->GetSourceGroup(folders);
  1978. if (sg == nullptr) {
  1979. this->AddSourceGroup(folders);
  1980. sg = this->GetSourceGroup(folders);
  1981. }
  1982. return sg;
  1983. }
  1984. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  1985. {
  1986. std::string delimiters;
  1987. if (cmValue p = this->GetDefinition("SOURCE_GROUP_DELIMITER")) {
  1988. delimiters = *p;
  1989. } else {
  1990. delimiters = "/\\";
  1991. }
  1992. return this->GetOrCreateSourceGroup(cmTokenize(name, delimiters));
  1993. }
  1994. /**
  1995. * Find a source group whose regular expression matches the filename
  1996. * part of the given source name. Search backward through the list of
  1997. * source groups, and take the first matching group found. This way
  1998. * non-inherited SOURCE_GROUP commands will have precedence over
  1999. * inherited ones.
  2000. */
  2001. cmSourceGroup* cmMakefile::FindSourceGroup(
  2002. const std::string& source, std::vector<cmSourceGroup>& groups) const
  2003. {
  2004. // First search for a group that lists the file explicitly.
  2005. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2006. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  2007. if (result) {
  2008. return result;
  2009. }
  2010. }
  2011. // Now search for a group whose regex matches the file.
  2012. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2013. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  2014. if (result) {
  2015. return result;
  2016. }
  2017. }
  2018. // Shouldn't get here, but just in case, return the default group.
  2019. return groups.data();
  2020. }
  2021. #endif
  2022. static bool mightExpandVariablesCMP0019(const char* s)
  2023. {
  2024. return s && *s && strstr(s, "${") && strchr(s, '}');
  2025. }
  2026. void cmMakefile::ExpandVariablesCMP0019()
  2027. {
  2028. // Drop this ancient compatibility behavior with a policy.
  2029. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  2030. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  2031. return;
  2032. }
  2033. std::ostringstream w;
  2034. cmValue includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  2035. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2036. std::string dirs = *includeDirs;
  2037. this->ExpandVariablesInString(dirs, true, true);
  2038. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2039. /* clang-format off */
  2040. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  2041. << " " << *includeDirs << "\n"
  2042. << "as\n"
  2043. << " " << dirs << "\n";
  2044. /* clang-format on */
  2045. }
  2046. this->SetProperty("INCLUDE_DIRECTORIES", dirs);
  2047. }
  2048. // Also for each target's INCLUDE_DIRECTORIES property:
  2049. for (auto& target : this->Targets) {
  2050. cmTarget& t = target.second;
  2051. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  2052. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  2053. continue;
  2054. }
  2055. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  2056. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2057. std::string dirs = *includeDirs;
  2058. this->ExpandVariablesInString(dirs, true, true);
  2059. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2060. /* clang-format off */
  2061. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  2062. << " " << *includeDirs << "\n"
  2063. << "as\n"
  2064. << " " << dirs << "\n";
  2065. /* clang-format on */
  2066. }
  2067. t.SetProperty("INCLUDE_DIRECTORIES", dirs);
  2068. }
  2069. }
  2070. if (cmValue linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2071. if (mightExpandVariablesCMP0019(linkDirsProp->c_str())) {
  2072. std::string d = *linkDirsProp;
  2073. const std::string orig = d;
  2074. this->ExpandVariablesInString(d, true, true);
  2075. if (pol == cmPolicies::WARN && d != orig) {
  2076. /* clang-format off */
  2077. w << "Evaluated link directories\n"
  2078. << " " << orig << "\n"
  2079. << "as\n"
  2080. << " " << d << "\n";
  2081. /* clang-format on */
  2082. }
  2083. }
  2084. }
  2085. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2086. cmList linkLibs{ *linkLibsProp };
  2087. for (auto l = linkLibs.begin(); l != linkLibs.end(); ++l) {
  2088. std::string libName = *l;
  2089. if (libName == "optimized"_s || libName == "debug"_s) {
  2090. ++l;
  2091. libName = *l;
  2092. }
  2093. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2094. const std::string orig = libName;
  2095. this->ExpandVariablesInString(libName, true, true);
  2096. if (pol == cmPolicies::WARN && libName != orig) {
  2097. /* clang-format off */
  2098. w << "Evaluated link library\n"
  2099. << " " << orig << "\n"
  2100. << "as\n"
  2101. << " " << libName << "\n";
  2102. /* clang-format on */
  2103. }
  2104. }
  2105. }
  2106. }
  2107. if (!w.str().empty()) {
  2108. std::ostringstream m;
  2109. /* clang-format off */
  2110. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2111. << "\n"
  2112. << "The following variable evaluations were encountered:\n"
  2113. << w.str();
  2114. /* clang-format on */
  2115. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2116. m.str(), this->Backtrace);
  2117. }
  2118. }
  2119. bool cmMakefile::IsOn(const std::string& name) const
  2120. {
  2121. return cmIsOn(this->GetDefinition(name));
  2122. }
  2123. bool cmMakefile::IsSet(const std::string& name) const
  2124. {
  2125. cmValue value = this->GetDefinition(name);
  2126. if (!value) {
  2127. return false;
  2128. }
  2129. if (value->empty()) {
  2130. return false;
  2131. }
  2132. if (cmIsNOTFOUND(*value)) {
  2133. return false;
  2134. }
  2135. return true;
  2136. }
  2137. bool cmMakefile::PlatformIs32Bit() const
  2138. {
  2139. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2140. if (*plat_abi == "ELF X32") {
  2141. return false;
  2142. }
  2143. }
  2144. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2145. return atoi(sizeof_dptr->c_str()) == 4;
  2146. }
  2147. return false;
  2148. }
  2149. bool cmMakefile::PlatformIs64Bit() const
  2150. {
  2151. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2152. return atoi(sizeof_dptr->c_str()) == 8;
  2153. }
  2154. return false;
  2155. }
  2156. bool cmMakefile::PlatformIsx32() const
  2157. {
  2158. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2159. if (*plat_abi == "ELF X32") {
  2160. return true;
  2161. }
  2162. }
  2163. return false;
  2164. }
  2165. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2166. {
  2167. std::string sdkRoot;
  2168. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2169. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2170. struct
  2171. {
  2172. std::string name;
  2173. AppleSDK sdk;
  2174. } const sdkDatabase[]{
  2175. { "appletvos", AppleSDK::AppleTVOS },
  2176. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2177. { "iphoneos", AppleSDK::IPhoneOS },
  2178. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2179. { "watchos", AppleSDK::WatchOS },
  2180. { "watchsimulator", AppleSDK::WatchSimulator },
  2181. };
  2182. for (auto const& entry : sdkDatabase) {
  2183. if (cmHasPrefix(sdkRoot, entry.name) ||
  2184. sdkRoot.find(std::string("/") + entry.name) != std::string::npos) {
  2185. return entry.sdk;
  2186. }
  2187. }
  2188. return AppleSDK::MacOS;
  2189. }
  2190. bool cmMakefile::PlatformIsAppleEmbedded() const
  2191. {
  2192. return this->GetAppleSDKType() != AppleSDK::MacOS;
  2193. }
  2194. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  2195. {
  2196. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  2197. }
  2198. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2199. {
  2200. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2201. if (!language.empty()) {
  2202. name += "_";
  2203. name += language;
  2204. }
  2205. name += "_FLAG";
  2206. return this->GetDefinition(name).GetCStr();
  2207. }
  2208. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2209. {
  2210. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2211. return true;
  2212. }
  2213. // If we are doing an in-source build, then the test will always fail
  2214. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2215. this->GetHomeOutputDirectory())) {
  2216. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2217. }
  2218. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2219. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2220. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2221. }
  2222. const std::string& cmMakefile::GetRequiredDefinition(
  2223. const std::string& name) const
  2224. {
  2225. static std::string const empty;
  2226. cmValue def = this->GetDefinition(name);
  2227. if (!def) {
  2228. cmSystemTools::Error("Error required internal CMake variable not "
  2229. "set, cmake may not be built correctly.\n"
  2230. "Missing variable is:\n" +
  2231. name);
  2232. return empty;
  2233. }
  2234. return *def;
  2235. }
  2236. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2237. {
  2238. cmValue def = this->StateSnapshot.GetDefinition(name);
  2239. if (!def) {
  2240. def = this->GetState()->GetInitializedCacheValue(name);
  2241. }
  2242. #ifndef CMAKE_BOOTSTRAP
  2243. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2244. if (!def) {
  2245. vv->VariableAccessed(
  2246. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2247. }
  2248. }
  2249. #endif
  2250. return def != nullptr;
  2251. }
  2252. bool cmMakefile::IsNormalDefinitionSet(const std::string& name) const
  2253. {
  2254. cmValue def = this->StateSnapshot.GetDefinition(name);
  2255. #ifndef CMAKE_BOOTSTRAP
  2256. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2257. if (!def) {
  2258. vv->VariableAccessed(
  2259. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2260. }
  2261. }
  2262. #endif
  2263. return def != nullptr;
  2264. }
  2265. cmValue cmMakefile::GetDefinition(const std::string& name) const
  2266. {
  2267. cmValue def = this->StateSnapshot.GetDefinition(name);
  2268. if (!def) {
  2269. def = this->GetState()->GetInitializedCacheValue(name);
  2270. }
  2271. #ifndef CMAKE_BOOTSTRAP
  2272. cmVariableWatch* vv = this->GetVariableWatch();
  2273. if (vv && !this->SuppressSideEffects) {
  2274. bool const watch_function_executed =
  2275. vv->VariableAccessed(name,
  2276. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2277. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2278. def.GetCStr(), this);
  2279. if (watch_function_executed) {
  2280. // A callback was executed and may have caused re-allocation of the
  2281. // variable storage. Look it up again for now.
  2282. // FIXME: Refactor variable storage to avoid this problem.
  2283. def = this->StateSnapshot.GetDefinition(name);
  2284. if (!def) {
  2285. def = this->GetState()->GetInitializedCacheValue(name);
  2286. }
  2287. }
  2288. }
  2289. #endif
  2290. return def;
  2291. }
  2292. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2293. {
  2294. return this->GetDefinition(name);
  2295. }
  2296. bool cmMakefile::GetDefExpandList(const std::string& name,
  2297. std::vector<std::string>& out,
  2298. bool emptyArgs) const
  2299. {
  2300. cmValue def = this->GetDefinition(name);
  2301. if (!def) {
  2302. return false;
  2303. }
  2304. cmExpandList(*def, out, emptyArgs);
  2305. return true;
  2306. }
  2307. std::vector<std::string> cmMakefile::GetDefinitions() const
  2308. {
  2309. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2310. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2311. std::sort(res.begin(), res.end());
  2312. return res;
  2313. }
  2314. const std::string& cmMakefile::ExpandVariablesInString(
  2315. std::string& source) const
  2316. {
  2317. return this->ExpandVariablesInString(source, false, false);
  2318. }
  2319. const std::string& cmMakefile::ExpandVariablesInString(
  2320. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2321. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2322. {
  2323. bool compareResults = false;
  2324. MessageType mtype = MessageType::LOG;
  2325. std::string errorstr;
  2326. std::string original;
  2327. // Sanity check the @ONLY mode.
  2328. if (atOnly && (!noEscapes || !removeEmpty)) {
  2329. // This case should never be called. At-only is for
  2330. // configure-file/string which always does no escapes.
  2331. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2332. "ExpandVariablesInString @ONLY called "
  2333. "on something with escapes.");
  2334. return source;
  2335. }
  2336. // Variables used in the WARN case.
  2337. std::string newResult;
  2338. std::string newErrorstr;
  2339. MessageType newError = MessageType::LOG;
  2340. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2341. case cmPolicies::WARN: {
  2342. // Save the original string for the warning.
  2343. original = source;
  2344. newResult = source;
  2345. compareResults = true;
  2346. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2347. // dereferences since the OLD behavior is still what is actually used.
  2348. this->SuppressSideEffects = true;
  2349. newError = this->ExpandVariablesInStringNew(
  2350. newErrorstr, newResult, escapeQuotes, noEscapes, atOnly, filename,
  2351. line, replaceAt);
  2352. this->SuppressSideEffects = false;
  2353. CM_FALLTHROUGH;
  2354. }
  2355. case cmPolicies::OLD:
  2356. mtype = this->ExpandVariablesInStringOld(errorstr, source, escapeQuotes,
  2357. noEscapes, atOnly, filename,
  2358. line, removeEmpty, true);
  2359. break;
  2360. case cmPolicies::REQUIRED_IF_USED:
  2361. case cmPolicies::REQUIRED_ALWAYS:
  2362. // Messaging here would be *very* verbose.
  2363. case cmPolicies::NEW:
  2364. mtype = this->ExpandVariablesInStringNew(errorstr, source, escapeQuotes,
  2365. noEscapes, atOnly, filename,
  2366. line, replaceAt);
  2367. break;
  2368. }
  2369. // If it's an error in either case, just report the error...
  2370. if (mtype != MessageType::LOG) {
  2371. if (mtype == MessageType::FATAL_ERROR) {
  2372. cmSystemTools::SetFatalErrorOccurred();
  2373. }
  2374. this->IssueMessage(mtype, errorstr);
  2375. }
  2376. // ...otherwise, see if there's a difference that needs to be warned about.
  2377. else if (compareResults && (newResult != source || newError != mtype)) {
  2378. std::string msg =
  2379. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0053), '\n');
  2380. std::string msg_input = original;
  2381. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2382. msg += "For input:\n '";
  2383. msg += msg_input;
  2384. msg += "'\n";
  2385. std::string msg_old = source;
  2386. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2387. msg += "the old evaluation rules produce:\n '";
  2388. msg += msg_old;
  2389. msg += "'\n";
  2390. if (newError == mtype) {
  2391. std::string msg_new = newResult;
  2392. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2393. msg += "but the new evaluation rules produce:\n '";
  2394. msg += msg_new;
  2395. msg += "'\n";
  2396. } else {
  2397. std::string msg_err = newErrorstr;
  2398. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2399. msg += "but the new evaluation rules produce an error:\n ";
  2400. msg += msg_err;
  2401. msg += "\n";
  2402. }
  2403. msg +=
  2404. "Using the old result for compatibility since the policy is not set.";
  2405. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2406. }
  2407. return source;
  2408. }
  2409. MessageType cmMakefile::ExpandVariablesInStringOld(
  2410. std::string& errorstr, std::string& source, bool escapeQuotes,
  2411. bool noEscapes, bool atOnly, const char* filename, long line,
  2412. bool removeEmpty, bool replaceAt) const
  2413. {
  2414. // Fast path strings without any special characters.
  2415. if (source.find_first_of("$@\\") == std::string::npos) {
  2416. return MessageType::LOG;
  2417. }
  2418. // Special-case the @ONLY mode.
  2419. if (atOnly) {
  2420. // Store an original copy of the input.
  2421. std::string input = source;
  2422. // Start with empty output.
  2423. source.clear();
  2424. // Look for one @VAR@ at a time.
  2425. const char* in = input.c_str();
  2426. while (this->cmAtVarRegex.find(in)) {
  2427. // Get the range of the string to replace.
  2428. const char* first = in + this->cmAtVarRegex.start();
  2429. const char* last = in + this->cmAtVarRegex.end();
  2430. // Store the unchanged part of the string now.
  2431. source.append(in, first - in);
  2432. // Lookup the definition of VAR.
  2433. std::string var(first + 1, last - first - 2);
  2434. if (cmValue val = this->GetDefinition(var)) {
  2435. // Store the value in the output escaping as requested.
  2436. if (escapeQuotes) {
  2437. source.append(cmEscapeQuotes(*val));
  2438. } else {
  2439. source.append(*val);
  2440. }
  2441. }
  2442. // Continue looking for @VAR@ further along the string.
  2443. in = last;
  2444. }
  2445. // Append the rest of the unchanged part of the string.
  2446. source.append(in);
  2447. return MessageType::LOG;
  2448. }
  2449. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2450. // with GetDefinition(), if not found in the map, nothing is expanded.
  2451. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2452. // the current environment variables.
  2453. cmCommandArgumentParserHelper parser;
  2454. parser.SetMakefile(this);
  2455. parser.SetLineFile(line, filename);
  2456. parser.SetEscapeQuotes(escapeQuotes);
  2457. parser.SetNoEscapeMode(noEscapes);
  2458. parser.SetReplaceAtSyntax(replaceAt);
  2459. parser.SetRemoveEmpty(removeEmpty);
  2460. int res = parser.ParseString(source, 0);
  2461. const char* emsg = parser.GetError();
  2462. MessageType mtype = MessageType::LOG;
  2463. if (res && !emsg[0]) {
  2464. source = parser.GetResult();
  2465. } else {
  2466. // Construct the main error message.
  2467. std::ostringstream error;
  2468. error << "Syntax error in cmake code ";
  2469. if (filename && line > 0) {
  2470. // This filename and line number may be more specific than the
  2471. // command context because one command invocation can have
  2472. // arguments on multiple lines.
  2473. error << "at\n"
  2474. << " " << filename << ":" << line << "\n";
  2475. }
  2476. error << "when parsing string\n"
  2477. << " " << source << "\n";
  2478. error << emsg;
  2479. // If the parser failed ("res" is false) then this is a real
  2480. // argument parsing error, so the policy applies. Otherwise the
  2481. // parser reported an error message without failing because the
  2482. // helper implementation is unhappy, which has always reported an
  2483. // error.
  2484. mtype = MessageType::FATAL_ERROR;
  2485. if (!res) {
  2486. // This is a real argument parsing error. Use policy CMP0010 to
  2487. // decide whether it is an error.
  2488. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2489. case cmPolicies::WARN:
  2490. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2491. CM_FALLTHROUGH;
  2492. case cmPolicies::OLD:
  2493. // OLD behavior is to just warn and continue.
  2494. mtype = MessageType::AUTHOR_WARNING;
  2495. break;
  2496. case cmPolicies::REQUIRED_IF_USED:
  2497. case cmPolicies::REQUIRED_ALWAYS:
  2498. error << "\n"
  2499. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2500. break;
  2501. case cmPolicies::NEW:
  2502. // NEW behavior is to report the error.
  2503. break;
  2504. }
  2505. }
  2506. errorstr = error.str();
  2507. }
  2508. return mtype;
  2509. }
  2510. enum t_domain
  2511. {
  2512. NORMAL,
  2513. ENVIRONMENT,
  2514. CACHE
  2515. };
  2516. struct t_lookup
  2517. {
  2518. t_domain domain = NORMAL;
  2519. size_t loc = 0;
  2520. };
  2521. bool cmMakefile::IsProjectFile(const char* filename) const
  2522. {
  2523. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2524. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2525. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2526. }
  2527. size_t cmMakefile::GetRecursionDepthLimit() const
  2528. {
  2529. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2530. if (cmValue depthStr =
  2531. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2532. unsigned long depthUL;
  2533. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2534. depth = depthUL;
  2535. }
  2536. } else if (cm::optional<std::string> depthEnv =
  2537. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2538. unsigned long depthUL;
  2539. if (cmStrToULong(*depthEnv, &depthUL)) {
  2540. depth = depthUL;
  2541. }
  2542. }
  2543. return depth;
  2544. }
  2545. size_t cmMakefile::GetRecursionDepth() const
  2546. {
  2547. return this->RecursionDepth;
  2548. }
  2549. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2550. {
  2551. this->RecursionDepth = recursionDepth;
  2552. }
  2553. std::string cmMakefile::NewDeferId() const
  2554. {
  2555. return this->GetGlobalGenerator()->NewDeferId();
  2556. }
  2557. bool cmMakefile::DeferCall(std::string id, std::string file,
  2558. cmListFileFunction lff)
  2559. {
  2560. if (!this->Defer) {
  2561. return false;
  2562. }
  2563. this->Defer->Commands.emplace_back(
  2564. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2565. return true;
  2566. }
  2567. bool cmMakefile::DeferCancelCall(std::string const& id)
  2568. {
  2569. if (!this->Defer) {
  2570. return false;
  2571. }
  2572. for (DeferCommand& dc : this->Defer->Commands) {
  2573. if (dc.Id == id) {
  2574. dc.Id.clear();
  2575. }
  2576. }
  2577. return true;
  2578. }
  2579. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2580. {
  2581. cm::optional<std::string> ids;
  2582. if (this->Defer) {
  2583. ids = cmJoin(
  2584. cmMakeRange(this->Defer->Commands)
  2585. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2586. .transform(
  2587. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }),
  2588. ";");
  2589. }
  2590. return ids;
  2591. }
  2592. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2593. {
  2594. cm::optional<std::string> call;
  2595. if (this->Defer) {
  2596. std::string tmp;
  2597. for (DeferCommand const& dc : this->Defer->Commands) {
  2598. if (dc.Id == id) {
  2599. tmp = dc.Command.OriginalName();
  2600. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2601. tmp = cmStrCat(tmp, ';', arg.Value);
  2602. }
  2603. break;
  2604. }
  2605. }
  2606. call = std::move(tmp);
  2607. }
  2608. return call;
  2609. }
  2610. MessageType cmMakefile::ExpandVariablesInStringNew(
  2611. std::string& errorstr, std::string& source, bool escapeQuotes,
  2612. bool noEscapes, bool atOnly, const char* filename, long line,
  2613. bool replaceAt) const
  2614. {
  2615. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2616. // with GetDefinition(), if not found in the map, nothing is expanded.
  2617. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2618. // the current environment variables.
  2619. const char* in = source.c_str();
  2620. const char* last = in;
  2621. std::string result;
  2622. result.reserve(source.size());
  2623. std::vector<t_lookup> openstack;
  2624. bool error = false;
  2625. bool done = false;
  2626. MessageType mtype = MessageType::LOG;
  2627. cmState* state = this->GetCMakeInstance()->GetState();
  2628. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2629. do {
  2630. char inc = *in;
  2631. switch (inc) {
  2632. case '}':
  2633. if (!openstack.empty()) {
  2634. t_lookup var = openstack.back();
  2635. openstack.pop_back();
  2636. result.append(last, in - last);
  2637. std::string const& lookup = result.substr(var.loc);
  2638. cmValue value = nullptr;
  2639. std::string varresult;
  2640. std::string svalue;
  2641. switch (var.domain) {
  2642. case NORMAL:
  2643. if (filename && lookup == lineVar) {
  2644. cmListFileContext const& top = this->Backtrace.Top();
  2645. if (top.DeferId) {
  2646. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2647. } else {
  2648. varresult = std::to_string(line);
  2649. }
  2650. } else {
  2651. value = this->GetDefinition(lookup);
  2652. }
  2653. break;
  2654. case ENVIRONMENT:
  2655. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2656. value = cmValue(svalue);
  2657. }
  2658. break;
  2659. case CACHE:
  2660. value = state->GetCacheEntryValue(lookup);
  2661. break;
  2662. }
  2663. // Get the string we're meant to append to.
  2664. if (value) {
  2665. if (escapeQuotes) {
  2666. varresult = cmEscapeQuotes(*value);
  2667. } else {
  2668. varresult = *value;
  2669. }
  2670. } else if (!this->SuppressSideEffects) {
  2671. this->MaybeWarnUninitialized(lookup, filename);
  2672. }
  2673. result.replace(var.loc, result.size() - var.loc, varresult);
  2674. // Start looking from here on out.
  2675. last = in + 1;
  2676. }
  2677. break;
  2678. case '$':
  2679. if (!atOnly) {
  2680. t_lookup lookup;
  2681. const char* next = in + 1;
  2682. const char* start = nullptr;
  2683. char nextc = *next;
  2684. if (nextc == '{') {
  2685. // Looking for a variable.
  2686. start = in + 2;
  2687. lookup.domain = NORMAL;
  2688. } else if (nextc == '<') {
  2689. } else if (!nextc) {
  2690. result.append(last, next - last);
  2691. last = next;
  2692. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2693. // Looking for an environment variable.
  2694. start = in + 5;
  2695. lookup.domain = ENVIRONMENT;
  2696. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2697. // Looking for a cache variable.
  2698. start = in + 7;
  2699. lookup.domain = CACHE;
  2700. } else {
  2701. if (this->cmNamedCurly.find(next)) {
  2702. errorstr = "Syntax $" +
  2703. std::string(next, this->cmNamedCurly.end()) +
  2704. "{} is not supported. Only ${}, $ENV{}, "
  2705. "and $CACHE{} are allowed.";
  2706. mtype = MessageType::FATAL_ERROR;
  2707. error = true;
  2708. }
  2709. }
  2710. if (start) {
  2711. result.append(last, in - last);
  2712. last = start;
  2713. in = start - 1;
  2714. lookup.loc = result.size();
  2715. openstack.push_back(lookup);
  2716. }
  2717. break;
  2718. }
  2719. CM_FALLTHROUGH;
  2720. case '\\':
  2721. if (!noEscapes) {
  2722. const char* next = in + 1;
  2723. char nextc = *next;
  2724. if (nextc == 't') {
  2725. result.append(last, in - last);
  2726. result.append("\t");
  2727. last = next + 1;
  2728. } else if (nextc == 'n') {
  2729. result.append(last, in - last);
  2730. result.append("\n");
  2731. last = next + 1;
  2732. } else if (nextc == 'r') {
  2733. result.append(last, in - last);
  2734. result.append("\r");
  2735. last = next + 1;
  2736. } else if (nextc == ';' && openstack.empty()) {
  2737. // Handled in ExpandListArgument; pass the backslash literally.
  2738. } else if (isalnum(nextc) || nextc == '\0') {
  2739. errorstr += "Invalid character escape '\\";
  2740. if (nextc) {
  2741. errorstr += nextc;
  2742. errorstr += "'.";
  2743. } else {
  2744. errorstr += "' (at end of input).";
  2745. }
  2746. error = true;
  2747. } else {
  2748. // Take what we've found so far, skipping the escape character.
  2749. result.append(last, in - last);
  2750. // Start tracking from the next character.
  2751. last = in + 1;
  2752. }
  2753. // Skip the next character since it was escaped, but don't read past
  2754. // the end of the string.
  2755. if (*last) {
  2756. ++in;
  2757. }
  2758. }
  2759. break;
  2760. case '\n':
  2761. // Onto the next line.
  2762. ++line;
  2763. break;
  2764. case '\0':
  2765. done = true;
  2766. break;
  2767. case '@':
  2768. if (replaceAt) {
  2769. const char* nextAt = strchr(in + 1, '@');
  2770. if (nextAt && nextAt != in + 1 &&
  2771. nextAt ==
  2772. in + 1 +
  2773. strspn(in + 1,
  2774. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2775. "abcdefghijklmnopqrstuvwxyz"
  2776. "0123456789/_.+-")) {
  2777. std::string variable(in + 1, nextAt - in - 1);
  2778. std::string varresult;
  2779. if (filename && variable == lineVar) {
  2780. varresult = std::to_string(line);
  2781. } else {
  2782. cmValue def = this->GetDefinition(variable);
  2783. if (def) {
  2784. varresult = *def;
  2785. } else if (!this->SuppressSideEffects) {
  2786. this->MaybeWarnUninitialized(variable, filename);
  2787. }
  2788. }
  2789. if (escapeQuotes) {
  2790. varresult = cmEscapeQuotes(varresult);
  2791. }
  2792. // Skip over the variable.
  2793. result.append(last, in - last);
  2794. result.append(varresult);
  2795. in = nextAt;
  2796. last = in + 1;
  2797. break;
  2798. }
  2799. }
  2800. // Failed to find a valid @ expansion; treat it as literal.
  2801. CM_FALLTHROUGH;
  2802. default: {
  2803. if (!openstack.empty() &&
  2804. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2805. inc == '+' || inc == '-')) {
  2806. errorstr += "Invalid character (\'";
  2807. errorstr += inc;
  2808. result.append(last, in - last);
  2809. errorstr += "\') in a variable name: "
  2810. "'" +
  2811. result.substr(openstack.back().loc) + "'";
  2812. mtype = MessageType::FATAL_ERROR;
  2813. error = true;
  2814. }
  2815. break;
  2816. }
  2817. }
  2818. // Look at the next character.
  2819. } while (!error && !done && *++in);
  2820. // Check for open variable references yet.
  2821. if (!error && !openstack.empty()) {
  2822. // There's an open variable reference waiting. Policy CMP0010 flags
  2823. // whether this is an error or not. The new parser now enforces
  2824. // CMP0010 as well.
  2825. errorstr += "There is an unterminated variable reference.";
  2826. error = true;
  2827. }
  2828. if (error) {
  2829. std::ostringstream emsg;
  2830. emsg << "Syntax error in cmake code ";
  2831. if (filename) {
  2832. // This filename and line number may be more specific than the
  2833. // command context because one command invocation can have
  2834. // arguments on multiple lines.
  2835. emsg << "at\n"
  2836. << " " << filename << ":" << line << "\n";
  2837. }
  2838. emsg << "when parsing string\n"
  2839. << " " << source << "\n";
  2840. emsg << errorstr;
  2841. mtype = MessageType::FATAL_ERROR;
  2842. errorstr = emsg.str();
  2843. } else {
  2844. // Append the rest of the unchanged part of the string.
  2845. result.append(last);
  2846. source = result;
  2847. }
  2848. return mtype;
  2849. }
  2850. void cmMakefile::RemoveVariablesInString(std::string& source,
  2851. bool atOnly) const
  2852. {
  2853. if (!atOnly) {
  2854. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2855. while (var.find(source)) {
  2856. source.erase(var.start(), var.end() - var.start());
  2857. }
  2858. }
  2859. if (!atOnly) {
  2860. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2861. while (varb.find(source)) {
  2862. source.erase(varb.start(), varb.end() - varb.start());
  2863. }
  2864. }
  2865. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2866. while (var2.find(source)) {
  2867. source.erase(var2.start(), var2.end() - var2.start());
  2868. }
  2869. }
  2870. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2871. {
  2872. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2873. return;
  2874. }
  2875. std::string initConfigs;
  2876. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2877. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2878. initConfigs = genDefault;
  2879. }
  2880. this->AddCacheDefinition(
  2881. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2882. "Semicolon separated list of supported configuration types, "
  2883. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2884. "anything else will be ignored.",
  2885. cmStateEnums::STRING);
  2886. }
  2887. std::string cmMakefile::GetDefaultConfiguration() const
  2888. {
  2889. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2890. return std::string{};
  2891. }
  2892. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2893. }
  2894. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2895. GeneratorConfigQuery mode) const
  2896. {
  2897. std::vector<std::string> configs;
  2898. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2899. this->GetDefExpandList("CMAKE_CONFIGURATION_TYPES", configs);
  2900. } else if (mode != cmMakefile::OnlyMultiConfig) {
  2901. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2902. if (!buildType.empty()) {
  2903. configs.emplace_back(buildType);
  2904. }
  2905. }
  2906. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  2907. configs.emplace_back();
  2908. }
  2909. return configs;
  2910. }
  2911. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  2912. cmExecutionStatus& status)
  2913. {
  2914. // if there are no blockers get out of here
  2915. if (this->FunctionBlockers.empty()) {
  2916. return false;
  2917. }
  2918. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  2919. }
  2920. void cmMakefile::PushFunctionBlockerBarrier()
  2921. {
  2922. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2923. }
  2924. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2925. {
  2926. // Remove any extra entries pushed on the barrier.
  2927. FunctionBlockersType::size_type barrier =
  2928. this->FunctionBlockerBarriers.back();
  2929. while (this->FunctionBlockers.size() > barrier) {
  2930. std::unique_ptr<cmFunctionBlocker> fb(
  2931. std::move(this->FunctionBlockers.top()));
  2932. this->FunctionBlockers.pop();
  2933. if (reportError) {
  2934. // Report the context in which the unclosed block was opened.
  2935. cmListFileContext const& lfc = fb->GetStartingContext();
  2936. std::ostringstream e;
  2937. /* clang-format off */
  2938. e << "A logical block opening on the line\n"
  2939. << " " << lfc << "\n"
  2940. << "is not closed.";
  2941. /* clang-format on */
  2942. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2943. reportError = false;
  2944. }
  2945. }
  2946. // Remove the barrier.
  2947. this->FunctionBlockerBarriers.pop_back();
  2948. }
  2949. void cmMakefile::PushLoopBlock()
  2950. {
  2951. assert(!this->LoopBlockCounter.empty());
  2952. this->LoopBlockCounter.top()++;
  2953. }
  2954. void cmMakefile::PopLoopBlock()
  2955. {
  2956. assert(!this->LoopBlockCounter.empty());
  2957. assert(this->LoopBlockCounter.top() > 0);
  2958. this->LoopBlockCounter.top()--;
  2959. }
  2960. void cmMakefile::PushLoopBlockBarrier()
  2961. {
  2962. this->LoopBlockCounter.push(0);
  2963. }
  2964. void cmMakefile::PopLoopBlockBarrier()
  2965. {
  2966. assert(!this->LoopBlockCounter.empty());
  2967. assert(this->LoopBlockCounter.top() == 0);
  2968. this->LoopBlockCounter.pop();
  2969. }
  2970. bool cmMakefile::IsLoopBlock() const
  2971. {
  2972. assert(!this->LoopBlockCounter.empty());
  2973. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  2974. }
  2975. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  2976. std::vector<std::string>& outArgs) const
  2977. {
  2978. std::string const& filename = this->GetBacktrace().Top().FilePath;
  2979. std::string value;
  2980. outArgs.reserve(inArgs.size());
  2981. for (cmListFileArgument const& i : inArgs) {
  2982. // No expansion in a bracket argument.
  2983. if (i.Delim == cmListFileArgument::Bracket) {
  2984. outArgs.push_back(i.Value);
  2985. continue;
  2986. }
  2987. // Expand the variables in the argument.
  2988. value = i.Value;
  2989. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  2990. i.Line, false, false);
  2991. // If the argument is quoted, it should be one argument.
  2992. // Otherwise, it may be a list of arguments.
  2993. if (i.Delim == cmListFileArgument::Quoted) {
  2994. outArgs.push_back(value);
  2995. } else {
  2996. cmExpandList(value, outArgs);
  2997. }
  2998. }
  2999. return !cmSystemTools::GetFatalErrorOccurred();
  3000. }
  3001. bool cmMakefile::ExpandArguments(
  3002. std::vector<cmListFileArgument> const& inArgs,
  3003. std::vector<cmExpandedCommandArgument>& outArgs) const
  3004. {
  3005. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3006. std::string value;
  3007. outArgs.reserve(inArgs.size());
  3008. for (cmListFileArgument const& i : inArgs) {
  3009. // No expansion in a bracket argument.
  3010. if (i.Delim == cmListFileArgument::Bracket) {
  3011. outArgs.emplace_back(i.Value, true);
  3012. continue;
  3013. }
  3014. // Expand the variables in the argument.
  3015. value = i.Value;
  3016. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3017. i.Line, false, false);
  3018. // If the argument is quoted, it should be one argument.
  3019. // Otherwise, it may be a list of arguments.
  3020. if (i.Delim == cmListFileArgument::Quoted) {
  3021. outArgs.emplace_back(value, true);
  3022. } else {
  3023. cmList stringArgs{ value };
  3024. for (std::string const& stringArg : stringArgs) {
  3025. outArgs.emplace_back(stringArg, false);
  3026. }
  3027. }
  3028. }
  3029. return !cmSystemTools::GetFatalErrorOccurred();
  3030. }
  3031. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  3032. {
  3033. if (!this->ExecutionStatusStack.empty()) {
  3034. // Record the context in which the blocker is created.
  3035. fb->SetStartingContext(this->Backtrace.Top());
  3036. }
  3037. this->FunctionBlockers.push(std::move(fb));
  3038. }
  3039. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  3040. {
  3041. assert(!this->FunctionBlockers.empty());
  3042. assert(this->FunctionBlockerBarriers.empty() ||
  3043. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  3044. auto b = std::move(this->FunctionBlockers.top());
  3045. this->FunctionBlockers.pop();
  3046. return b;
  3047. }
  3048. std::string const& cmMakefile::GetHomeDirectory() const
  3049. {
  3050. return this->GetCMakeInstance()->GetHomeDirectory();
  3051. }
  3052. std::string const& cmMakefile::GetHomeOutputDirectory() const
  3053. {
  3054. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3055. }
  3056. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  3057. {
  3058. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  3059. }
  3060. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  3061. {
  3062. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  3063. // this->MarkVariableAsUsed("CMAKE_ARGC");
  3064. for (unsigned int t = 0; t < args.size(); ++t) {
  3065. std::ostringstream tmpStream;
  3066. tmpStream << "CMAKE_ARGV" << t;
  3067. this->AddDefinition(tmpStream.str(), args[t]);
  3068. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  3069. }
  3070. }
  3071. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  3072. cmSourceFileLocationKind kind) const
  3073. {
  3074. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  3075. if (kind == cmSourceFileLocationKind::Known) {
  3076. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  3077. if (sfsi != this->KnownFileSearchIndex.end()) {
  3078. return sfsi->second;
  3079. }
  3080. }
  3081. cmSourceFileLocation sfl(this, sourceName, kind);
  3082. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  3083. #if defined(_WIN32) || defined(__APPLE__)
  3084. name = cmSystemTools::LowerCase(name);
  3085. #endif
  3086. auto sfsi = this->SourceFileSearchIndex.find(name);
  3087. if (sfsi != this->SourceFileSearchIndex.end()) {
  3088. for (auto* sf : sfsi->second) {
  3089. if (sf->Matches(sfl)) {
  3090. return sf;
  3091. }
  3092. }
  3093. }
  3094. return nullptr;
  3095. }
  3096. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  3097. bool generated,
  3098. cmSourceFileLocationKind kind)
  3099. {
  3100. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  3101. auto name =
  3102. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  3103. #if defined(_WIN32) || defined(__APPLE__)
  3104. name = cmSystemTools::LowerCase(name);
  3105. #endif
  3106. this->SourceFileSearchIndex[name].push_back(sf.get());
  3107. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  3108. if (kind == cmSourceFileLocationKind::Known) {
  3109. this->KnownFileSearchIndex[sourceName] = sf.get();
  3110. }
  3111. this->SourceFiles.push_back(std::move(sf));
  3112. return this->SourceFiles.back().get();
  3113. }
  3114. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  3115. bool generated,
  3116. cmSourceFileLocationKind kind)
  3117. {
  3118. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  3119. return esf;
  3120. }
  3121. return this->CreateSource(sourceName, generated, kind);
  3122. }
  3123. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  3124. const std::string& sourceName)
  3125. {
  3126. cmSourceFile* sf =
  3127. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  3128. sf->MarkAsGenerated(); // In case we did not create the source file.
  3129. return sf;
  3130. }
  3131. void cmMakefile::CreateGeneratedOutputs(
  3132. const std::vector<std::string>& outputs)
  3133. {
  3134. for (std::string const& o : outputs) {
  3135. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  3136. this->GetOrCreateGeneratedSource(o);
  3137. }
  3138. }
  3139. }
  3140. void cmMakefile::AddTargetObject(std::string const& tgtName,
  3141. std::string const& objFile)
  3142. {
  3143. cmSourceFile* sf =
  3144. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  3145. sf->SetObjectLibrary(tgtName);
  3146. sf->SetProperty("EXTERNAL_OBJECT", "1");
  3147. #if !defined(CMAKE_BOOTSTRAP)
  3148. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  3149. sf->ResolveFullPath());
  3150. #endif
  3151. }
  3152. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  3153. bool optional)
  3154. {
  3155. if (this->DeferRunning) {
  3156. this->IssueMessage(
  3157. MessageType::FATAL_ERROR,
  3158. "Languages may not be enabled during deferred execution.");
  3159. return;
  3160. }
  3161. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  3162. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  3163. }
  3164. std::vector<std::string> unique_languages;
  3165. {
  3166. std::vector<std::string> duplicate_languages;
  3167. for (std::string const& language : languages) {
  3168. if (!cm::contains(unique_languages, language)) {
  3169. unique_languages.push_back(language);
  3170. } else if (!cm::contains(duplicate_languages, language)) {
  3171. duplicate_languages.push_back(language);
  3172. }
  3173. }
  3174. if (!duplicate_languages.empty()) {
  3175. auto quantity = duplicate_languages.size() == 1 ? std::string(" has")
  3176. : std::string("s have");
  3177. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3178. "Languages to be enabled may not be specified more "
  3179. "than once at the same time. The following language" +
  3180. quantity + " been specified multiple times: " +
  3181. cmJoin(duplicate_languages, ", "));
  3182. }
  3183. }
  3184. // If RC is explicitly listed we need to do it after other languages.
  3185. // On some platforms we enable RC implicitly while enabling others.
  3186. // Do not let that look like recursive enable_language(RC).
  3187. std::vector<std::string> languages_without_RC;
  3188. std::vector<std::string> languages_for_RC;
  3189. languages_without_RC.reserve(unique_languages.size());
  3190. for (std::string const& language : unique_languages) {
  3191. if (language == "RC") {
  3192. languages_for_RC.push_back(language);
  3193. } else {
  3194. languages_without_RC.push_back(language);
  3195. }
  3196. }
  3197. if (!languages_without_RC.empty()) {
  3198. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  3199. optional);
  3200. }
  3201. if (!languages_for_RC.empty()) {
  3202. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  3203. optional);
  3204. }
  3205. }
  3206. int cmMakefile::TryCompile(const std::string& srcdir,
  3207. const std::string& bindir,
  3208. const std::string& projectName,
  3209. const std::string& targetName, bool fast, int jobs,
  3210. const std::vector<std::string>* cmakeArgs,
  3211. std::string& output)
  3212. {
  3213. this->IsSourceFileTryCompile = fast;
  3214. // does the binary directory exist ? If not create it...
  3215. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3216. cmSystemTools::MakeDirectory(bindir);
  3217. }
  3218. // change to the tests directory and run cmake
  3219. // use the cmake object instead of calling cmake
  3220. cmWorkingDirectory workdir(bindir);
  3221. if (workdir.Failed()) {
  3222. this->IssueMessage(MessageType::FATAL_ERROR,
  3223. "Failed to set working directory to " + bindir + " : " +
  3224. std::strerror(workdir.GetLastResult()));
  3225. cmSystemTools::SetFatalErrorOccurred();
  3226. this->IsSourceFileTryCompile = false;
  3227. return 1;
  3228. }
  3229. // make sure the same generator is used
  3230. // use this program as the cmake to be run, it should not
  3231. // be run that way but the cmake object requires a vailid path
  3232. cmake cm(cmake::RoleProject, cmState::Project,
  3233. cmState::ProjectKind::TryCompile);
  3234. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3235. if (!gg) {
  3236. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3237. "Global generator '" +
  3238. this->GetGlobalGenerator()->GetName() +
  3239. "' could not be created.");
  3240. cmSystemTools::SetFatalErrorOccurred();
  3241. this->IsSourceFileTryCompile = false;
  3242. return 1;
  3243. }
  3244. gg->RecursionDepth = this->RecursionDepth;
  3245. cm.SetGlobalGenerator(std::move(gg));
  3246. // copy trace state
  3247. cm.SetTraceRedirect(this->GetCMakeInstance());
  3248. // do a configure
  3249. cm.SetHomeDirectory(srcdir);
  3250. cm.SetHomeOutputDirectory(bindir);
  3251. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3252. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3253. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3254. cm.LoadCache();
  3255. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  3256. if (cmValue config =
  3257. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3258. // Tell the single-configuration generator which one to use.
  3259. // Add this before the user-provided CMake arguments in case
  3260. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3261. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3262. cmStateEnums::STRING);
  3263. }
  3264. }
  3265. cmValue recursionDepth =
  3266. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3267. if (recursionDepth) {
  3268. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3269. "Maximum recursion depth", cmStateEnums::STRING);
  3270. }
  3271. // if cmake args were provided then pass them in
  3272. if (cmakeArgs) {
  3273. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3274. //
  3275. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  3276. // However, there is a subtle problem when certain arguments are passed to
  3277. // a macro wrapping around try_compile or try_run that does not escape
  3278. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3279. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3280. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3281. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3282. // the try_compile or try_run does not get the proper value of VAR. If we
  3283. // call SetArgs here then it would treat "b" as the source directory and
  3284. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3285. // does not exist", thus breaking the try_compile or try_run completely.
  3286. //
  3287. // Strictly speaking the bug is in the wrapper macro because the CMake
  3288. // language has always flattened nested lists and the macro should escape
  3289. // the semicolons in its arguments before forwarding them. However, this
  3290. // bug is so subtle that projects typically work anyway, usually because
  3291. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3292. // correct result. Calling SetArgs here would break such projects that
  3293. // previously built. Instead we work around the issue by never reporting
  3294. // unused arguments and ignoring options such as --no-warn-unused-cli.
  3295. cm.SetWarnUnusedCli(false);
  3296. // cm.SetArgs(*cmakeArgs, true);
  3297. cm.SetCacheArgs(*cmakeArgs);
  3298. }
  3299. // to save time we pass the EnableLanguage info directly
  3300. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  3301. this->GetGlobalGenerator(), this);
  3302. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3303. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3304. cmStateEnums::INTERNAL);
  3305. } else {
  3306. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3307. cmStateEnums::INTERNAL);
  3308. }
  3309. if (cm.Configure() != 0) {
  3310. this->IssueMessage(MessageType::FATAL_ERROR,
  3311. "Failed to configure test project build system.");
  3312. cmSystemTools::SetFatalErrorOccurred();
  3313. this->IsSourceFileTryCompile = false;
  3314. return 1;
  3315. }
  3316. if (cm.Generate() != 0) {
  3317. this->IssueMessage(MessageType::FATAL_ERROR,
  3318. "Failed to generate test project build system.");
  3319. cmSystemTools::SetFatalErrorOccurred();
  3320. this->IsSourceFileTryCompile = false;
  3321. return 1;
  3322. }
  3323. // finally call the generator to actually build the resulting project
  3324. int ret = this->GetGlobalGenerator()->TryCompile(
  3325. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3326. this->IsSourceFileTryCompile = false;
  3327. return ret;
  3328. }
  3329. bool cmMakefile::GetIsSourceFileTryCompile() const
  3330. {
  3331. return this->IsSourceFileTryCompile;
  3332. }
  3333. cmake* cmMakefile::GetCMakeInstance() const
  3334. {
  3335. return this->GlobalGenerator->GetCMakeInstance();
  3336. }
  3337. cmMessenger* cmMakefile::GetMessenger() const
  3338. {
  3339. return this->GetCMakeInstance()->GetMessenger();
  3340. }
  3341. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3342. {
  3343. return this->GlobalGenerator;
  3344. }
  3345. #ifndef CMAKE_BOOTSTRAP
  3346. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3347. {
  3348. if (this->GetCMakeInstance() &&
  3349. this->GetCMakeInstance()->GetVariableWatch()) {
  3350. return this->GetCMakeInstance()->GetVariableWatch();
  3351. }
  3352. return nullptr;
  3353. }
  3354. #endif
  3355. cmState* cmMakefile::GetState() const
  3356. {
  3357. return this->GetCMakeInstance()->GetState();
  3358. }
  3359. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3360. {
  3361. cmake* cm = this->GetCMakeInstance();
  3362. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3363. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3364. // directly be fed to the compiler, which will be confused.
  3365. return;
  3366. }
  3367. cm->UpdateProgress(message, s);
  3368. }
  3369. std::string cmMakefile::GetModulesFile(const std::string& filename,
  3370. bool& system, bool debug,
  3371. std::string& debugBuffer) const
  3372. {
  3373. std::string result;
  3374. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3375. // and then decide based on the policy setting which one to return.
  3376. // See CMP0017 for more details.
  3377. // The specific problem was that KDE 4.5.0 installs a
  3378. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3379. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3380. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3381. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3382. // new features, which were not there in the version from kdelibs, and so
  3383. // failed ("
  3384. std::string moduleInCMakeRoot;
  3385. std::string moduleInCMakeModulePath;
  3386. // Always search in CMAKE_MODULE_PATH:
  3387. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3388. if (cmakeModulePath) {
  3389. cmList modulePath{ *cmakeModulePath };
  3390. // Look through the possible module directories.
  3391. for (std::string itempl : modulePath) {
  3392. cmSystemTools::ConvertToUnixSlashes(itempl);
  3393. itempl += "/";
  3394. itempl += filename;
  3395. if (cmSystemTools::FileExists(itempl)) {
  3396. moduleInCMakeModulePath = itempl;
  3397. break;
  3398. }
  3399. if (debug) {
  3400. debugBuffer = cmStrCat(debugBuffer, " ", itempl, "\n");
  3401. }
  3402. }
  3403. }
  3404. // Always search in the standard modules location.
  3405. moduleInCMakeRoot =
  3406. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  3407. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3408. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3409. if (debug) {
  3410. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, "\n");
  3411. }
  3412. moduleInCMakeRoot.clear();
  3413. }
  3414. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3415. // from which we are being called is located itself in CMAKE_ROOT, then
  3416. // prefer results from CMAKE_ROOT depending on the policy setting.
  3417. system = false;
  3418. result = moduleInCMakeModulePath;
  3419. if (result.empty()) {
  3420. system = true;
  3421. result = moduleInCMakeRoot;
  3422. }
  3423. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3424. cmValue currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3425. std::string mods = cmSystemTools::GetCMakeRoot() + "/Modules/";
  3426. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  3427. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3428. case cmPolicies::WARN: {
  3429. std::ostringstream e;
  3430. /* clang-format off */
  3431. e << "File " << *currentFile << " includes "
  3432. << moduleInCMakeModulePath
  3433. << " (found via CMAKE_MODULE_PATH) which shadows "
  3434. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3435. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3436. /* clang-format on */
  3437. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3438. CM_FALLTHROUGH;
  3439. }
  3440. case cmPolicies::OLD:
  3441. system = false;
  3442. result = moduleInCMakeModulePath;
  3443. break;
  3444. case cmPolicies::REQUIRED_IF_USED:
  3445. case cmPolicies::REQUIRED_ALWAYS:
  3446. case cmPolicies::NEW:
  3447. system = true;
  3448. result = moduleInCMakeRoot;
  3449. break;
  3450. }
  3451. }
  3452. }
  3453. return result;
  3454. }
  3455. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3456. bool atOnly, bool escapeQuotes) const
  3457. {
  3458. // Split input to handle one line at a time.
  3459. std::string::const_iterator lineStart = input.begin();
  3460. while (lineStart != input.end()) {
  3461. // Find the end of this line.
  3462. std::string::const_iterator lineEnd = lineStart;
  3463. while (lineEnd != input.end() && *lineEnd != '\n') {
  3464. ++lineEnd;
  3465. }
  3466. // Copy the line.
  3467. std::string line(lineStart, lineEnd);
  3468. // Skip the newline character.
  3469. bool haveNewline = (lineEnd != input.end());
  3470. if (haveNewline) {
  3471. ++lineEnd;
  3472. }
  3473. // Replace #cmakedefine instances.
  3474. if (this->cmDefineRegex.find(line)) {
  3475. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3476. if (!cmIsOff(def)) {
  3477. const std::string indentation = this->cmDefineRegex.match(1);
  3478. cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine",
  3479. "#" + indentation + "define");
  3480. output += line;
  3481. } else {
  3482. output += "/* #undef ";
  3483. output += this->cmDefineRegex.match(2);
  3484. output += " */";
  3485. }
  3486. } else if (this->cmDefine01Regex.find(line)) {
  3487. const std::string indentation = this->cmDefine01Regex.match(1);
  3488. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3489. cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine01",
  3490. "#" + indentation + "define");
  3491. output += line;
  3492. if (!cmIsOff(def)) {
  3493. output += " 1";
  3494. } else {
  3495. output += " 0";
  3496. }
  3497. } else {
  3498. output += line;
  3499. }
  3500. if (haveNewline) {
  3501. output += "\n";
  3502. }
  3503. // Move to the next line.
  3504. lineStart = lineEnd;
  3505. }
  3506. // Perform variable replacements.
  3507. const char* filename = nullptr;
  3508. long lineNumber = -1;
  3509. if (!this->Backtrace.Empty()) {
  3510. const auto& currentTrace = this->Backtrace.Top();
  3511. filename = currentTrace.FilePath.c_str();
  3512. lineNumber = currentTrace.Line;
  3513. }
  3514. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3515. lineNumber, true, true);
  3516. }
  3517. int cmMakefile::ConfigureFile(const std::string& infile,
  3518. const std::string& outfile, bool copyonly,
  3519. bool atOnly, bool escapeQuotes,
  3520. mode_t permissions, cmNewLineStyle newLine)
  3521. {
  3522. int res = 1;
  3523. if (!this->CanIWriteThisFile(outfile)) {
  3524. cmSystemTools::Error("Attempt to write file: " + outfile +
  3525. " into a source directory.");
  3526. return 0;
  3527. }
  3528. if (!cmSystemTools::FileExists(infile)) {
  3529. cmSystemTools::Error("File " + infile + " does not exist.");
  3530. return 0;
  3531. }
  3532. std::string soutfile = outfile;
  3533. const std::string& sinfile = infile;
  3534. this->AddCMakeDependFile(sinfile);
  3535. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3536. // Re-generate if non-temporary outputs are missing.
  3537. // when we finalize the configuration we will remove all
  3538. // output files that now don't exist.
  3539. this->AddCMakeOutputFile(soutfile);
  3540. if (permissions == 0) {
  3541. cmSystemTools::GetPermissions(sinfile, permissions);
  3542. }
  3543. std::string::size_type pos = soutfile.rfind('/');
  3544. if (pos != std::string::npos) {
  3545. std::string path = soutfile.substr(0, pos);
  3546. cmSystemTools::MakeDirectory(path);
  3547. }
  3548. if (copyonly) {
  3549. if (!cmSystemTools::CopyFileIfDifferent(sinfile, soutfile)) {
  3550. this->IssueMessage(MessageType::FATAL_ERROR,
  3551. cmSystemTools::GetLastSystemError());
  3552. return 0;
  3553. }
  3554. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3555. this->IssueMessage(MessageType::FATAL_ERROR,
  3556. cmSystemTools::GetLastSystemError());
  3557. return 0;
  3558. }
  3559. } else {
  3560. std::string newLineCharacters;
  3561. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3562. if (newLine.IsValid()) {
  3563. newLineCharacters = newLine.GetCharacters();
  3564. omode |= std::ios::binary;
  3565. } else {
  3566. newLineCharacters = "\n";
  3567. }
  3568. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3569. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3570. if (!fout) {
  3571. cmSystemTools::Error("Could not open file for write in copy operation " +
  3572. tempOutputFile);
  3573. cmSystemTools::ReportLastSystemError("");
  3574. return 0;
  3575. }
  3576. cmsys::ifstream fin(sinfile.c_str());
  3577. if (!fin) {
  3578. cmSystemTools::Error("Could not open file for read in copy operation " +
  3579. sinfile);
  3580. return 0;
  3581. }
  3582. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3583. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3584. std::ostringstream e;
  3585. e << "File starts with a Byte-Order-Mark that is not UTF-8:\n "
  3586. << sinfile;
  3587. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3588. return 0;
  3589. }
  3590. // rewind to copy BOM to output file
  3591. fin.seekg(0);
  3592. // now copy input to output and expand variables in the
  3593. // input file at the same time
  3594. std::string inLine;
  3595. std::string outLine;
  3596. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3597. outLine.clear();
  3598. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3599. fout << outLine << newLineCharacters;
  3600. }
  3601. // close the files before attempting to copy
  3602. fin.close();
  3603. fout.close();
  3604. if (!cmSystemTools::CopyFileIfDifferent(tempOutputFile, soutfile)) {
  3605. this->IssueMessage(MessageType::FATAL_ERROR,
  3606. cmSystemTools::GetLastSystemError());
  3607. res = 0;
  3608. } else {
  3609. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3610. this->IssueMessage(MessageType::FATAL_ERROR,
  3611. cmSystemTools::GetLastSystemError());
  3612. res = 0;
  3613. }
  3614. }
  3615. cmSystemTools::RemoveFile(tempOutputFile);
  3616. }
  3617. return res;
  3618. }
  3619. void cmMakefile::SetProperty(const std::string& prop, const char* value)
  3620. {
  3621. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3622. }
  3623. void cmMakefile::SetProperty(const std::string& prop, cmValue value)
  3624. {
  3625. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3626. }
  3627. void cmMakefile::AppendProperty(const std::string& prop,
  3628. const std::string& value, bool asString)
  3629. {
  3630. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3631. this->Backtrace);
  3632. }
  3633. cmValue cmMakefile::GetProperty(const std::string& prop) const
  3634. {
  3635. // Check for computed properties.
  3636. static std::string output;
  3637. if (prop == "TESTS") {
  3638. std::vector<std::string> keys;
  3639. // get list of keys
  3640. const auto* t = this;
  3641. std::transform(
  3642. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3643. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3644. output = cmJoin(keys, ";");
  3645. return cmValue(output);
  3646. }
  3647. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3648. }
  3649. cmValue cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3650. {
  3651. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3652. }
  3653. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3654. {
  3655. return cmIsOn(this->GetProperty(prop));
  3656. }
  3657. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3658. {
  3659. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3660. }
  3661. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3662. {
  3663. auto i = this->Targets.find(name);
  3664. if (i != this->Targets.end()) {
  3665. return &i->second;
  3666. }
  3667. return nullptr;
  3668. }
  3669. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3670. {
  3671. cmTest* test = this->GetTest(testName);
  3672. if (test) {
  3673. return test;
  3674. }
  3675. auto newTest = cm::make_unique<cmTest>(this);
  3676. test = newTest.get();
  3677. newTest->SetName(testName);
  3678. this->Tests[testName] = std::move(newTest);
  3679. return test;
  3680. }
  3681. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3682. {
  3683. auto mi = this->Tests.find(testName);
  3684. if (mi != this->Tests.end()) {
  3685. return mi->second.get();
  3686. }
  3687. return nullptr;
  3688. }
  3689. void cmMakefile::GetTests(const std::string& config,
  3690. std::vector<cmTest*>& tests) const
  3691. {
  3692. for (const auto& generator : this->GetTestGenerators()) {
  3693. if (generator->TestsForConfig(config)) {
  3694. tests.push_back(generator->GetTest());
  3695. }
  3696. }
  3697. }
  3698. void cmMakefile::AddCMakeDependFilesFromUser()
  3699. {
  3700. std::vector<std::string> deps;
  3701. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3702. cmExpandList(*deps_str, deps);
  3703. }
  3704. for (std::string const& dep : deps) {
  3705. if (cmSystemTools::FileIsFullPath(dep)) {
  3706. this->AddCMakeDependFile(dep);
  3707. } else {
  3708. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3709. this->AddCMakeDependFile(f);
  3710. }
  3711. }
  3712. }
  3713. std::string cmMakefile::FormatListFileStack() const
  3714. {
  3715. std::vector<std::string> listFiles;
  3716. cmStateSnapshot snp = this->StateSnapshot;
  3717. while (snp.IsValid()) {
  3718. listFiles.push_back(snp.GetExecutionListFile());
  3719. snp = snp.GetCallStackParent();
  3720. }
  3721. std::reverse(listFiles.begin(), listFiles.end());
  3722. std::ostringstream tmp;
  3723. size_t depth = listFiles.size();
  3724. if (depth > 0) {
  3725. auto it = listFiles.end();
  3726. do {
  3727. if (depth != listFiles.size()) {
  3728. tmp << "\n ";
  3729. }
  3730. --it;
  3731. tmp << "[";
  3732. tmp << depth;
  3733. tmp << "]\t";
  3734. tmp << *it;
  3735. depth--;
  3736. } while (it != listFiles.begin());
  3737. }
  3738. return tmp.str();
  3739. }
  3740. void cmMakefile::PushScope()
  3741. {
  3742. this->StateSnapshot =
  3743. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3744. this->PushLoopBlockBarrier();
  3745. #if !defined(CMAKE_BOOTSTRAP)
  3746. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3747. #endif
  3748. }
  3749. void cmMakefile::PopScope()
  3750. {
  3751. #if !defined(CMAKE_BOOTSTRAP)
  3752. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3753. #endif
  3754. this->PopLoopBlockBarrier();
  3755. this->PopSnapshot();
  3756. }
  3757. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3758. {
  3759. if (var.empty()) {
  3760. return;
  3761. }
  3762. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3763. std::ostringstream m;
  3764. m << "Cannot set \"" << var << "\": current scope has no parent.";
  3765. this->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  3766. return;
  3767. }
  3768. #ifndef CMAKE_BOOTSTRAP
  3769. cmVariableWatch* vv = this->GetVariableWatch();
  3770. if (vv) {
  3771. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3772. varDef, this);
  3773. }
  3774. #endif
  3775. }
  3776. void cmMakefile::RaiseScope(const std::vector<std::string>& variables)
  3777. {
  3778. for (auto const& varName : variables) {
  3779. if (this->IsNormalDefinitionSet(varName)) {
  3780. this->RaiseScope(varName, this->GetDefinition(varName));
  3781. } else {
  3782. // unset variable in parent scope
  3783. this->RaiseScope(varName, nullptr);
  3784. }
  3785. }
  3786. }
  3787. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3788. cmStateEnums::TargetType type,
  3789. bool global)
  3790. {
  3791. // Create the target.
  3792. std::unique_ptr<cmTarget> target(
  3793. new cmTarget(name, type,
  3794. global ? cmTarget::Visibility::ImportedGlobally
  3795. : cmTarget::Visibility::Imported,
  3796. this, cmTarget::PerConfig::Yes));
  3797. // Add to the set of available imported targets.
  3798. this->ImportedTargets[name] = target.get();
  3799. this->GetGlobalGenerator()->IndexTarget(target.get());
  3800. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3801. // Transfer ownership to this cmMakefile object.
  3802. this->ImportedTargetsOwned.push_back(std::move(target));
  3803. return this->ImportedTargetsOwned.back().get();
  3804. }
  3805. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3806. bool excludeAliases) const
  3807. {
  3808. // Look for an imported target. These take priority because they
  3809. // are more local in scope and do not have to be globally unique.
  3810. auto targetName = name;
  3811. if (!excludeAliases) {
  3812. // Look for local alias targets.
  3813. auto alias = this->AliasTargets.find(name);
  3814. if (alias != this->AliasTargets.end()) {
  3815. targetName = alias->second;
  3816. }
  3817. }
  3818. auto imported = this->ImportedTargets.find(targetName);
  3819. if (imported != this->ImportedTargets.end()) {
  3820. return imported->second;
  3821. }
  3822. // Look for a target built in this directory.
  3823. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3824. return t;
  3825. }
  3826. // Look for a target built in this project.
  3827. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3828. }
  3829. bool cmMakefile::IsAlias(const std::string& name) const
  3830. {
  3831. if (cm::contains(this->AliasTargets, name)) {
  3832. return true;
  3833. }
  3834. return this->GetGlobalGenerator()->IsAlias(name);
  3835. }
  3836. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3837. bool isCustom) const
  3838. {
  3839. if (this->IsAlias(name)) {
  3840. std::ostringstream e;
  3841. e << "cannot create target \"" << name
  3842. << "\" because an alias with the same name already exists.";
  3843. msg = e.str();
  3844. return false;
  3845. }
  3846. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3847. // The name given conflicts with an existing target. Produce an
  3848. // error in a compatible way.
  3849. if (existing->IsImported()) {
  3850. // Imported targets were not supported in previous versions.
  3851. // This is new code, so we can make it an error.
  3852. std::ostringstream e;
  3853. e << "cannot create target \"" << name
  3854. << "\" because an imported target with the same name already exists.";
  3855. msg = e.str();
  3856. return false;
  3857. }
  3858. // target names must be globally unique
  3859. switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
  3860. case cmPolicies::WARN:
  3861. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3862. cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
  3863. CM_FALLTHROUGH;
  3864. case cmPolicies::OLD:
  3865. return true;
  3866. case cmPolicies::REQUIRED_IF_USED:
  3867. case cmPolicies::REQUIRED_ALWAYS:
  3868. this->IssueMessage(
  3869. MessageType::FATAL_ERROR,
  3870. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
  3871. return true;
  3872. case cmPolicies::NEW:
  3873. break;
  3874. }
  3875. // The conflict is with a non-imported target.
  3876. // Allow this if the user has requested support.
  3877. cmake* cm = this->GetCMakeInstance();
  3878. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3879. this != existing->GetMakefile() &&
  3880. cm->GetState()->GetGlobalPropertyAsBool(
  3881. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3882. return true;
  3883. }
  3884. // Produce an error that tells the user how to work around the
  3885. // problem.
  3886. std::ostringstream e;
  3887. e << "cannot create target \"" << name
  3888. << "\" because another target with the same name already exists. "
  3889. << "The existing target is ";
  3890. switch (existing->GetType()) {
  3891. case cmStateEnums::EXECUTABLE:
  3892. e << "an executable ";
  3893. break;
  3894. case cmStateEnums::STATIC_LIBRARY:
  3895. e << "a static library ";
  3896. break;
  3897. case cmStateEnums::SHARED_LIBRARY:
  3898. e << "a shared library ";
  3899. break;
  3900. case cmStateEnums::MODULE_LIBRARY:
  3901. e << "a module library ";
  3902. break;
  3903. case cmStateEnums::UTILITY:
  3904. e << "a custom target ";
  3905. break;
  3906. case cmStateEnums::INTERFACE_LIBRARY:
  3907. e << "an interface library ";
  3908. break;
  3909. default:
  3910. break;
  3911. }
  3912. e << "created in source directory \""
  3913. << existing->GetMakefile()->GetCurrentSourceDirectory() << "\". "
  3914. << "See documentation for policy CMP0002 for more details.";
  3915. msg = e.str();
  3916. return false;
  3917. }
  3918. return true;
  3919. }
  3920. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  3921. const std::string& binPath) const
  3922. {
  3923. // Make sure the binary directory is unique.
  3924. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  3925. if (gg->BinaryDirectoryIsNew(binPath)) {
  3926. return true;
  3927. }
  3928. std::ostringstream e;
  3929. switch (this->GetPolicyStatus(cmPolicies::CMP0013)) {
  3930. case cmPolicies::WARN:
  3931. // Print the warning.
  3932. /* clang-format off */
  3933. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0013)
  3934. << "\n"
  3935. << "The binary directory\n"
  3936. << " " << binPath << "\n"
  3937. << "is already used to build a source directory. "
  3938. << "This command uses it to build source directory\n"
  3939. << " " << srcPath << "\n"
  3940. << "which can generate conflicting build files. "
  3941. << "CMake does not support this use case but it used "
  3942. << "to work accidentally and is being allowed for "
  3943. << "compatibility.";
  3944. /* clang-format on */
  3945. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3946. CM_FALLTHROUGH;
  3947. case cmPolicies::OLD:
  3948. // OLD behavior does not warn.
  3949. return true;
  3950. case cmPolicies::REQUIRED_IF_USED:
  3951. case cmPolicies::REQUIRED_ALWAYS:
  3952. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0013) << "\n";
  3953. CM_FALLTHROUGH;
  3954. case cmPolicies::NEW:
  3955. // NEW behavior prints the error.
  3956. /* clang-format off */
  3957. e << "The binary directory\n"
  3958. << " " << binPath << "\n"
  3959. << "is already used to build a source directory. "
  3960. << "It cannot be used to build source directory\n"
  3961. << " " << srcPath << "\n"
  3962. << "Specify a unique binary directory name.";
  3963. /* clang-format on */
  3964. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3965. break;
  3966. }
  3967. return false;
  3968. }
  3969. static std::string const matchVariables[] = {
  3970. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  3971. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  3972. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  3973. };
  3974. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  3975. void cmMakefile::ClearMatches()
  3976. {
  3977. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  3978. if (!nMatchesStr) {
  3979. return;
  3980. }
  3981. int nMatches = atoi(nMatchesStr->c_str());
  3982. for (int i = 0; i <= nMatches; i++) {
  3983. std::string const& var = matchVariables[i];
  3984. std::string const& s = this->GetSafeDefinition(var);
  3985. if (!s.empty()) {
  3986. this->AddDefinition(var, "");
  3987. this->MarkVariableAsUsed(var);
  3988. }
  3989. }
  3990. this->AddDefinition(nMatchesVariable, "0");
  3991. this->MarkVariableAsUsed(nMatchesVariable);
  3992. }
  3993. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  3994. {
  3995. char highest = 0;
  3996. for (int i = 0; i < 10; i++) {
  3997. std::string const& m = re.match(i);
  3998. if (!m.empty()) {
  3999. std::string const& var = matchVariables[i];
  4000. this->AddDefinition(var, m);
  4001. this->MarkVariableAsUsed(var);
  4002. highest = static_cast<char>('0' + i);
  4003. }
  4004. }
  4005. char nMatches[] = { highest, '\0' };
  4006. this->AddDefinition(nMatchesVariable, nMatches);
  4007. this->MarkVariableAsUsed(nMatchesVariable);
  4008. }
  4009. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  4010. {
  4011. return this->StateSnapshot;
  4012. }
  4013. const char* cmMakefile::GetDefineFlagsCMP0059() const
  4014. {
  4015. return this->DefineFlagsOrig.c_str();
  4016. }
  4017. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  4018. bool parent_scope) const
  4019. {
  4020. return this->StateSnapshot.GetPolicy(id, parent_scope);
  4021. }
  4022. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  4023. {
  4024. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  4025. if (cmValue val = this->GetDefinition(var)) {
  4026. return cmIsOn(val);
  4027. }
  4028. // Enable optional policy warnings with --debug-output, --trace,
  4029. // or --trace-expand.
  4030. cmake* cm = this->GetCMakeInstance();
  4031. return cm->GetDebugOutput() || cm->GetTrace();
  4032. }
  4033. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  4034. {
  4035. cmPolicies::PolicyID pid;
  4036. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  4037. std::ostringstream e;
  4038. e << "Policy \"" << id << "\" is not known to this version of CMake.";
  4039. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4040. return false;
  4041. }
  4042. return this->SetPolicy(pid, status);
  4043. }
  4044. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  4045. cmPolicies::PolicyStatus status)
  4046. {
  4047. // A REQUIRED_ALWAYS policy may be set only to NEW.
  4048. if (status != cmPolicies::NEW &&
  4049. cmPolicies::GetPolicyStatus(id) == cmPolicies::REQUIRED_ALWAYS) {
  4050. std::string msg = cmPolicies::GetRequiredAlwaysPolicyError(id);
  4051. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  4052. return false;
  4053. }
  4054. // Deprecate old policies.
  4055. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0114 &&
  4056. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  4057. (
  4058. // Policies set by cmCoreTryCompile::TryCompileCode.
  4059. id == cmPolicies::CMP0065 || id == cmPolicies::CMP0083 ||
  4060. id == cmPolicies::CMP0091 || id == cmPolicies::CMP0104)) &&
  4061. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  4062. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  4063. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  4064. cmPolicies::GetPolicyDeprecatedWarning(id));
  4065. }
  4066. this->StateSnapshot.SetPolicy(id, status);
  4067. return true;
  4068. }
  4069. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  4070. : Makefile(m)
  4071. {
  4072. this->Makefile->PushPolicy();
  4073. }
  4074. cmMakefile::PolicyPushPop::~PolicyPushPop()
  4075. {
  4076. this->Makefile->PopPolicy();
  4077. }
  4078. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  4079. {
  4080. this->StateSnapshot.PushPolicy(pm, weak);
  4081. }
  4082. void cmMakefile::PopPolicy()
  4083. {
  4084. if (!this->StateSnapshot.PopPolicy()) {
  4085. this->IssueMessage(MessageType::FATAL_ERROR,
  4086. "cmake_policy POP without matching PUSH");
  4087. }
  4088. }
  4089. void cmMakefile::PopSnapshot(bool reportError)
  4090. {
  4091. // cmStateSnapshot manages nested policy scopes within it.
  4092. // Since the scope corresponding to the snapshot is closing,
  4093. // reject any still-open nested policy scopes with an error.
  4094. while (this->StateSnapshot.CanPopPolicyScope()) {
  4095. if (reportError) {
  4096. this->IssueMessage(MessageType::FATAL_ERROR,
  4097. "cmake_policy PUSH without matching POP");
  4098. reportError = false;
  4099. }
  4100. this->PopPolicy();
  4101. }
  4102. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  4103. assert(this->StateSnapshot.IsValid());
  4104. }
  4105. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  4106. std::string const& version_max)
  4107. {
  4108. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  4109. cmPolicies::WarnCompat::On);
  4110. }
  4111. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  4112. : Makefile(m)
  4113. {
  4114. this->Makefile->StateSnapshot =
  4115. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  4116. this->Makefile->StateSnapshot);
  4117. }
  4118. cmMakefile::VariablePushPop::~VariablePushPop()
  4119. {
  4120. this->Makefile->PopSnapshot();
  4121. }
  4122. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  4123. cmListFileContext const& context) const
  4124. {
  4125. return !this->CMP0054ReportedIds.insert(context).second;
  4126. }
  4127. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  4128. {
  4129. /* Record the setting of every policy. */
  4130. using PolicyID = cmPolicies::PolicyID;
  4131. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  4132. pid = static_cast<PolicyID>(pid + 1)) {
  4133. pm.Set(pid, this->GetPolicyStatus(pid));
  4134. }
  4135. }
  4136. bool cmMakefile::IgnoreErrorsCMP0061() const
  4137. {
  4138. bool ignoreErrors = true;
  4139. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  4140. case cmPolicies::WARN:
  4141. // No warning for this policy!
  4142. CM_FALLTHROUGH;
  4143. case cmPolicies::OLD:
  4144. break;
  4145. case cmPolicies::REQUIRED_IF_USED:
  4146. case cmPolicies::REQUIRED_ALWAYS:
  4147. case cmPolicies::NEW:
  4148. ignoreErrors = false;
  4149. break;
  4150. }
  4151. return ignoreErrors;
  4152. }
  4153. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  4154. const std::string& fileName,
  4155. cmPolicies::PolicyMap const& pm)
  4156. : Makefile(mf)
  4157. {
  4158. this->Makefile->PushFunctionScope(fileName, pm);
  4159. }
  4160. cmMakefile::FunctionPushPop::~FunctionPushPop()
  4161. {
  4162. this->Makefile->PopFunctionScope(this->ReportError);
  4163. }
  4164. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  4165. const std::string& fileName,
  4166. const cmPolicies::PolicyMap& pm)
  4167. : Makefile(mf)
  4168. {
  4169. this->Makefile->PushMacroScope(fileName, pm);
  4170. }
  4171. cmMakefile::MacroPushPop::~MacroPushPop()
  4172. {
  4173. this->Makefile->PopMacroScope(this->ReportError);
  4174. }
  4175. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  4176. std::string const& pkg)
  4177. : Makefile(mf)
  4178. , OldValue(this->Makefile->DebugFindPkg)
  4179. {
  4180. this->Makefile->DebugFindPkg =
  4181. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  4182. }
  4183. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  4184. {
  4185. this->Makefile->DebugFindPkg = this->OldValue;
  4186. }
  4187. bool cmMakefile::GetDebugFindPkgMode() const
  4188. {
  4189. return this->DebugFindPkg;
  4190. }