cmMakefile.cxx 167 KB

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