cmMakefile.cxx 156 KB

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