cmMakefile.cxx 156 KB

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