cmMakefile.cxx 161 KB

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