cmMakefile.cxx 169 KB

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