cmMakefile.cxx 176 KB

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