cmMakefile.cxx 147 KB

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