cmMakefile.cxx 162 KB

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