cmMakefile.cxx 158 KB

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