cmVisualStudio10TargetGenerator.cxx 214 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmVisualStudio10TargetGenerator.h"
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <iterator>
  8. #include <set>
  9. #include <sstream>
  10. #include <cm/memory>
  11. #include <cm/optional>
  12. #include <cm/string_view>
  13. #include <cm/vector>
  14. #include <cmext/algorithm>
  15. #include <cmext/string_view>
  16. #include "windows.h"
  17. // include wincrypt.h after windows.h
  18. #include <wincrypt.h>
  19. #include "cmsys/FStream.hxx"
  20. #include "cmsys/RegularExpression.hxx"
  21. #include "cmComputeLinkInformation.h"
  22. #include "cmCryptoHash.h"
  23. #include "cmCustomCommand.h"
  24. #include "cmCustomCommandGenerator.h"
  25. #include "cmFileSet.h"
  26. #include "cmGeneratedFileStream.h"
  27. #include "cmGeneratorExpression.h"
  28. #include "cmGeneratorTarget.h"
  29. #include "cmGlobalGenerator.h"
  30. #include "cmGlobalVisualStudio10Generator.h"
  31. #include "cmGlobalVisualStudio7Generator.h"
  32. #include "cmGlobalVisualStudioGenerator.h"
  33. #include "cmLinkLineDeviceComputer.h"
  34. #include "cmList.h"
  35. #include "cmListFileCache.h"
  36. #include "cmLocalGenerator.h"
  37. #include "cmLocalVisualStudio10Generator.h"
  38. #include "cmLocalVisualStudio7Generator.h"
  39. #include "cmLocalVisualStudioGenerator.h"
  40. #include "cmMakefile.h"
  41. #include "cmMessageType.h"
  42. #include "cmPropertyMap.h"
  43. #include "cmSourceFile.h"
  44. #include "cmSourceFileLocation.h"
  45. #include "cmSourceFileLocationKind.h"
  46. #include "cmSourceGroup.h"
  47. #include "cmStateTypes.h"
  48. #include "cmStringAlgorithms.h"
  49. #include "cmSystemTools.h"
  50. #include "cmTarget.h"
  51. #include "cmValue.h"
  52. #include "cmVisualStudioGeneratorOptions.h"
  53. struct cmIDEFlagTable;
  54. static void ConvertToWindowsSlash(std::string& s);
  55. static std::string cmVS10EscapeXML(std::string arg)
  56. {
  57. cmSystemTools::ReplaceString(arg, "&", "&amp;");
  58. cmSystemTools::ReplaceString(arg, "<", "&lt;");
  59. cmSystemTools::ReplaceString(arg, ">", "&gt;");
  60. return arg;
  61. }
  62. static std::string cmVS10EscapeAttr(std::string arg)
  63. {
  64. cmSystemTools::ReplaceString(arg, "&", "&amp;");
  65. cmSystemTools::ReplaceString(arg, "<", "&lt;");
  66. cmSystemTools::ReplaceString(arg, ">", "&gt;");
  67. cmSystemTools::ReplaceString(arg, "\"", "&quot;");
  68. cmSystemTools::ReplaceString(arg, "\n", "&#10;");
  69. return arg;
  70. }
  71. struct cmVisualStudio10TargetGenerator::Elem
  72. {
  73. std::ostream& S;
  74. const int Indent;
  75. bool HasElements = false;
  76. bool HasContent = false;
  77. std::string Tag;
  78. Elem(std::ostream& s, std::string tag)
  79. : S(s)
  80. , Indent(0)
  81. , Tag(std::move(tag))
  82. {
  83. this->StartElement();
  84. }
  85. Elem(const Elem&) = delete;
  86. Elem(Elem& par, cm::string_view tag)
  87. : S(par.S)
  88. , Indent(par.Indent + 1)
  89. , Tag(std::string(tag))
  90. {
  91. par.SetHasElements();
  92. this->StartElement();
  93. }
  94. void SetHasElements()
  95. {
  96. if (!HasElements) {
  97. this->S << '>';
  98. HasElements = true;
  99. }
  100. }
  101. std::ostream& WriteString(const char* line);
  102. void StartElement() { this->WriteString("<") << this->Tag; }
  103. void Element(cm::string_view tag, std::string val)
  104. {
  105. Elem(*this, tag).Content(std::move(val));
  106. }
  107. Elem& Attribute(const char* an, std::string av)
  108. {
  109. this->S << ' ' << an << "=\"" << cmVS10EscapeAttr(std::move(av)) << '"';
  110. return *this;
  111. }
  112. void Content(std::string val)
  113. {
  114. if (!this->HasContent) {
  115. this->S << '>';
  116. this->HasContent = true;
  117. }
  118. this->S << cmVS10EscapeXML(std::move(val));
  119. }
  120. ~Elem()
  121. {
  122. // Do not emit element which has not been started
  123. if (Tag.empty()) {
  124. return;
  125. }
  126. if (HasElements) {
  127. this->WriteString("</") << this->Tag << '>';
  128. } else if (HasContent) {
  129. this->S << "</" << this->Tag << '>';
  130. } else {
  131. this->S << " />";
  132. }
  133. }
  134. void WritePlatformConfigTag(const std::string& tag, const std::string& cond,
  135. const std::string& content);
  136. };
  137. class cmVS10GeneratorOptions : public cmVisualStudioGeneratorOptions
  138. {
  139. public:
  140. using Elem = cmVisualStudio10TargetGenerator::Elem;
  141. cmVS10GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool,
  142. cmVS7FlagTable const* table,
  143. cmVisualStudio10TargetGenerator* g = nullptr)
  144. : cmVisualStudioGeneratorOptions(lg, tool, table)
  145. , TargetGenerator(g)
  146. {
  147. }
  148. void OutputFlag(std::ostream& /*fout*/, int /*indent*/,
  149. const std::string& tag, const std::string& content) override
  150. {
  151. if (!this->GetConfiguration().empty()) {
  152. // if there are configuration specific flags, then
  153. // use the configuration specific tag for PreprocessorDefinitions
  154. const std::string cond =
  155. this->TargetGenerator->CalcCondition(this->GetConfiguration());
  156. this->Parent->WritePlatformConfigTag(tag, cond, content);
  157. } else {
  158. this->Parent->Element(tag, content);
  159. }
  160. }
  161. private:
  162. cmVisualStudio10TargetGenerator* const TargetGenerator;
  163. Elem* Parent = nullptr;
  164. friend cmVisualStudio10TargetGenerator::OptionsHelper;
  165. };
  166. struct cmVisualStudio10TargetGenerator::OptionsHelper
  167. {
  168. cmVS10GeneratorOptions& O;
  169. OptionsHelper(cmVS10GeneratorOptions& o, Elem& e)
  170. : O(o)
  171. {
  172. O.Parent = &e;
  173. }
  174. ~OptionsHelper() { O.Parent = nullptr; }
  175. void OutputPreprocessorDefinitions(const std::string& lang)
  176. {
  177. O.OutputPreprocessorDefinitions(O.Parent->S, O.Parent->Indent + 1, lang);
  178. }
  179. void OutputAdditionalIncludeDirectories(const std::string& lang)
  180. {
  181. O.OutputAdditionalIncludeDirectories(O.Parent->S, O.Parent->Indent + 1,
  182. lang);
  183. }
  184. void OutputFlagMap() { O.OutputFlagMap(O.Parent->S, O.Parent->Indent + 1); }
  185. void PrependInheritedString(std::string const& key)
  186. {
  187. O.PrependInheritedString(key);
  188. }
  189. };
  190. static std::string cmVS10EscapeComment(std::string const& comment)
  191. {
  192. // MSBuild takes the CDATA of a <Message></Message> element and just
  193. // does "echo $CDATA" with no escapes. We must encode the string.
  194. // http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx
  195. std::string echoable;
  196. for (char c : comment) {
  197. switch (c) {
  198. case '\r':
  199. break;
  200. case '\n':
  201. echoable += '\t';
  202. break;
  203. case '"': /* no break */
  204. case '|': /* no break */
  205. case '&': /* no break */
  206. case '<': /* no break */
  207. case '>': /* no break */
  208. case '^':
  209. echoable += '^'; /* no break */
  210. CM_FALLTHROUGH;
  211. default:
  212. echoable += c;
  213. break;
  214. }
  215. }
  216. return echoable;
  217. }
  218. static bool cmVS10IsTargetsFile(std::string const& path)
  219. {
  220. std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
  221. return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
  222. }
  223. static VsProjectType computeProjectType(cmGeneratorTarget const* t)
  224. {
  225. if (t->IsCSharpOnly()) {
  226. return VsProjectType::csproj;
  227. }
  228. return VsProjectType::vcxproj;
  229. }
  230. static std::string computeProjectFileExtension(VsProjectType projectType)
  231. {
  232. switch (projectType) {
  233. case VsProjectType::csproj:
  234. return ".csproj";
  235. case VsProjectType::proj:
  236. return ".proj";
  237. default:
  238. return ".vcxproj";
  239. }
  240. }
  241. static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
  242. {
  243. return computeProjectFileExtension(computeProjectType(t));
  244. }
  245. cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
  246. cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
  247. : GeneratorTarget(target)
  248. , Makefile(target->Target->GetMakefile())
  249. , Platform(gg->GetPlatformName())
  250. , Name(target->GetName())
  251. , GUID(gg->GetGUID(this->Name))
  252. , GlobalGenerator(gg)
  253. , LocalGenerator(
  254. (cmLocalVisualStudio10Generator*)target->GetLocalGenerator())
  255. {
  256. this->Configurations =
  257. this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  258. this->NsightTegra = gg->IsNsightTegra();
  259. this->Android = gg->TargetsAndroid();
  260. auto scanProp = target->GetProperty("CXX_SCAN_FOR_MODULES");
  261. for (auto const& config : this->Configurations) {
  262. if (scanProp.IsSet()) {
  263. this->ScanSourceForModuleDependencies[config] = scanProp.IsOn();
  264. } else {
  265. this->ScanSourceForModuleDependencies[config] =
  266. target->NeedCxxDyndep(config) ==
  267. cmGeneratorTarget::CxxModuleSupport::Enabled;
  268. }
  269. }
  270. for (unsigned int& version : this->NsightTegraVersion) {
  271. version = 0;
  272. }
  273. sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
  274. &this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
  275. &this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
  276. this->MSTools = !this->NsightTegra && !this->Android;
  277. this->Managed = false;
  278. this->TargetCompileAsWinRT = false;
  279. this->IsMissingFiles = false;
  280. this->DefaultArtifactDir =
  281. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  282. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  283. this->InSourceBuild = (this->Makefile->GetCurrentSourceDirectory() ==
  284. this->Makefile->GetCurrentBinaryDirectory());
  285. this->ClassifyAllConfigSources();
  286. }
  287. cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator() = default;
  288. std::string cmVisualStudio10TargetGenerator::CalcCondition(
  289. const std::string& config) const
  290. {
  291. std::ostringstream oss;
  292. oss << "'$(Configuration)|$(Platform)'=='" << config << '|' << this->Platform
  293. << '\'';
  294. // handle special case for 32 bit C# targets
  295. if (this->ProjectType == VsProjectType::csproj &&
  296. this->Platform == "Win32"_s) {
  297. oss << " Or "
  298. "'$(Configuration)|$(Platform)'=='"
  299. << config
  300. << "|x86"
  301. "'";
  302. }
  303. return oss.str();
  304. }
  305. void cmVisualStudio10TargetGenerator::Elem::WritePlatformConfigTag(
  306. const std::string& tag, const std::string& cond, const std::string& content)
  307. {
  308. Elem(*this, tag).Attribute("Condition", cond).Content(content);
  309. }
  310. std::ostream& cmVisualStudio10TargetGenerator::Elem::WriteString(
  311. const char* line)
  312. {
  313. this->S << '\n';
  314. this->S.fill(' ');
  315. this->S.width(this->Indent * 2);
  316. // write an empty string to get the fill level indent to print
  317. this->S << "";
  318. this->S << line;
  319. return this->S;
  320. }
  321. #define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
  322. #define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
  323. #define VS10_CXX_USER_PROPS \
  324. "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
  325. #define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
  326. #define VS10_CSharp_DEFAULT_PROPS \
  327. "$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
  328. // This does not seem to exist by default, it's just provided for consistency
  329. // in case users want to have default custom props for C# targets
  330. #define VS10_CSharp_USER_PROPS \
  331. "$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
  332. #define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
  333. #define VS10_CSharp_NETCF_TARGETS \
  334. "$(MSBuildExtensionsPath)\\Microsoft\\$(TargetFrameworkIdentifier)\\" \
  335. "$(TargetFrameworkTargetsVersion)\\Microsoft.$(TargetFrameworkIdentifier)" \
  336. ".CSharp.targets"
  337. void cmVisualStudio10TargetGenerator::Generate()
  338. {
  339. if (this->GeneratorTarget->IsSynthetic()) {
  340. this->GeneratorTarget->Makefile->IssueMessage(
  341. MessageType::FATAL_ERROR,
  342. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  343. "\" contains C++ modules intended for BMI-only compilation. "
  344. "This is not yet supported by the Visual Studio generator."));
  345. return;
  346. }
  347. for (std::string const& config : this->Configurations) {
  348. this->GeneratorTarget->CheckCxxModuleStatus(config);
  349. }
  350. this->ProjectType = computeProjectType(this->GeneratorTarget);
  351. this->Managed = this->ProjectType == VsProjectType::csproj;
  352. const std::string ProjectFileExtension =
  353. computeProjectFileExtension(this->ProjectType);
  354. if (this->ProjectType == VsProjectType::csproj &&
  355. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  356. std::string message =
  357. cmStrCat("The C# target \"", this->GeneratorTarget->GetName(),
  358. "\" is of type STATIC_LIBRARY. This is discouraged (and may be "
  359. "disabled in future). Make it a SHARED library instead.");
  360. this->Makefile->IssueMessage(MessageType::DEPRECATION_WARNING, message);
  361. }
  362. if (this->Android &&
  363. this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE &&
  364. !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
  365. this->GlobalGenerator->AddAndroidExecutableWarning(this->Name);
  366. }
  367. // Tell the global generator the name of the project file
  368. this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
  369. this->Name);
  370. this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
  371. ProjectFileExtension);
  372. this->DotNetHintReferences.clear();
  373. this->AdditionalUsingDirectories.clear();
  374. if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  375. if (!this->ComputeClOptions()) {
  376. return;
  377. }
  378. if (!this->ComputeRcOptions()) {
  379. return;
  380. }
  381. if (!this->ComputeCudaOptions()) {
  382. return;
  383. }
  384. if (!this->ComputeCudaLinkOptions()) {
  385. return;
  386. }
  387. if (!this->ComputeMarmasmOptions()) {
  388. return;
  389. }
  390. if (!this->ComputeMasmOptions()) {
  391. return;
  392. }
  393. if (!this->ComputeNasmOptions()) {
  394. return;
  395. }
  396. if (!this->ComputeLinkOptions()) {
  397. return;
  398. }
  399. if (!this->ComputeLibOptions()) {
  400. return;
  401. }
  402. }
  403. std::string path =
  404. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  405. this->Name, ProjectFileExtension);
  406. cmGeneratedFileStream BuildFileStream(path);
  407. const std::string& PathToProjectFile = path;
  408. BuildFileStream.SetCopyIfDifferent(true);
  409. // Write the encoding header into the file
  410. char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
  411. BuildFileStream.write(magic, 3);
  412. if (this->ProjectType == VsProjectType::csproj &&
  413. this->GeneratorTarget->IsDotNetSdkTarget() &&
  414. this->GlobalGenerator->GetVersion() >=
  415. cmGlobalVisualStudioGenerator::VSVersion::VS16) {
  416. this->WriteSdkStyleProjectFile(BuildFileStream);
  417. } else {
  418. this->WriteClassicMsBuildProjectFile(BuildFileStream);
  419. }
  420. if (BuildFileStream.Close()) {
  421. this->GlobalGenerator->FileReplacedDuringGenerate(PathToProjectFile);
  422. }
  423. // The groups are stored in a separate file for VS 10
  424. this->WriteGroups();
  425. // Update cache with project-specific entries.
  426. this->UpdateCache();
  427. }
  428. void cmVisualStudio10TargetGenerator::WriteClassicMsBuildProjectFile(
  429. cmGeneratedFileStream& BuildFileStream)
  430. {
  431. BuildFileStream << R"(<?xml version="1.0" encoding=")"
  432. << this->GlobalGenerator->Encoding() << "\"?>";
  433. {
  434. Elem e0(BuildFileStream, "Project");
  435. e0.Attribute("DefaultTargets", "Build");
  436. const char* toolsVersion = this->GlobalGenerator->GetToolsVersion();
  437. e0.Attribute("ToolsVersion", toolsVersion);
  438. e0.Attribute("xmlns",
  439. "http://schemas.microsoft.com/developer/msbuild/2003");
  440. if (this->NsightTegra) {
  441. Elem e1(e0, "PropertyGroup");
  442. e1.Attribute("Label", "NsightTegraProject");
  443. const unsigned int nsightTegraMajorVersion = this->NsightTegraVersion[0];
  444. const unsigned int nsightTegraMinorVersion = this->NsightTegraVersion[1];
  445. if (nsightTegraMajorVersion >= 2) {
  446. if (nsightTegraMajorVersion > 3 ||
  447. (nsightTegraMajorVersion == 3 && nsightTegraMinorVersion >= 1)) {
  448. e1.Element("NsightTegraProjectRevisionNumber", "11");
  449. } else {
  450. // Nsight Tegra 2.0 uses project revision 9.
  451. e1.Element("NsightTegraProjectRevisionNumber", "9");
  452. }
  453. // Tell newer versions to upgrade silently when loading.
  454. e1.Element("NsightTegraUpgradeOnceWithoutPrompt", "true");
  455. } else {
  456. // Require Nsight Tegra 1.6 for JCompile support.
  457. e1.Element("NsightTegraProjectRevisionNumber", "7");
  458. }
  459. }
  460. if (const char* hostArch =
  461. this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
  462. Elem e1(e0, "PropertyGroup");
  463. e1.Element("PreferredToolArchitecture", hostArch);
  464. }
  465. // The ALL_BUILD, PACKAGE, and ZERO_CHECK projects transitively include
  466. // Microsoft.Common.CurrentVersion.targets which triggers Target
  467. // ResolveNugetPackageAssets when SDK-style targets are in the project.
  468. // However, these projects have no nuget packages to reference and the
  469. // build fails.
  470. // Setting ResolveNugetPackages to false skips this target and the build
  471. // succeeds.
  472. cm::string_view targetName{ this->GeneratorTarget->GetName() };
  473. if (targetName == "ALL_BUILD"_s || targetName == "PACKAGE"_s ||
  474. targetName == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  475. Elem e1(e0, "PropertyGroup");
  476. e1.Element("ResolveNugetPackages", "false");
  477. }
  478. if (this->ProjectType != VsProjectType::csproj) {
  479. this->WriteProjectConfigurations(e0);
  480. }
  481. {
  482. Elem e1(e0, "PropertyGroup");
  483. this->WriteCommonPropertyGroupGlobals(e1);
  484. if ((this->MSTools || this->Android) &&
  485. this->GeneratorTarget->IsInBuildSystem()) {
  486. this->WriteApplicationTypeSettings(e1);
  487. this->VerifyNecessaryFiles();
  488. }
  489. cmValue vsProjectName =
  490. this->GeneratorTarget->GetProperty("VS_SCC_PROJECTNAME");
  491. cmValue vsLocalPath =
  492. this->GeneratorTarget->GetProperty("VS_SCC_LOCALPATH");
  493. cmValue vsProvider =
  494. this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER");
  495. if (vsProjectName && vsLocalPath && vsProvider) {
  496. e1.Element("SccProjectName", *vsProjectName);
  497. e1.Element("SccLocalPath", *vsLocalPath);
  498. e1.Element("SccProvider", *vsProvider);
  499. cmValue vsAuxPath =
  500. this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH");
  501. if (vsAuxPath) {
  502. e1.Element("SccAuxPath", *vsAuxPath);
  503. }
  504. }
  505. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
  506. e1.Element("WinMDAssembly", "true");
  507. }
  508. e1.Element("Platform", this->Platform);
  509. cmValue projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL");
  510. e1.Element("ProjectName", projLabel ? *projLabel : this->Name);
  511. {
  512. cm::optional<std::string> targetFramework;
  513. cm::optional<std::string> targetFrameworkVersion;
  514. cm::optional<std::string> targetFrameworkIdentifier;
  515. cm::optional<std::string> targetFrameworkTargetsVersion;
  516. if (cmValue tf =
  517. this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK")) {
  518. targetFramework = *tf;
  519. } else if (cmValue vstfVer = this->GeneratorTarget->GetProperty(
  520. "VS_DOTNET_TARGET_FRAMEWORK_VERSION")) {
  521. // FIXME: Someday, add a deprecation warning for VS_* property.
  522. targetFrameworkVersion = *vstfVer;
  523. } else if (cmValue tfVer = this->GeneratorTarget->GetProperty(
  524. "DOTNET_TARGET_FRAMEWORK_VERSION")) {
  525. targetFrameworkVersion = *tfVer;
  526. } else if (this->ProjectType == VsProjectType::csproj) {
  527. targetFrameworkVersion =
  528. this->GlobalGenerator->GetTargetFrameworkVersion();
  529. }
  530. if (this->ProjectType == VsProjectType::vcxproj &&
  531. this->GlobalGenerator->TargetsWindowsCE()) {
  532. e1.Element("EnableRedirectPlatform", "true");
  533. e1.Element("RedirectPlatformValue", this->Platform);
  534. }
  535. if (this->ProjectType == VsProjectType::csproj) {
  536. if (this->GlobalGenerator->TargetsWindowsCE()) {
  537. // FIXME: These target VS_TARGET_FRAMEWORK* target properties
  538. // are undocumented settings only ever supported for WinCE.
  539. // We need a better way to control these in general.
  540. if (cmValue tfId = this->GeneratorTarget->GetProperty(
  541. "VS_TARGET_FRAMEWORK_IDENTIFIER")) {
  542. targetFrameworkIdentifier = *tfId;
  543. }
  544. if (cmValue tfTargetsVer = this->GeneratorTarget->GetProperty(
  545. "VS_TARGET_FRAMEWORKS_TARGET_VERSION")) {
  546. targetFrameworkTargetsVersion = *tfTargetsVer;
  547. }
  548. }
  549. if (!targetFrameworkIdentifier) {
  550. targetFrameworkIdentifier =
  551. this->GlobalGenerator->GetTargetFrameworkIdentifier();
  552. }
  553. if (!targetFrameworkTargetsVersion) {
  554. targetFrameworkTargetsVersion =
  555. this->GlobalGenerator->GetTargetFrameworkTargetsVersion();
  556. }
  557. }
  558. if (targetFramework) {
  559. if (targetFramework->find(';') != std::string::npos) {
  560. e1.Element("TargetFrameworks", *targetFramework);
  561. } else {
  562. e1.Element("TargetFramework", *targetFramework);
  563. }
  564. }
  565. if (targetFrameworkVersion) {
  566. e1.Element("TargetFrameworkVersion", *targetFrameworkVersion);
  567. }
  568. if (targetFrameworkIdentifier) {
  569. e1.Element("TargetFrameworkIdentifier", *targetFrameworkIdentifier);
  570. }
  571. if (targetFrameworkTargetsVersion) {
  572. e1.Element("TargetFrameworkTargetsVersion",
  573. *targetFrameworkTargetsVersion);
  574. }
  575. if (!this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString()
  576. .empty()) {
  577. e1.Element(
  578. "CudaToolkitCustomDir",
  579. cmStrCat(
  580. this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString(),
  581. this->GlobalGenerator
  582. ->GetPlatformToolsetCudaNvccSubdirString()));
  583. }
  584. }
  585. // Disable the project upgrade prompt that is displayed the first time a
  586. // project using an older toolset version is opened in a newer version of
  587. // the IDE.
  588. e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
  589. if (const char* vcTargetsPath =
  590. this->GlobalGenerator->GetCustomVCTargetsPath()) {
  591. e1.Element("VCTargetsPath", vcTargetsPath);
  592. }
  593. if (this->Managed) {
  594. if (this->LocalGenerator->GetVersion() >=
  595. cmGlobalVisualStudioGenerator::VSVersion::VS17) {
  596. e1.Element("ManagedAssembly", "true");
  597. }
  598. std::string outputType;
  599. switch (this->GeneratorTarget->GetType()) {
  600. case cmStateEnums::OBJECT_LIBRARY:
  601. case cmStateEnums::STATIC_LIBRARY:
  602. case cmStateEnums::SHARED_LIBRARY:
  603. outputType = "Library";
  604. break;
  605. case cmStateEnums::MODULE_LIBRARY:
  606. outputType = "Module";
  607. break;
  608. case cmStateEnums::EXECUTABLE: {
  609. auto const win32 =
  610. this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
  611. if (win32.find("$<") != std::string::npos) {
  612. this->Makefile->IssueMessage(
  613. MessageType::FATAL_ERROR,
  614. cmStrCat(
  615. "Target \"", this->GeneratorTarget->GetName(),
  616. "\" has a generator expression in its WIN32_EXECUTABLE "
  617. "property. This is not supported on managed executables."));
  618. return;
  619. }
  620. if (cmIsOn(win32)) {
  621. outputType = "WinExe";
  622. } else {
  623. outputType = "Exe";
  624. }
  625. } break;
  626. case cmStateEnums::UTILITY:
  627. case cmStateEnums::INTERFACE_LIBRARY:
  628. case cmStateEnums::GLOBAL_TARGET:
  629. outputType = "Utility";
  630. break;
  631. case cmStateEnums::UNKNOWN_LIBRARY:
  632. break;
  633. }
  634. e1.Element("OutputType", outputType);
  635. e1.Element("AppDesignerFolder", "Properties");
  636. }
  637. }
  638. cmValue startupObject =
  639. this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
  640. if (startupObject && this->Managed) {
  641. Elem e1(e0, "PropertyGroup");
  642. e1.Element("StartupObject", *startupObject);
  643. }
  644. switch (this->ProjectType) {
  645. case VsProjectType::vcxproj: {
  646. Elem(e0, "Import").Attribute("Project", VS10_CXX_DEFAULT_PROPS);
  647. std::string const& props =
  648. this->GlobalGenerator->GetPlatformToolsetVersionProps();
  649. if (!props.empty()) {
  650. Elem(e0, "Import").Attribute("Project", props);
  651. }
  652. } break;
  653. case VsProjectType::csproj:
  654. Elem(e0, "Import")
  655. .Attribute("Project", VS10_CSharp_DEFAULT_PROPS)
  656. .Attribute("Condition", "Exists('" VS10_CSharp_DEFAULT_PROPS "')");
  657. break;
  658. default:
  659. break;
  660. }
  661. this->WriteProjectConfigurationValues(e0);
  662. if (this->ProjectType == VsProjectType::vcxproj) {
  663. Elem(e0, "Import").Attribute("Project", VS10_CXX_PROPS);
  664. }
  665. {
  666. Elem e1(e0, "ImportGroup");
  667. e1.Attribute("Label", "ExtensionSettings");
  668. e1.SetHasElements();
  669. if (this->GlobalGenerator->IsCudaEnabled()) {
  670. auto customDir =
  671. this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
  672. std::string cudaPath = customDir.empty()
  673. ? "$(VCTargetsPath)\\BuildCustomizations\\"
  674. : cmStrCat(customDir,
  675. this->GlobalGenerator
  676. ->GetPlatformToolsetCudaVSIntegrationSubdirString(),
  677. R"(extras\visual_studio_integration\MSBuildExtensions\)");
  678. Elem(e1, "Import")
  679. .Attribute("Project",
  680. cmStrCat(std::move(cudaPath), "CUDA ",
  681. this->GlobalGenerator->GetPlatformToolsetCuda(),
  682. ".props"));
  683. }
  684. if (this->GlobalGenerator->IsMarmasmEnabled()) {
  685. Elem(e1, "Import")
  686. .Attribute("Project",
  687. "$(VCTargetsPath)\\BuildCustomizations\\marmasm.props");
  688. }
  689. if (this->GlobalGenerator->IsMasmEnabled()) {
  690. Elem(e1, "Import")
  691. .Attribute("Project",
  692. "$(VCTargetsPath)\\BuildCustomizations\\masm.props");
  693. }
  694. if (this->GlobalGenerator->IsNasmEnabled()) {
  695. // Always search in the standard modules location.
  696. std::string propsTemplate =
  697. GetCMakeFilePath("Templates/MSBuild/nasm.props.in");
  698. std::string propsLocal =
  699. cmStrCat(this->DefaultArtifactDir, "\\nasm.props");
  700. ConvertToWindowsSlash(propsLocal);
  701. this->Makefile->ConfigureFile(propsTemplate, propsLocal, false, true,
  702. true);
  703. Elem(e1, "Import").Attribute("Project", propsLocal);
  704. }
  705. }
  706. {
  707. Elem e1(e0, "ImportGroup");
  708. e1.Attribute("Label", "PropertySheets");
  709. std::string props;
  710. switch (this->ProjectType) {
  711. case VsProjectType::vcxproj:
  712. props = VS10_CXX_USER_PROPS;
  713. break;
  714. case VsProjectType::csproj:
  715. props = VS10_CSharp_USER_PROPS;
  716. break;
  717. default:
  718. break;
  719. }
  720. if (cmValue p = this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
  721. props = *p;
  722. }
  723. if (!props.empty()) {
  724. ConvertToWindowsSlash(props);
  725. Elem(e1, "Import")
  726. .Attribute("Project", props)
  727. .Attribute("Condition", cmStrCat("exists('", props, "')"))
  728. .Attribute("Label", "LocalAppDataPlatform");
  729. }
  730. this->WritePlatformExtensions(e1);
  731. }
  732. this->WriteDotNetDocumentationFile(e0);
  733. Elem(e0, "PropertyGroup").Attribute("Label", "UserMacros");
  734. this->WriteWinRTPackageCertificateKeyFile(e0);
  735. this->WritePathAndIncrementalLinkOptions(e0);
  736. this->WritePublicProjectContentOptions(e0);
  737. this->WriteCEDebugProjectConfigurationValues(e0);
  738. this->WriteItemDefinitionGroups(e0);
  739. this->WriteCustomCommands(e0);
  740. this->WriteAllSources(e0);
  741. this->WriteDotNetReferences(e0);
  742. this->WriteFrameworkReferences(e0);
  743. this->WritePackageReferences(e0);
  744. this->WriteImports(e0);
  745. this->WriteEmbeddedResourceGroup(e0);
  746. this->WriteXamlFilesGroup(e0);
  747. this->WriteWinRTReferences(e0);
  748. this->WriteProjectReferences(e0);
  749. this->WriteSDKReferences(e0);
  750. switch (this->ProjectType) {
  751. case VsProjectType::vcxproj:
  752. Elem(e0, "Import").Attribute("Project", VS10_CXX_TARGETS);
  753. break;
  754. case VsProjectType::csproj:
  755. if (this->GlobalGenerator->TargetsWindowsCE()) {
  756. Elem(e0, "Import").Attribute("Project", VS10_CSharp_NETCF_TARGETS);
  757. } else {
  758. Elem(e0, "Import").Attribute("Project", VS10_CSharp_TARGETS);
  759. }
  760. break;
  761. default:
  762. break;
  763. }
  764. this->WriteTargetSpecificReferences(e0);
  765. {
  766. Elem e1(e0, "ImportGroup");
  767. e1.Attribute("Label", "ExtensionTargets");
  768. e1.SetHasElements();
  769. this->WriteTargetsFileReferences(e1);
  770. if (this->GlobalGenerator->IsCudaEnabled()) {
  771. auto customDir =
  772. this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
  773. std::string cudaPath = customDir.empty()
  774. ? "$(VCTargetsPath)\\BuildCustomizations\\"
  775. : cmStrCat(customDir,
  776. this->GlobalGenerator
  777. ->GetPlatformToolsetCudaVSIntegrationSubdirString(),
  778. R"(extras\visual_studio_integration\MSBuildExtensions\)");
  779. Elem(e1, "Import")
  780. .Attribute("Project",
  781. cmStrCat(std::move(cudaPath), "CUDA ",
  782. this->GlobalGenerator->GetPlatformToolsetCuda(),
  783. ".targets"));
  784. }
  785. if (this->GlobalGenerator->IsMarmasmEnabled()) {
  786. Elem(e1, "Import")
  787. .Attribute("Project",
  788. "$(VCTargetsPath)\\BuildCustomizations\\marmasm.targets");
  789. }
  790. if (this->GlobalGenerator->IsMasmEnabled()) {
  791. Elem(e1, "Import")
  792. .Attribute("Project",
  793. "$(VCTargetsPath)\\BuildCustomizations\\masm.targets");
  794. }
  795. if (this->GlobalGenerator->IsNasmEnabled()) {
  796. std::string nasmTargets =
  797. GetCMakeFilePath("Templates/MSBuild/nasm.targets");
  798. Elem(e1, "Import").Attribute("Project", nasmTargets);
  799. }
  800. }
  801. if (this->ProjectType == VsProjectType::vcxproj &&
  802. this->HaveCustomCommandDepfile) {
  803. std::string depfileTargets =
  804. GetCMakeFilePath("Templates/MSBuild/CustomBuildDepFile.targets");
  805. Elem(e0, "Import").Attribute("Project", depfileTargets);
  806. }
  807. if (this->ProjectType == VsProjectType::csproj) {
  808. for (std::string const& c : this->Configurations) {
  809. Elem e1(e0, "PropertyGroup");
  810. e1.Attribute("Condition",
  811. cmStrCat("'$(Configuration)' == '", c, '\''));
  812. e1.SetHasElements();
  813. this->WriteEvents(e1, c);
  814. }
  815. // make sure custom commands are executed before build (if necessary)
  816. {
  817. Elem e1(e0, "PropertyGroup");
  818. std::ostringstream oss;
  819. oss << "\n";
  820. for (std::string const& i : this->CSharpCustomCommandNames) {
  821. oss << " " << i << ";\n";
  822. }
  823. oss << " "
  824. "$(BuildDependsOn)\n";
  825. e1.Element("BuildDependsOn", oss.str());
  826. }
  827. }
  828. }
  829. }
  830. void cmVisualStudio10TargetGenerator::WriteSdkStyleProjectFile(
  831. cmGeneratedFileStream& BuildFileStream)
  832. {
  833. if (this->ProjectType != VsProjectType::csproj ||
  834. !this->GeneratorTarget->IsDotNetSdkTarget()) {
  835. std::string message =
  836. cmStrCat("The target \"", this->GeneratorTarget->GetName(),
  837. "\" is not eligible for .Net SDK style project.");
  838. this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
  839. return;
  840. }
  841. Elem e0(BuildFileStream, "Project");
  842. e0.Attribute("Sdk", *this->GeneratorTarget->GetProperty("DOTNET_SDK"));
  843. {
  844. Elem e1(e0, "PropertyGroup");
  845. this->WriteCommonPropertyGroupGlobals(e1);
  846. e1.Element("Configurations", cmJoinStrings(this->Configurations, ";", ""));
  847. e1.Element("EnableDefaultItems", "false");
  848. // Disable the project upgrade prompt that is displayed the first time a
  849. // project using an older toolset version is opened in a newer version
  850. // of the IDE.
  851. e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
  852. e1.Element("ManagedAssembly", "true");
  853. cmValue targetFramework =
  854. this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK");
  855. if (targetFramework) {
  856. if (targetFramework->find(';') != std::string::npos) {
  857. e1.Element("TargetFrameworks", *targetFramework);
  858. } else {
  859. e1.Element("TargetFramework", *targetFramework);
  860. e1.Element("AppendTargetFrameworkToOutputPath", "false");
  861. }
  862. } else {
  863. e1.Element("TargetFramework", "net5.0");
  864. e1.Element("AppendTargetFrameworkToOutputPath", "false");
  865. }
  866. std::string outputType;
  867. switch (this->GeneratorTarget->GetType()) {
  868. case cmStateEnums::OBJECT_LIBRARY:
  869. case cmStateEnums::STATIC_LIBRARY:
  870. case cmStateEnums::MODULE_LIBRARY:
  871. this->Makefile->IssueMessage(
  872. MessageType::FATAL_ERROR,
  873. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  874. "\" is of a type not supported for managed binaries."));
  875. return;
  876. case cmStateEnums::SHARED_LIBRARY:
  877. outputType = "Library";
  878. break;
  879. case cmStateEnums::EXECUTABLE: {
  880. auto const win32 =
  881. this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
  882. if (win32.find("$<") != std::string::npos) {
  883. this->Makefile->IssueMessage(
  884. MessageType::FATAL_ERROR,
  885. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  886. "\" has a generator expression in its WIN32_EXECUTABLE "
  887. "property. This is not supported on managed "
  888. "executables."));
  889. return;
  890. }
  891. if (cmIsOn(win32)) {
  892. outputType = "WinExe";
  893. } else {
  894. outputType = "Exe";
  895. }
  896. } break;
  897. case cmStateEnums::UTILITY:
  898. case cmStateEnums::INTERFACE_LIBRARY:
  899. case cmStateEnums::GLOBAL_TARGET:
  900. outputType = "Utility";
  901. break;
  902. case cmStateEnums::UNKNOWN_LIBRARY:
  903. break;
  904. }
  905. e1.Element("OutputType", outputType);
  906. cmValue startupObject =
  907. this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
  908. if (startupObject) {
  909. e1.Element("StartupObject", *startupObject);
  910. }
  911. }
  912. for (const std::string& config : this->Configurations) {
  913. Elem e1(e0, "PropertyGroup");
  914. e1.Attribute("Condition",
  915. cmStrCat("'$(Configuration)' == '", config, '\''));
  916. e1.SetHasElements();
  917. std::string outDir =
  918. cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
  919. ConvertToWindowsSlash(outDir);
  920. e1.Element("OutputPath", outDir);
  921. e1.Element("AssemblyName", GetAssemblyName(config));
  922. Options& o = *(this->ClOptions[config]);
  923. OptionsHelper oh(o, e1);
  924. oh.OutputFlagMap();
  925. }
  926. for (const std::string& config : this->Configurations) {
  927. this->WriteSdkStyleEvents(e0, config);
  928. }
  929. this->WriteDotNetDocumentationFile(e0);
  930. this->WriteCustomCommands(e0);
  931. this->WriteAllSources(e0);
  932. this->WriteEmbeddedResourceGroup(e0);
  933. this->WriteXamlFilesGroup(e0);
  934. this->WriteDotNetReferences(e0);
  935. this->WritePackageReferences(e0);
  936. this->WriteProjectReferences(e0);
  937. }
  938. void cmVisualStudio10TargetGenerator::WriteCommonPropertyGroupGlobals(Elem& e1)
  939. {
  940. e1.Attribute("Label", "Globals");
  941. e1.Element("ProjectGuid", cmStrCat('{', this->GUID, '}'));
  942. cmValue vsProjectTypes =
  943. this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
  944. if (vsProjectTypes) {
  945. const char* tagName = "ProjectTypes";
  946. if (this->ProjectType == VsProjectType::csproj) {
  947. tagName = "ProjectTypeGuids";
  948. }
  949. e1.Element(tagName, *vsProjectTypes);
  950. }
  951. cmValue vsGlobalKeyword =
  952. this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD");
  953. if (!vsGlobalKeyword) {
  954. if (this->GlobalGenerator->TargetsAndroid()) {
  955. e1.Element("Keyword", "Android");
  956. } else {
  957. e1.Element("Keyword", "Win32Proj");
  958. }
  959. } else {
  960. e1.Element("Keyword", *vsGlobalKeyword);
  961. }
  962. cmValue vsGlobalRootNamespace =
  963. this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE");
  964. if (vsGlobalRootNamespace) {
  965. e1.Element("RootNamespace", *vsGlobalRootNamespace);
  966. }
  967. std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
  968. for (std::string const& keyIt : keys) {
  969. static const cm::string_view prefix = "VS_GLOBAL_";
  970. if (!cmHasPrefix(keyIt, prefix)) {
  971. continue;
  972. }
  973. cm::string_view globalKey = cm::string_view(keyIt).substr(prefix.length());
  974. // Skip invalid or separately-handled properties.
  975. if (globalKey.empty() || globalKey == "PROJECT_TYPES"_s ||
  976. globalKey == "ROOTNAMESPACE"_s || globalKey == "KEYWORD"_s) {
  977. continue;
  978. }
  979. cmValue value = this->GeneratorTarget->GetProperty(keyIt);
  980. if (!value) {
  981. continue;
  982. }
  983. e1.Element(globalKey, *value);
  984. }
  985. }
  986. void cmVisualStudio10TargetGenerator::WritePackageReferences(Elem& e0)
  987. {
  988. std::vector<std::string> packageReferences =
  989. this->GeneratorTarget->GetPackageReferences();
  990. if (!packageReferences.empty()) {
  991. Elem e1(e0, "ItemGroup");
  992. for (std::string const& ri : packageReferences) {
  993. size_t versionIndex = ri.find_last_of('_');
  994. if (versionIndex != std::string::npos) {
  995. Elem e2(e1, "PackageReference");
  996. e2.Attribute("Include", ri.substr(0, versionIndex));
  997. e2.Attribute("Version", ri.substr(versionIndex + 1));
  998. }
  999. }
  1000. }
  1001. }
  1002. void cmVisualStudio10TargetGenerator::WriteDotNetReferences(Elem& e0)
  1003. {
  1004. cmList references;
  1005. if (cmValue vsDotNetReferences =
  1006. this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
  1007. references.assign(*vsDotNetReferences);
  1008. }
  1009. cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
  1010. for (auto const& i : props.GetList()) {
  1011. static const cm::string_view vsDnRef = "VS_DOTNET_REFERENCE_";
  1012. if (cmHasPrefix(i.first, vsDnRef)) {
  1013. std::string path = i.second;
  1014. if (!cmsys::SystemTools::FileIsFullPath(path)) {
  1015. path =
  1016. cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', path);
  1017. }
  1018. ConvertToWindowsSlash(path);
  1019. this->DotNetHintReferences[""].emplace_back(
  1020. DotNetHintReference(i.first.substr(vsDnRef.length()), path));
  1021. }
  1022. }
  1023. if (!references.empty() || !this->DotNetHintReferences.empty()) {
  1024. Elem e1(e0, "ItemGroup");
  1025. for (auto const& ri : references) {
  1026. // if the entry from VS_DOTNET_REFERENCES is an existing file, generate
  1027. // a new hint-reference and name it from the filename
  1028. if (cmsys::SystemTools::FileExists(ri, true)) {
  1029. std::string name =
  1030. cmsys::SystemTools::GetFilenameWithoutLastExtension(ri);
  1031. std::string path = ri;
  1032. ConvertToWindowsSlash(path);
  1033. this->DotNetHintReferences[""].emplace_back(
  1034. DotNetHintReference(name, path));
  1035. } else {
  1036. this->WriteDotNetReference(e1, ri, "", "");
  1037. }
  1038. }
  1039. for (const auto& h : this->DotNetHintReferences) {
  1040. // DotNetHintReferences is also populated from AddLibraries().
  1041. // The configuration specific hint references are added there.
  1042. for (const auto& i : h.second) {
  1043. this->WriteDotNetReference(e1, i.first, i.second, h.first);
  1044. }
  1045. }
  1046. }
  1047. }
  1048. void cmVisualStudio10TargetGenerator::WriteDotNetReference(
  1049. Elem& e1, std::string const& ref, std::string const& hint,
  1050. std::string const& config)
  1051. {
  1052. Elem e2(e1, "Reference");
  1053. // If 'config' is not empty, the reference is only added for the given
  1054. // configuration. This is used when referencing imported managed assemblies.
  1055. // See also cmVisualStudio10TargetGenerator::AddLibraries().
  1056. if (!config.empty()) {
  1057. e2.Attribute("Condition", this->CalcCondition(config));
  1058. }
  1059. e2.Attribute("Include", ref);
  1060. e2.Element("CopyLocalSatelliteAssemblies", "true");
  1061. e2.Element("ReferenceOutputAssembly", "true");
  1062. if (!hint.empty()) {
  1063. const char* privateReference = "True";
  1064. if (cmValue value = this->GeneratorTarget->GetProperty(
  1065. "VS_DOTNET_REFERENCES_COPY_LOCAL")) {
  1066. if (value.IsOff()) {
  1067. privateReference = "False";
  1068. }
  1069. }
  1070. e2.Element("Private", privateReference);
  1071. e2.Element("HintPath", hint);
  1072. }
  1073. this->WriteDotNetReferenceCustomTags(e2, ref);
  1074. }
  1075. void cmVisualStudio10TargetGenerator::WriteFrameworkReferences(Elem& e0)
  1076. {
  1077. cmList references;
  1078. if (cmValue vsFrameworkReferences =
  1079. this->GeneratorTarget->GetProperty("VS_FRAMEWORK_REFERENCES")) {
  1080. references.assign(*vsFrameworkReferences);
  1081. }
  1082. Elem e1(e0, "ItemGroup");
  1083. for (auto const& ref : references) {
  1084. Elem e2(e1, "FrameworkReference");
  1085. e2.Attribute("Include", ref);
  1086. }
  1087. }
  1088. void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0)
  1089. {
  1090. cmValue imports =
  1091. this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT");
  1092. if (imports) {
  1093. cmList argsSplit{ *imports };
  1094. for (auto& path : argsSplit) {
  1095. if (!cmsys::SystemTools::FileIsFullPath(path)) {
  1096. path =
  1097. cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', path);
  1098. }
  1099. ConvertToWindowsSlash(path);
  1100. Elem e1(e0, "Import");
  1101. e1.Attribute("Project", path);
  1102. }
  1103. }
  1104. }
  1105. void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
  1106. Elem& e2, std::string const& ref)
  1107. {
  1108. static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
  1109. static const std::string refpropInfix = "_TAG_";
  1110. const std::string refPropFullPrefix =
  1111. cmStrCat(refpropPrefix, ref, refpropInfix);
  1112. using CustomTags = std::map<std::string, std::string>;
  1113. CustomTags tags;
  1114. cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
  1115. for (const auto& i : props.GetList()) {
  1116. if (cmHasPrefix(i.first, refPropFullPrefix) && !i.second.empty()) {
  1117. tags[i.first.substr(refPropFullPrefix.length())] = i.second;
  1118. }
  1119. }
  1120. for (auto const& tag : tags) {
  1121. e2.Element(tag.first, tag.second);
  1122. }
  1123. }
  1124. void cmVisualStudio10TargetGenerator::WriteDotNetDocumentationFile(Elem& e0)
  1125. {
  1126. std::string const& documentationFile =
  1127. this->GeneratorTarget->GetSafeProperty("VS_DOTNET_DOCUMENTATION_FILE");
  1128. if (this->ProjectType == VsProjectType::csproj &&
  1129. !documentationFile.empty()) {
  1130. Elem e1(e0, "PropertyGroup");
  1131. Elem e2(e1, "DocumentationFile");
  1132. e2.Content(documentationFile);
  1133. }
  1134. }
  1135. void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup(Elem& e0)
  1136. {
  1137. if (!this->ResxObjs.empty()) {
  1138. Elem e1(e0, "ItemGroup");
  1139. std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
  1140. ConvertToWindowsSlash(srcDir);
  1141. for (cmSourceFile const* oi : this->ResxObjs) {
  1142. std::string obj = oi->GetFullPath();
  1143. ConvertToWindowsSlash(obj);
  1144. bool useRelativePath = false;
  1145. if (this->ProjectType == VsProjectType::csproj && this->InSourceBuild) {
  1146. // If we do an in-source build and the resource file is in a
  1147. // subdirectory
  1148. // of the .csproj file, we have to use relative pathnames, otherwise
  1149. // visual studio does not show the file in the IDE. Sorry.
  1150. if (cmHasPrefix(obj, srcDir)) {
  1151. obj = this->ConvertPath(obj, true);
  1152. ConvertToWindowsSlash(obj);
  1153. useRelativePath = true;
  1154. }
  1155. }
  1156. Elem e2(e1, "EmbeddedResource");
  1157. e2.Attribute("Include", obj);
  1158. if (this->ProjectType != VsProjectType::csproj) {
  1159. std::string hFileName =
  1160. cmStrCat(obj.substr(0, obj.find_last_of('.')), ".h");
  1161. e2.Element("DependentUpon", hFileName);
  1162. for (std::string const& c : this->Configurations) {
  1163. std::string s;
  1164. if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
  1165. // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
  1166. this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
  1167. s = "$(RootNamespace).";
  1168. }
  1169. s += "%(Filename).resources";
  1170. e2.WritePlatformConfigTag("LogicalName", this->CalcCondition(c), s);
  1171. }
  1172. } else {
  1173. std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
  1174. ConvertToWindowsSlash(binDir);
  1175. // If the resource was NOT added using a relative path (which should
  1176. // be the default), we have to provide a link here
  1177. if (!useRelativePath) {
  1178. std::string link = this->GetCSharpSourceLink(oi);
  1179. if (link.empty()) {
  1180. link = cmsys::SystemTools::GetFilenameName(obj);
  1181. }
  1182. e2.Element("Link", link);
  1183. }
  1184. // Determine if this is a generated resource from a .Designer.cs file
  1185. std::string designerResource = cmStrCat(
  1186. cmSystemTools::GetFilenamePath(oi->GetFullPath()), '/',
  1187. cmSystemTools::GetFilenameWithoutLastExtension(oi->GetFullPath()),
  1188. ".Designer.cs");
  1189. if (cmsys::SystemTools::FileExists(designerResource)) {
  1190. std::string generator = "PublicResXFileCodeGenerator";
  1191. if (cmValue g = oi->GetProperty("VS_RESOURCE_GENERATOR")) {
  1192. generator = *g;
  1193. }
  1194. if (!generator.empty()) {
  1195. e2.Element("Generator", generator);
  1196. if (cmHasPrefix(designerResource, srcDir)) {
  1197. designerResource.erase(0, srcDir.length());
  1198. } else if (cmHasPrefix(designerResource, binDir)) {
  1199. designerResource.erase(0, binDir.length());
  1200. } else {
  1201. designerResource =
  1202. cmsys::SystemTools::GetFilenameName(designerResource);
  1203. }
  1204. ConvertToWindowsSlash(designerResource);
  1205. e2.Element("LastGenOutput", designerResource);
  1206. }
  1207. }
  1208. const cmPropertyMap& props = oi->GetProperties();
  1209. for (const std::string& p : props.GetKeys()) {
  1210. static const cm::string_view propNamePrefix = "VS_CSHARP_";
  1211. if (cmHasPrefix(p, propNamePrefix)) {
  1212. cm::string_view tagName =
  1213. cm::string_view(p).substr(propNamePrefix.length());
  1214. if (!tagName.empty()) {
  1215. cmValue value = props.GetPropertyValue(p);
  1216. if (cmNonempty(value)) {
  1217. e2.Element(tagName, *value);
  1218. }
  1219. }
  1220. }
  1221. }
  1222. }
  1223. }
  1224. }
  1225. }
  1226. void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup(Elem& e0)
  1227. {
  1228. if (!this->XamlObjs.empty()) {
  1229. Elem e1(e0, "ItemGroup");
  1230. for (cmSourceFile const* oi : this->XamlObjs) {
  1231. std::string obj = oi->GetFullPath();
  1232. std::string xamlType;
  1233. cmValue xamlTypeProperty = oi->GetProperty("VS_XAML_TYPE");
  1234. if (xamlTypeProperty) {
  1235. xamlType = *xamlTypeProperty;
  1236. } else {
  1237. xamlType = "Page";
  1238. }
  1239. Elem e2(e1, xamlType);
  1240. this->WriteSource(e2, oi);
  1241. e2.SetHasElements();
  1242. e2.Element("SubType", "Designer");
  1243. }
  1244. }
  1245. }
  1246. void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences(Elem& e0)
  1247. {
  1248. if (this->MSTools) {
  1249. if (this->GlobalGenerator->TargetsWindowsPhone() &&
  1250. this->GlobalGenerator->GetSystemVersion() == "8.0"_s) {
  1251. Elem(e0, "Import")
  1252. .Attribute("Project",
  1253. "$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
  1254. "$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
  1255. "$(TargetPlatformVersion).targets");
  1256. }
  1257. }
  1258. }
  1259. void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences(Elem& e1)
  1260. {
  1261. for (TargetsFileAndConfigs const& tac : this->TargetsFileAndConfigsVec) {
  1262. std::ostringstream oss;
  1263. oss << "Exists('" << tac.File << "')";
  1264. if (!tac.Configs.empty()) {
  1265. oss << " And (";
  1266. for (size_t j = 0; j < tac.Configs.size(); ++j) {
  1267. if (j > 0) {
  1268. oss << " Or ";
  1269. }
  1270. oss << "'$(Configuration)'=='" << tac.Configs[j] << '\'';
  1271. }
  1272. oss << ')';
  1273. }
  1274. Elem(e1, "Import")
  1275. .Attribute("Project", tac.File)
  1276. .Attribute("Condition", oss.str());
  1277. }
  1278. }
  1279. void cmVisualStudio10TargetGenerator::WriteWinRTReferences(Elem& e0)
  1280. {
  1281. cmList references;
  1282. if (cmValue vsWinRTReferences =
  1283. this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) {
  1284. references.assign(*vsWinRTReferences);
  1285. }
  1286. if (this->GlobalGenerator->TargetsWindowsPhone() &&
  1287. this->GlobalGenerator->GetSystemVersion() == "8.0"_s &&
  1288. references.empty()) {
  1289. references.push_back(std::string{ "platform.winmd" });
  1290. }
  1291. if (!references.empty()) {
  1292. Elem e1(e0, "ItemGroup");
  1293. for (auto const& ri : references) {
  1294. Elem e2(e1, "Reference");
  1295. e2.Attribute("Include", ri);
  1296. e2.Element("IsWinMDFile", "true");
  1297. }
  1298. }
  1299. }
  1300. // ConfigurationType Application, Utility StaticLibrary DynamicLibrary
  1301. void cmVisualStudio10TargetGenerator::WriteProjectConfigurations(Elem& e0)
  1302. {
  1303. Elem e1(e0, "ItemGroup");
  1304. e1.Attribute("Label", "ProjectConfigurations");
  1305. for (std::string const& c : this->Configurations) {
  1306. Elem e2(e1, "ProjectConfiguration");
  1307. e2.Attribute("Include", cmStrCat(c, '|', this->Platform));
  1308. e2.Element("Configuration", c);
  1309. e2.Element("Platform", this->Platform);
  1310. }
  1311. }
  1312. void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues(Elem& e0)
  1313. {
  1314. for (std::string const& c : this->Configurations) {
  1315. Elem e1(e0, "PropertyGroup");
  1316. e1.Attribute("Condition", this->CalcCondition(c));
  1317. e1.Attribute("Label", "Configuration");
  1318. if (this->ProjectType != VsProjectType::csproj) {
  1319. std::string configType;
  1320. if (cmValue vsConfigurationType =
  1321. this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
  1322. configType = cmGeneratorExpression::Evaluate(*vsConfigurationType,
  1323. this->LocalGenerator, c);
  1324. } else {
  1325. switch (this->GeneratorTarget->GetType()) {
  1326. case cmStateEnums::SHARED_LIBRARY:
  1327. case cmStateEnums::MODULE_LIBRARY:
  1328. configType = "DynamicLibrary";
  1329. break;
  1330. case cmStateEnums::OBJECT_LIBRARY:
  1331. case cmStateEnums::STATIC_LIBRARY:
  1332. configType = "StaticLibrary";
  1333. break;
  1334. case cmStateEnums::EXECUTABLE:
  1335. if (this->NsightTegra &&
  1336. !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
  1337. // Android executables are .so too.
  1338. configType = "DynamicLibrary";
  1339. } else if (this->Android) {
  1340. configType = "DynamicLibrary";
  1341. } else {
  1342. configType = "Application";
  1343. }
  1344. break;
  1345. case cmStateEnums::UTILITY:
  1346. case cmStateEnums::INTERFACE_LIBRARY:
  1347. case cmStateEnums::GLOBAL_TARGET:
  1348. if (this->NsightTegra) {
  1349. // Tegra-Android platform does not understand "Utility".
  1350. configType = "StaticLibrary";
  1351. } else {
  1352. configType = "Utility";
  1353. }
  1354. break;
  1355. case cmStateEnums::UNKNOWN_LIBRARY:
  1356. break;
  1357. }
  1358. }
  1359. e1.Element("ConfigurationType", configType);
  1360. }
  1361. if (this->MSTools) {
  1362. if (!this->Managed) {
  1363. this->WriteMSToolConfigurationValues(e1, c);
  1364. } else {
  1365. this->WriteMSToolConfigurationValuesManaged(e1, c);
  1366. }
  1367. } else if (this->NsightTegra) {
  1368. this->WriteNsightTegraConfigurationValues(e1, c);
  1369. } else if (this->Android) {
  1370. this->WriteAndroidConfigurationValues(e1, c);
  1371. }
  1372. }
  1373. }
  1374. void cmVisualStudio10TargetGenerator::WriteCEDebugProjectConfigurationValues(
  1375. Elem& e0)
  1376. {
  1377. if (!this->GlobalGenerator->TargetsWindowsCE()) {
  1378. return;
  1379. }
  1380. cmValue additionalFiles =
  1381. this->GeneratorTarget->GetProperty("DEPLOYMENT_ADDITIONAL_FILES");
  1382. cmValue remoteDirectory =
  1383. this->GeneratorTarget->GetProperty("DEPLOYMENT_REMOTE_DIRECTORY");
  1384. if (!(additionalFiles || remoteDirectory)) {
  1385. return;
  1386. }
  1387. for (std::string const& c : this->Configurations) {
  1388. Elem e1(e0, "PropertyGroup");
  1389. e1.Attribute("Condition", this->CalcCondition(c));
  1390. if (remoteDirectory) {
  1391. e1.Element("RemoteDirectory", *remoteDirectory);
  1392. }
  1393. if (additionalFiles) {
  1394. e1.Element("CEAdditionalFiles", *additionalFiles);
  1395. }
  1396. }
  1397. }
  1398. void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
  1399. Elem& e1, std::string const& config)
  1400. {
  1401. cmValue mfcFlag = this->Makefile->GetDefinition("CMAKE_MFC_FLAG");
  1402. if (mfcFlag) {
  1403. std::string const mfcFlagValue =
  1404. cmGeneratorExpression::Evaluate(*mfcFlag, this->LocalGenerator, config);
  1405. std::string useOfMfcValue = "false";
  1406. if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  1407. if (mfcFlagValue == "1"_s) {
  1408. useOfMfcValue = "Static";
  1409. } else if (mfcFlagValue == "2"_s) {
  1410. useOfMfcValue = "Dynamic";
  1411. }
  1412. }
  1413. e1.Element("UseOfMfc", useOfMfcValue);
  1414. }
  1415. if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
  1416. this->ClOptions[config]->UsingUnicode()) ||
  1417. this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
  1418. this->GlobalGenerator->TargetsWindowsPhone() ||
  1419. this->GlobalGenerator->TargetsWindowsStore() ||
  1420. this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
  1421. e1.Element("CharacterSet", "Unicode");
  1422. } else if (this->GeneratorTarget->GetType() <=
  1423. cmStateEnums::OBJECT_LIBRARY &&
  1424. this->ClOptions[config]->UsingSBCS()) {
  1425. e1.Element("CharacterSet", "NotSet");
  1426. } else {
  1427. e1.Element("CharacterSet", "MultiByte");
  1428. }
  1429. this->WriteMSToolConfigurationValuesCommon(e1, config);
  1430. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
  1431. this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
  1432. e1.Element("WindowsAppContainer", "true");
  1433. }
  1434. if (this->IPOEnabledConfigurations.count(config) > 0) {
  1435. e1.Element("WholeProgramOptimization", "true");
  1436. }
  1437. if (this->ASanEnabledConfigurations.find(config) !=
  1438. this->ASanEnabledConfigurations.end()) {
  1439. e1.Element("EnableAsan", "true");
  1440. }
  1441. if (this->FuzzerEnabledConfigurations.find(config) !=
  1442. this->FuzzerEnabledConfigurations.end()) {
  1443. e1.Element("EnableFuzzer", "true");
  1444. }
  1445. {
  1446. auto s = this->SpectreMitigation.find(config);
  1447. if (s != this->SpectreMitigation.end()) {
  1448. e1.Element("SpectreMitigation", s->second);
  1449. }
  1450. }
  1451. }
  1452. void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
  1453. Elem& e1, std::string const& config)
  1454. {
  1455. if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  1456. return;
  1457. }
  1458. Options& o = *(this->ClOptions[config]);
  1459. if (o.UsingDebugInfo()) {
  1460. e1.Element("DebugSymbols", "true");
  1461. e1.Element("DefineDebug", "true");
  1462. }
  1463. std::string outDir =
  1464. cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
  1465. ConvertToWindowsSlash(outDir);
  1466. e1.Element("OutputPath", outDir);
  1467. if (o.HasFlag("Platform")) {
  1468. e1.Element("PlatformTarget", o.GetFlag("Platform"));
  1469. o.RemoveFlag("Platform");
  1470. }
  1471. this->WriteMSToolConfigurationValuesCommon(e1, config);
  1472. std::string assemblyName = GetAssemblyName(config);
  1473. e1.Element("AssemblyName", assemblyName);
  1474. if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
  1475. e1.Element("StartAction", "Program");
  1476. e1.Element("StartProgram", cmStrCat(outDir, assemblyName, ".exe"));
  1477. }
  1478. OptionsHelper oh(o, e1);
  1479. oh.OutputFlagMap();
  1480. }
  1481. void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesCommon(
  1482. Elem& e1, std::string const& config)
  1483. {
  1484. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  1485. if (cmValue projectToolsetOverride =
  1486. this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
  1487. e1.Element("PlatformToolset", *projectToolsetOverride);
  1488. } else if (const char* toolset = gg->GetPlatformToolset()) {
  1489. e1.Element("PlatformToolset", toolset);
  1490. }
  1491. cm::optional<bool> maybeUseDebugLibraries;
  1492. if (cmValue useDebugLibrariesProp =
  1493. this->GeneratorTarget->GetProperty("VS_USE_DEBUG_LIBRARIES")) {
  1494. // The project explicitly specified a value for this target.
  1495. // An empty string suppresses generation of the setting altogether.
  1496. std::string const useDebugLibraries = cmGeneratorExpression::Evaluate(
  1497. *useDebugLibrariesProp, this->LocalGenerator, config);
  1498. if (!useDebugLibraries.empty()) {
  1499. maybeUseDebugLibraries = cmIsOn(useDebugLibraries);
  1500. }
  1501. } else if (this->GeneratorTarget->GetPolicyStatusCMP0162() ==
  1502. cmPolicies::NEW) {
  1503. // The project did not explicitly specify a value for this target.
  1504. // If the target compiles sources for a known MSVC runtime library,
  1505. // base our default value on that.
  1506. if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  1507. maybeUseDebugLibraries = this->ClOptions[config]->UsingDebugRuntime();
  1508. }
  1509. // For other targets, such as UTILITY targets, base our default
  1510. // on the configuration name.
  1511. if (!maybeUseDebugLibraries) {
  1512. maybeUseDebugLibraries = cmSystemTools::UpperCase(config) == "DEBUG"_s;
  1513. }
  1514. }
  1515. if (maybeUseDebugLibraries) {
  1516. if (*maybeUseDebugLibraries) {
  1517. e1.Element("UseDebugLibraries", "true");
  1518. } else {
  1519. e1.Element("UseDebugLibraries", "false");
  1520. }
  1521. }
  1522. }
  1523. //----------------------------------------------------------------------------
  1524. void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
  1525. Elem& e1, std::string const&)
  1526. {
  1527. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  1528. const char* toolset = gg->GetPlatformToolset();
  1529. e1.Element("NdkToolchainVersion", toolset ? toolset : "Default");
  1530. if (cmValue minApi = this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) {
  1531. e1.Element("AndroidMinAPI", cmStrCat("android-", *minApi));
  1532. }
  1533. if (cmValue api = this->GeneratorTarget->GetProperty("ANDROID_API")) {
  1534. e1.Element("AndroidTargetAPI", cmStrCat("android-", *api));
  1535. }
  1536. if (cmValue cpuArch = this->GeneratorTarget->GetProperty("ANDROID_ARCH")) {
  1537. e1.Element("AndroidArch", *cpuArch);
  1538. }
  1539. if (cmValue stlType =
  1540. this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
  1541. e1.Element("AndroidStlType", *stlType);
  1542. }
  1543. }
  1544. void cmVisualStudio10TargetGenerator::WriteAndroidConfigurationValues(
  1545. Elem& e1, std::string const&)
  1546. {
  1547. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  1548. if (cmValue projectToolsetOverride =
  1549. this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
  1550. e1.Element("PlatformToolset", *projectToolsetOverride);
  1551. } else if (const char* toolset = gg->GetPlatformToolset()) {
  1552. e1.Element("PlatformToolset", toolset);
  1553. }
  1554. if (cmValue stlType =
  1555. this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
  1556. if (*stlType != "none"_s) {
  1557. e1.Element("UseOfStl", *stlType);
  1558. }
  1559. }
  1560. std::string const& apiLevel = gg->GetSystemVersion();
  1561. if (!apiLevel.empty()) {
  1562. e1.Element("AndroidAPILevel", cmStrCat("android-", apiLevel));
  1563. }
  1564. }
  1565. void cmVisualStudio10TargetGenerator::WriteCustomCommands(Elem& e0)
  1566. {
  1567. this->CSharpCustomCommandNames.clear();
  1568. cmSourceFile const* srcCMakeLists =
  1569. this->LocalGenerator->CreateVCProjBuildRule();
  1570. for (cmGeneratorTarget::AllConfigSource const& si :
  1571. this->GeneratorTarget->GetAllConfigSources()) {
  1572. if (si.Source == srcCMakeLists) {
  1573. // Skip explicit reference to CMakeLists.txt source.
  1574. continue;
  1575. }
  1576. this->WriteCustomCommand(e0, si.Source);
  1577. }
  1578. // Add CMakeLists.txt file with rule to re-run CMake for user convenience.
  1579. if (this->GeneratorTarget->GetType() != cmStateEnums::GLOBAL_TARGET &&
  1580. this->GeneratorTarget->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  1581. if (srcCMakeLists) {
  1582. // Write directly rather than through WriteCustomCommand because
  1583. // we do not want the de-duplication and it has no dependencies.
  1584. if (cmCustomCommand const* command = srcCMakeLists->GetCustomCommand()) {
  1585. this->WriteCustomRule(e0, srcCMakeLists, *command);
  1586. }
  1587. }
  1588. }
  1589. }
  1590. void cmVisualStudio10TargetGenerator::WriteCustomCommand(
  1591. Elem& e0, cmSourceFile const* sf)
  1592. {
  1593. if (this->LocalGenerator->GetSourcesVisited(this->GeneratorTarget)
  1594. .insert(sf)
  1595. .second) {
  1596. if (std::vector<cmSourceFile*> const* depends =
  1597. this->GeneratorTarget->GetSourceDepends(sf)) {
  1598. for (cmSourceFile const* di : *depends) {
  1599. this->WriteCustomCommand(e0, di);
  1600. }
  1601. }
  1602. if (cmCustomCommand const* command = sf->GetCustomCommand()) {
  1603. // C# projects write their <Target> within WriteCustomRule()
  1604. this->WriteCustomRule(e0, sf, *command);
  1605. }
  1606. }
  1607. }
  1608. void cmVisualStudio10TargetGenerator::WriteCustomRule(
  1609. Elem& e0, cmSourceFile const* source, cmCustomCommand const& command)
  1610. {
  1611. std::string sourcePath = source->GetFullPath();
  1612. // VS 10 will always rebuild a custom command attached to a .rule
  1613. // file that doesn't exist so create the file explicitly.
  1614. if (source->GetPropertyAsBool("__CMAKE_RULE")) {
  1615. if (!cmSystemTools::FileExists(sourcePath)) {
  1616. // Make sure the path exists for the file
  1617. std::string path = cmSystemTools::GetFilenamePath(sourcePath);
  1618. cmSystemTools::MakeDirectory(path);
  1619. cmsys::ofstream fout(sourcePath.c_str());
  1620. if (fout) {
  1621. fout << "# generated from CMake\n";
  1622. fout.flush();
  1623. fout.close();
  1624. // Force given file to have a very old timestamp, thus
  1625. // preventing dependent rebuilds.
  1626. this->ForceOld(sourcePath);
  1627. } else {
  1628. cmSystemTools::Error(cmStrCat("Could not create file: [", sourcePath,
  1629. "] ",
  1630. cmSystemTools::GetLastSystemError()));
  1631. }
  1632. }
  1633. }
  1634. cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
  1635. std::unique_ptr<Elem> spe1;
  1636. std::unique_ptr<Elem> spe2;
  1637. if (this->ProjectType != VsProjectType::csproj) {
  1638. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  1639. spe2 = cm::make_unique<Elem>(*spe1, "CustomBuild");
  1640. this->WriteSource(*spe2, source);
  1641. spe2->SetHasElements();
  1642. if (command.GetStdPipesUTF8()) {
  1643. this->WriteStdOutEncodingUtf8(*spe2);
  1644. }
  1645. } else {
  1646. Elem e1(e0, "ItemGroup");
  1647. Elem e2(e1, "None");
  1648. this->WriteSource(e2, source);
  1649. e2.SetHasElements();
  1650. }
  1651. for (std::string const& c : this->Configurations) {
  1652. cmCustomCommandGenerator ccg(command, c, lg, true);
  1653. std::string comment = lg->ConstructComment(ccg);
  1654. comment = cmVS10EscapeComment(comment);
  1655. std::string script = lg->ConstructScript(ccg);
  1656. bool symbolic = false;
  1657. // input files for custom command
  1658. std::stringstream additional_inputs;
  1659. {
  1660. const char* sep = "";
  1661. if (this->ProjectType == VsProjectType::csproj) {
  1662. // csproj files do not attach the command to a specific file
  1663. // so the primary input must be listed explicitly.
  1664. additional_inputs << source->GetFullPath();
  1665. sep = ";";
  1666. }
  1667. // Avoid listing an input more than once.
  1668. std::set<std::string> unique_inputs;
  1669. // The source is either implicit an input or has been added above.
  1670. unique_inputs.insert(source->GetFullPath());
  1671. for (std::string const& d : ccg.GetDepends()) {
  1672. std::string dep;
  1673. if (lg->GetRealDependency(d, c, dep)) {
  1674. if (!unique_inputs.insert(dep).second) {
  1675. // already listed
  1676. continue;
  1677. }
  1678. ConvertToWindowsSlash(dep);
  1679. additional_inputs << sep << dep;
  1680. sep = ";";
  1681. if (!symbolic) {
  1682. if (cmSourceFile* sf = this->Makefile->GetSource(
  1683. dep, cmSourceFileLocationKind::Known)) {
  1684. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1685. }
  1686. }
  1687. // Without UpToDateCheckInput VS will ignore the dependency files
  1688. // when doing it's fast up-to-date check and the command will not run
  1689. if (this->ProjectType == VsProjectType::csproj &&
  1690. this->GeneratorTarget->IsDotNetSdkTarget()) {
  1691. Elem e1(e0, "ItemGroup");
  1692. Elem e2(e1, "UpToDateCheckInput");
  1693. e2.Attribute("Include", dep);
  1694. }
  1695. }
  1696. }
  1697. if (this->ProjectType != VsProjectType::csproj) {
  1698. additional_inputs << sep << "%(AdditionalInputs)";
  1699. }
  1700. }
  1701. // output files for custom command
  1702. std::stringstream outputs;
  1703. {
  1704. const char* sep = "";
  1705. for (std::string const& o : ccg.GetOutputs()) {
  1706. std::string out = o;
  1707. ConvertToWindowsSlash(out);
  1708. outputs << sep << out;
  1709. sep = ";";
  1710. if (!symbolic) {
  1711. if (cmSourceFile* sf = this->Makefile->GetSource(
  1712. o, cmSourceFileLocationKind::Known)) {
  1713. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1714. }
  1715. }
  1716. }
  1717. }
  1718. script += lg->FinishConstructScript(this->ProjectType);
  1719. if (this->ProjectType == VsProjectType::csproj) {
  1720. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  1721. std::string name =
  1722. cmStrCat("CustomCommand_", c, '_', hasher.HashString(sourcePath));
  1723. this->WriteCustomRuleCSharp(e0, c, name, script, additional_inputs.str(),
  1724. outputs.str(), comment, ccg);
  1725. } else {
  1726. BuildInParallel buildInParallel = BuildInParallel::No;
  1727. if (command.GetCMP0147Status() == cmPolicies::NEW &&
  1728. !command.GetUsesTerminal() &&
  1729. !(command.HasMainDependency() && source->GetIsGenerated()) &&
  1730. !source->GetPropertyAsBool(
  1731. "VS_CUSTOM_COMMAND_DISABLE_PARALLEL_BUILD")) {
  1732. buildInParallel = BuildInParallel::Yes;
  1733. }
  1734. this->WriteCustomRuleCpp(*spe2, c, script, additional_inputs.str(),
  1735. outputs.str(), comment, ccg, symbolic,
  1736. buildInParallel);
  1737. }
  1738. }
  1739. }
  1740. void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
  1741. Elem& e2, std::string const& config, std::string const& script,
  1742. std::string const& additional_inputs, std::string const& outputs,
  1743. std::string const& comment, cmCustomCommandGenerator const& ccg,
  1744. bool symbolic, BuildInParallel buildInParallel)
  1745. {
  1746. const std::string cond = this->CalcCondition(config);
  1747. if (buildInParallel == BuildInParallel::Yes &&
  1748. this->GlobalGenerator->IsBuildInParallelSupported()) {
  1749. e2.WritePlatformConfigTag("BuildInParallel", cond, "true");
  1750. }
  1751. e2.WritePlatformConfigTag("Message", cond, comment);
  1752. e2.WritePlatformConfigTag("Command", cond, script);
  1753. e2.WritePlatformConfigTag("AdditionalInputs", cond, additional_inputs);
  1754. e2.WritePlatformConfigTag("Outputs", cond, outputs);
  1755. // Turn off linking of custom command outputs.
  1756. e2.WritePlatformConfigTag("LinkObjects", cond, "false");
  1757. if (symbolic &&
  1758. this->LocalGenerator->GetVersion() >=
  1759. cmGlobalVisualStudioGenerator::VSVersion::VS16) {
  1760. // VS >= 16.4 warn if outputs are not created, but one of our
  1761. // outputs is marked SYMBOLIC and not expected to be created.
  1762. e2.WritePlatformConfigTag("VerifyInputsAndOutputsExist", cond, "false");
  1763. }
  1764. std::string depfile = ccg.GetFullDepfile();
  1765. if (!depfile.empty()) {
  1766. this->HaveCustomCommandDepfile = true;
  1767. std::string internal_depfile = ccg.GetInternalDepfile();
  1768. ConvertToWindowsSlash(internal_depfile);
  1769. e2.WritePlatformConfigTag("DepFileAdditionalInputsFile", cond,
  1770. internal_depfile);
  1771. }
  1772. }
  1773. void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
  1774. Elem& e0, std::string const& config, std::string const& name,
  1775. std::string const& script, std::string const& inputs,
  1776. std::string const& outputs, std::string const& comment,
  1777. cmCustomCommandGenerator const& ccg)
  1778. {
  1779. if (!ccg.GetFullDepfile().empty()) {
  1780. this->Makefile->IssueMessage(
  1781. MessageType::FATAL_ERROR,
  1782. cmStrCat("CSharp target \"", this->GeneratorTarget->GetName(),
  1783. "\" does not support add_custom_command DEPFILE."));
  1784. }
  1785. this->CSharpCustomCommandNames.insert(name);
  1786. Elem e1(e0, "Target");
  1787. e1.Attribute("Condition", cmStrCat("'$(Configuration)' == '", config, '\''));
  1788. e1.S << "\n Name=\"" << name << "\"";
  1789. e1.S << "\n Inputs=\"" << cmVS10EscapeAttr(inputs) << "\"";
  1790. e1.S << "\n Outputs=\"" << cmVS10EscapeAttr(outputs) << "\"";
  1791. // Run before sources are compiled...
  1792. e1.S << "\n BeforeTargets=\"CoreCompile\""; // BeforeBuild
  1793. // ...but after output directory has been created
  1794. e1.S << "\n DependsOnTargets=\"PrepareForBuild\"";
  1795. if (!comment.empty()) {
  1796. Elem(e1, "Exec").Attribute("Command", cmStrCat("echo ", comment));
  1797. }
  1798. Elem(e1, "Exec").Attribute("Command", script);
  1799. }
  1800. std::string cmVisualStudio10TargetGenerator::ConvertPath(
  1801. std::string const& path, bool forceRelative)
  1802. {
  1803. return forceRelative
  1804. ? cmSystemTools::RelativePath(
  1805. this->LocalGenerator->GetCurrentBinaryDirectory(), path)
  1806. : path;
  1807. }
  1808. static void ConvertToWindowsSlash(std::string& s)
  1809. {
  1810. // first convert all of the slashes
  1811. for (auto& ch : s) {
  1812. if (ch == '/') {
  1813. ch = '\\';
  1814. }
  1815. }
  1816. }
  1817. void cmVisualStudio10TargetGenerator::WriteGroups()
  1818. {
  1819. if (this->ProjectType == VsProjectType::csproj) {
  1820. return;
  1821. }
  1822. // collect up group information
  1823. std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
  1824. std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
  1825. this->GeneratorTarget->GetAllConfigSources();
  1826. std::set<cmSourceGroup const*> groupsUsed;
  1827. for (cmGeneratorTarget::AllConfigSource const& si : sources) {
  1828. std::string const& source = si.Source->GetFullPath();
  1829. cmSourceGroup* sourceGroup =
  1830. this->Makefile->FindSourceGroup(source, sourceGroups);
  1831. groupsUsed.insert(sourceGroup);
  1832. }
  1833. if (cmSourceFile const* srcCMakeLists =
  1834. this->LocalGenerator->CreateVCProjBuildRule()) {
  1835. std::string const& source = srcCMakeLists->GetFullPath();
  1836. cmSourceGroup* sourceGroup =
  1837. this->Makefile->FindSourceGroup(source, sourceGroups);
  1838. groupsUsed.insert(sourceGroup);
  1839. }
  1840. this->AddMissingSourceGroups(groupsUsed, sourceGroups);
  1841. // Write out group file
  1842. std::string path = cmStrCat(
  1843. this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->Name,
  1844. computeProjectFileExtension(this->GeneratorTarget), ".filters");
  1845. cmGeneratedFileStream fout(path);
  1846. fout.SetCopyIfDifferent(true);
  1847. char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
  1848. fout.write(magic, 3);
  1849. fout << R"(<?xml version="1.0" encoding=")"
  1850. << this->GlobalGenerator->Encoding() << "\"?>";
  1851. {
  1852. Elem e0(fout, "Project");
  1853. e0.Attribute("ToolsVersion", this->GlobalGenerator->GetToolsVersion());
  1854. e0.Attribute("xmlns",
  1855. "http://schemas.microsoft.com/developer/msbuild/2003");
  1856. for (auto const& ti : this->Tools) {
  1857. this->WriteGroupSources(e0, ti.first, ti.second, sourceGroups);
  1858. }
  1859. // Added files are images and the manifest.
  1860. if (!this->AddedFiles.empty()) {
  1861. Elem e1(e0, "ItemGroup");
  1862. e1.SetHasElements();
  1863. for (std::string const& oi : this->AddedFiles) {
  1864. std::string fileName =
  1865. cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(oi));
  1866. if (fileName == "wmappmanifest.xml"_s) {
  1867. Elem e2(e1, "XML");
  1868. e2.Attribute("Include", oi);
  1869. e2.Element("Filter", "Resource Files");
  1870. } else if (cmSystemTools::GetFilenameExtension(fileName) ==
  1871. ".appxmanifest") {
  1872. Elem e2(e1, "AppxManifest");
  1873. e2.Attribute("Include", oi);
  1874. e2.Element("Filter", "Resource Files");
  1875. } else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx"_s) {
  1876. Elem e2(e1, "None");
  1877. e2.Attribute("Include", oi);
  1878. e2.Element("Filter", "Resource Files");
  1879. } else {
  1880. Elem e2(e1, "Image");
  1881. e2.Attribute("Include", oi);
  1882. e2.Element("Filter", "Resource Files");
  1883. }
  1884. }
  1885. }
  1886. if (!this->ResxObjs.empty()) {
  1887. Elem e1(e0, "ItemGroup");
  1888. for (cmSourceFile const* oi : this->ResxObjs) {
  1889. std::string obj = oi->GetFullPath();
  1890. ConvertToWindowsSlash(obj);
  1891. Elem e2(e1, "EmbeddedResource");
  1892. e2.Attribute("Include", obj);
  1893. e2.Element("Filter", "Resource Files");
  1894. }
  1895. }
  1896. {
  1897. Elem e1(e0, "ItemGroup");
  1898. e1.SetHasElements();
  1899. std::vector<cmSourceGroup const*> groupsVec(groupsUsed.begin(),
  1900. groupsUsed.end());
  1901. std::sort(groupsVec.begin(), groupsVec.end(),
  1902. [](cmSourceGroup const* l, cmSourceGroup const* r) {
  1903. return l->GetFullName() < r->GetFullName();
  1904. });
  1905. for (cmSourceGroup const* sg : groupsVec) {
  1906. std::string const& name = sg->GetFullName();
  1907. if (!name.empty()) {
  1908. std::string guidName = cmStrCat("SG_Filter_", name);
  1909. std::string guid = this->GlobalGenerator->GetGUID(guidName);
  1910. Elem e2(e1, "Filter");
  1911. e2.Attribute("Include", name);
  1912. e2.Element("UniqueIdentifier", cmStrCat('{', guid, '}'));
  1913. }
  1914. }
  1915. if (!this->ResxObjs.empty() || !this->AddedFiles.empty()) {
  1916. std::string guidName = "SG_Filter_Resource Files";
  1917. std::string guid = this->GlobalGenerator->GetGUID(guidName);
  1918. Elem e2(e1, "Filter");
  1919. e2.Attribute("Include", "Resource Files");
  1920. e2.Element("UniqueIdentifier", cmStrCat('{', guid, '}'));
  1921. e2.Element("Extensions",
  1922. "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;"
  1923. "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms");
  1924. }
  1925. }
  1926. {
  1927. if (cmValue p = this->GeneratorTarget->GetProperty("VS_FILTER_PROPS")) {
  1928. auto props = *p;
  1929. if (!props.empty()) {
  1930. ConvertToWindowsSlash(props);
  1931. Elem(e0, "Import")
  1932. .Attribute("Project", props)
  1933. .Attribute("Condition", cmStrCat("exists('", props, "')"))
  1934. .Attribute("Label", "LocalAppDataPlatform");
  1935. }
  1936. }
  1937. }
  1938. }
  1939. fout << '\n';
  1940. if (fout.Close()) {
  1941. this->GlobalGenerator->FileReplacedDuringGenerate(path);
  1942. }
  1943. }
  1944. // Add to groupsUsed empty source groups that have non-empty children.
  1945. void cmVisualStudio10TargetGenerator::AddMissingSourceGroups(
  1946. std::set<cmSourceGroup const*>& groupsUsed,
  1947. const std::vector<cmSourceGroup>& allGroups)
  1948. {
  1949. for (cmSourceGroup const& current : allGroups) {
  1950. std::vector<cmSourceGroup> const& children = current.GetGroupChildren();
  1951. if (children.empty()) {
  1952. continue; // the group is really empty
  1953. }
  1954. this->AddMissingSourceGroups(groupsUsed, children);
  1955. if (groupsUsed.count(&current) > 0) {
  1956. continue; // group has already been added to set
  1957. }
  1958. // check if it least one of the group's descendants is not empty
  1959. // (at least one child must already have been added)
  1960. auto child_it = children.begin();
  1961. while (child_it != children.end()) {
  1962. if (groupsUsed.count(&(*child_it)) > 0) {
  1963. break; // found a child that was already added => add current group too
  1964. }
  1965. child_it++;
  1966. }
  1967. if (child_it == children.end()) {
  1968. continue; // no descendants have source files => ignore this group
  1969. }
  1970. groupsUsed.insert(&current);
  1971. }
  1972. }
  1973. void cmVisualStudio10TargetGenerator::WriteGroupSources(
  1974. Elem& e0, std::string const& name, ToolSources const& sources,
  1975. std::vector<cmSourceGroup>& sourceGroups)
  1976. {
  1977. Elem e1(e0, "ItemGroup");
  1978. e1.SetHasElements();
  1979. for (ToolSource const& s : sources) {
  1980. cmSourceFile const* sf = s.SourceFile;
  1981. std::string const& source = sf->GetFullPath();
  1982. cmSourceGroup* sourceGroup =
  1983. this->Makefile->FindSourceGroup(source, sourceGroups);
  1984. std::string const& filter = sourceGroup->GetFullName();
  1985. std::string path = this->ConvertPath(source, s.RelativePath);
  1986. ConvertToWindowsSlash(path);
  1987. Elem e2(e1, name);
  1988. e2.Attribute("Include", path);
  1989. if (!filter.empty()) {
  1990. e2.Element("Filter", filter);
  1991. }
  1992. }
  1993. }
  1994. void cmVisualStudio10TargetGenerator::WriteHeaderSource(
  1995. Elem& e1, cmSourceFile const* sf, ConfigToSettings const& toolSettings)
  1996. {
  1997. std::string const& fileName = sf->GetFullPath();
  1998. Elem e2(e1, "ClInclude");
  1999. this->WriteSource(e2, sf);
  2000. if (this->IsResxHeader(fileName)) {
  2001. e2.Element("FileType", "CppForm");
  2002. } else if (this->IsXamlHeader(fileName)) {
  2003. e2.Element("DependentUpon",
  2004. fileName.substr(0, fileName.find_last_of('.')));
  2005. }
  2006. this->FinishWritingSource(e2, toolSettings);
  2007. }
  2008. void cmVisualStudio10TargetGenerator::ParseSettingsProperty(
  2009. const std::string& settingsPropertyValue, ConfigToSettings& toolSettings)
  2010. {
  2011. if (!settingsPropertyValue.empty()) {
  2012. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  2013. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  2014. ge.Parse(settingsPropertyValue);
  2015. for (const std::string& config : this->Configurations) {
  2016. std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
  2017. cmList settings{ evaluated };
  2018. for (const auto& setting : settings) {
  2019. const std::string::size_type assignment = setting.find('=');
  2020. if (assignment != std::string::npos) {
  2021. const std::string propName = setting.substr(0, assignment);
  2022. const std::string propValue = setting.substr(assignment + 1);
  2023. if (!propValue.empty()) {
  2024. toolSettings[config][propName] = propValue;
  2025. }
  2026. }
  2027. }
  2028. }
  2029. }
  2030. }
  2031. bool cmVisualStudio10TargetGenerator::PropertyIsSameInAllConfigs(
  2032. const ConfigToSettings& toolSettings, const std::string& propName)
  2033. {
  2034. std::string firstPropValue;
  2035. for (const auto& configToSettings : toolSettings) {
  2036. const std::unordered_map<std::string, std::string>& settings =
  2037. configToSettings.second;
  2038. if (firstPropValue.empty()) {
  2039. if (settings.find(propName) != settings.end()) {
  2040. firstPropValue = settings.find(propName)->second;
  2041. }
  2042. }
  2043. if (settings.find(propName) == settings.end()) {
  2044. return false;
  2045. }
  2046. if (settings.find(propName)->second != firstPropValue) {
  2047. return false;
  2048. }
  2049. }
  2050. return true;
  2051. }
  2052. void cmVisualStudio10TargetGenerator::WriteExtraSource(
  2053. Elem& e1, cmSourceFile const* sf, ConfigToSettings& toolSettings)
  2054. {
  2055. bool toolHasSettings = false;
  2056. const char* tool = "None";
  2057. std::string settingsGenerator;
  2058. std::string settingsLastGenOutput;
  2059. std::string sourceLink;
  2060. std::string subType;
  2061. std::string copyToOutDir;
  2062. std::string includeInVsix;
  2063. std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
  2064. if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
  2065. toolHasSettings = true;
  2066. }
  2067. if (ext == "hlsl"_s) {
  2068. tool = "FXCompile";
  2069. // Figure out the type of shader compiler to use.
  2070. if (cmValue st = sf->GetProperty("VS_SHADER_TYPE")) {
  2071. for (const std::string& config : this->Configurations) {
  2072. toolSettings[config]["ShaderType"] = *st;
  2073. }
  2074. }
  2075. // Figure out which entry point to use if any
  2076. if (cmValue se = sf->GetProperty("VS_SHADER_ENTRYPOINT")) {
  2077. for (const std::string& config : this->Configurations) {
  2078. toolSettings[config]["EntryPointName"] = *se;
  2079. }
  2080. }
  2081. // Figure out which shader model to use if any
  2082. if (cmValue sm = sf->GetProperty("VS_SHADER_MODEL")) {
  2083. for (const std::string& config : this->Configurations) {
  2084. toolSettings[config]["ShaderModel"] = *sm;
  2085. }
  2086. }
  2087. // Figure out which output header file to use if any
  2088. if (cmValue ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
  2089. for (const std::string& config : this->Configurations) {
  2090. toolSettings[config]["HeaderFileOutput"] = *ohf;
  2091. }
  2092. }
  2093. // Figure out which variable name to use if any
  2094. if (cmValue vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
  2095. for (const std::string& config : this->Configurations) {
  2096. toolSettings[config]["VariableName"] = *vn;
  2097. }
  2098. }
  2099. // Figure out if there's any additional flags to use
  2100. if (cmValue saf = sf->GetProperty("VS_SHADER_FLAGS")) {
  2101. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  2102. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*saf);
  2103. for (const std::string& config : this->Configurations) {
  2104. std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
  2105. if (!evaluated.empty()) {
  2106. toolSettings[config]["AdditionalOptions"] = evaluated;
  2107. }
  2108. }
  2109. }
  2110. // Figure out if debug information should be generated
  2111. if (cmValue sed = sf->GetProperty("VS_SHADER_ENABLE_DEBUG")) {
  2112. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  2113. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sed);
  2114. for (const std::string& config : this->Configurations) {
  2115. std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
  2116. if (!evaluated.empty()) {
  2117. toolSettings[config]["EnableDebuggingInformation"] =
  2118. cmIsOn(evaluated) ? "true" : "false";
  2119. }
  2120. }
  2121. }
  2122. // Figure out if optimizations should be disabled
  2123. if (cmValue sdo = sf->GetProperty("VS_SHADER_DISABLE_OPTIMIZATIONS")) {
  2124. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  2125. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sdo);
  2126. for (const std::string& config : this->Configurations) {
  2127. std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
  2128. if (!evaluated.empty()) {
  2129. toolSettings[config]["DisableOptimizations"] =
  2130. cmIsOn(evaluated) ? "true" : "false";
  2131. }
  2132. }
  2133. }
  2134. if (cmValue sofn = sf->GetProperty("VS_SHADER_OBJECT_FILE_NAME")) {
  2135. for (const std::string& config : this->Configurations) {
  2136. toolSettings[config]["ObjectFileOutput"] = *sofn;
  2137. }
  2138. }
  2139. } else if (ext == "jpg"_s || ext == "png"_s) {
  2140. tool = "Image";
  2141. } else if (ext == "resw"_s) {
  2142. tool = "PRIResource";
  2143. } else if (ext == "xml"_s) {
  2144. tool = "XML";
  2145. } else if (ext == "natvis"_s) {
  2146. tool = "Natvis";
  2147. } else if (ext == "settings"_s) {
  2148. settingsLastGenOutput =
  2149. cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
  2150. std::size_t pos = settingsLastGenOutput.find(".settings");
  2151. settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
  2152. settingsGenerator = "SettingsSingleFileGenerator";
  2153. toolHasSettings = true;
  2154. } else if (ext == "vsixmanifest"_s) {
  2155. subType = "Designer";
  2156. }
  2157. if (cmValue c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
  2158. tool = "Content";
  2159. copyToOutDir = *c;
  2160. toolHasSettings = true;
  2161. }
  2162. if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
  2163. includeInVsix = "True";
  2164. tool = "Content";
  2165. toolHasSettings = true;
  2166. }
  2167. // Collect VS_CSHARP_* property values (if some are set)
  2168. std::map<std::string, std::string> sourceFileTags;
  2169. this->GetCSharpSourceProperties(sf, sourceFileTags);
  2170. if (this->NsightTegra) {
  2171. // Nsight Tegra needs specific file types to check up-to-dateness.
  2172. std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
  2173. if (name == "androidmanifest.xml"_s || name == "build.xml"_s ||
  2174. name == "proguard.cfg"_s || name == "proguard-project.txt"_s ||
  2175. ext == "properties"_s) {
  2176. tool = "AndroidBuild";
  2177. } else if (ext == "java"_s) {
  2178. tool = "JCompile";
  2179. } else if (ext == "asm"_s || ext == "s"_s) {
  2180. tool = "ClCompile";
  2181. }
  2182. }
  2183. cmValue toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
  2184. if (cmNonempty(toolOverride)) {
  2185. tool = toolOverride->c_str();
  2186. }
  2187. std::string deployContent;
  2188. std::string deployLocation;
  2189. if (this->GlobalGenerator->TargetsWindowsPhone() ||
  2190. this->GlobalGenerator->TargetsWindowsStore()) {
  2191. cmValue content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
  2192. if (cmNonempty(content)) {
  2193. toolHasSettings = true;
  2194. deployContent = *content;
  2195. cmValue location = sf->GetProperty("VS_DEPLOYMENT_LOCATION");
  2196. if (cmNonempty(location)) {
  2197. deployLocation = *location;
  2198. }
  2199. }
  2200. }
  2201. if (ParsedToolTargetSettings.find(tool) == ParsedToolTargetSettings.end()) {
  2202. cmValue toolTargetProperty = this->GeneratorTarget->Target->GetProperty(
  2203. cmStrCat("VS_SOURCE_SETTINGS_", tool));
  2204. ConfigToSettings toolTargetSettings;
  2205. if (toolTargetProperty) {
  2206. ParseSettingsProperty(*toolTargetProperty, toolTargetSettings);
  2207. }
  2208. ParsedToolTargetSettings[tool] = toolTargetSettings;
  2209. }
  2210. for (const auto& configToSetting : ParsedToolTargetSettings[tool]) {
  2211. for (const auto& setting : configToSetting.second) {
  2212. toolSettings[configToSetting.first][setting.first] = setting.second;
  2213. }
  2214. }
  2215. if (!toolSettings.empty()) {
  2216. toolHasSettings = true;
  2217. }
  2218. Elem e2(e1, tool);
  2219. this->WriteSource(e2, sf);
  2220. if (toolHasSettings) {
  2221. e2.SetHasElements();
  2222. this->FinishWritingSource(e2, toolSettings);
  2223. if (!deployContent.empty()) {
  2224. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  2225. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  2226. ge.Parse(deployContent);
  2227. // Deployment location cannot be set on a configuration basis
  2228. if (!deployLocation.empty()) {
  2229. e2.Element("Link",
  2230. cmStrCat(deployLocation, "\\%(FileName)%(Extension)"));
  2231. }
  2232. for (auto& config : this->Configurations) {
  2233. if (cge->Evaluate(this->LocalGenerator, config) == "1"_s) {
  2234. e2.WritePlatformConfigTag(
  2235. "DeploymentContent",
  2236. cmStrCat("'$(Configuration)|$(Platform)'=='", config, '|',
  2237. this->Platform, '\''),
  2238. "true");
  2239. } else {
  2240. e2.WritePlatformConfigTag(
  2241. "ExcludedFromBuild",
  2242. cmStrCat("'$(Configuration)|$(Platform)'=='", config, '|',
  2243. this->Platform, '\''),
  2244. "true");
  2245. }
  2246. }
  2247. }
  2248. if (!settingsGenerator.empty()) {
  2249. e2.Element("Generator", settingsGenerator);
  2250. }
  2251. if (!settingsLastGenOutput.empty()) {
  2252. e2.Element("LastGenOutput", settingsLastGenOutput);
  2253. }
  2254. if (!subType.empty()) {
  2255. e2.Element("SubType", subType);
  2256. }
  2257. if (!copyToOutDir.empty()) {
  2258. e2.Element("CopyToOutputDirectory", copyToOutDir);
  2259. }
  2260. if (!includeInVsix.empty()) {
  2261. e2.Element("IncludeInVSIX", includeInVsix);
  2262. }
  2263. // write source file specific tags
  2264. this->WriteCSharpSourceProperties(e2, sourceFileTags);
  2265. }
  2266. }
  2267. void cmVisualStudio10TargetGenerator::WriteSource(Elem& e2,
  2268. cmSourceFile const* sf)
  2269. {
  2270. // Visual Studio tools append relative paths to the current dir, as in:
  2271. //
  2272. // c:\path\to\current\dir\..\..\..\relative\path\to\source.c
  2273. //
  2274. // and fail if this exceeds the maximum allowed path length. Our path
  2275. // conversion uses full paths when possible to allow deeper trees.
  2276. // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
  2277. // we must use relative paths.
  2278. bool forceRelative = sf->GetLanguage() == "CUDA"_s;
  2279. std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative);
  2280. ConvertToWindowsSlash(sourceFile);
  2281. e2.Attribute("Include", sourceFile);
  2282. if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
  2283. // For out of source projects we have to provide a link (if not specified
  2284. // via property) for every source file (besides .cs files) otherwise they
  2285. // will not be visible in VS at all.
  2286. // First we check if the file is in a source group, then we check if the
  2287. // file path is relative to current source- or binary-dir, otherwise it is
  2288. // added with the plain filename without any path. This means the file will
  2289. // show up at root-level of the csproj (where CMakeLists.txt etc. are).
  2290. std::string link = this->GetCSharpSourceLink(sf);
  2291. if (link.empty()) {
  2292. link = cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
  2293. }
  2294. e2.Element("Link", link);
  2295. }
  2296. ToolSource toolSource = { sf, forceRelative };
  2297. this->Tools[e2.Tag].push_back(toolSource);
  2298. }
  2299. void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
  2300. {
  2301. if (this->GeneratorTarget->GetType() == cmStateEnums::GLOBAL_TARGET) {
  2302. return;
  2303. }
  2304. const bool haveUnityBuild =
  2305. this->GeneratorTarget->GetPropertyAsBool("UNITY_BUILD");
  2306. if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
  2307. Elem e1(e0, "PropertyGroup");
  2308. e1.Element("EnableUnitySupport", "true");
  2309. }
  2310. Elem e1(e0, "ItemGroup");
  2311. e1.SetHasElements();
  2312. std::vector<size_t> all_configs;
  2313. for (size_t ci = 0; ci < this->Configurations.size(); ++ci) {
  2314. all_configs.push_back(ci);
  2315. }
  2316. std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
  2317. this->GeneratorTarget->GetAllConfigSources();
  2318. cmSourceFile const* srcCMakeLists =
  2319. this->LocalGenerator->CreateVCProjBuildRule();
  2320. for (cmGeneratorTarget::AllConfigSource const& si : sources) {
  2321. if (si.Source == srcCMakeLists) {
  2322. // Skip explicit reference to CMakeLists.txt source.
  2323. continue;
  2324. }
  2325. ConfigToSettings toolSettings;
  2326. for (const auto& config : this->Configurations) {
  2327. toolSettings[config];
  2328. }
  2329. if (cmValue p = si.Source->GetProperty("VS_SETTINGS")) {
  2330. ParseSettingsProperty(*p, toolSettings);
  2331. }
  2332. const char* tool = nullptr;
  2333. const cmValue toolOverride = si.Source->GetProperty("VS_TOOL_OVERRIDE");
  2334. if (cmNonempty(toolOverride)) {
  2335. // Custom tool specified: the file will be built in a user-defined way
  2336. this->WriteExtraSource(e1, si.Source, toolSettings);
  2337. } else {
  2338. switch (si.Kind) {
  2339. case cmGeneratorTarget::SourceKindAppManifest:
  2340. tool = "AppxManifest";
  2341. break;
  2342. case cmGeneratorTarget::SourceKindCertificate:
  2343. tool = "None";
  2344. break;
  2345. case cmGeneratorTarget::SourceKindCustomCommand:
  2346. // Handled elsewhere.
  2347. break;
  2348. case cmGeneratorTarget::SourceKindExternalObject:
  2349. tool = "Object";
  2350. break;
  2351. case cmGeneratorTarget::SourceKindExtra:
  2352. this->WriteExtraSource(e1, si.Source, toolSettings);
  2353. break;
  2354. case cmGeneratorTarget::SourceKindHeader:
  2355. this->WriteHeaderSource(e1, si.Source, toolSettings);
  2356. break;
  2357. case cmGeneratorTarget::SourceKindIDL:
  2358. tool = "Midl";
  2359. break;
  2360. case cmGeneratorTarget::SourceKindManifest:
  2361. // Handled elsewhere.
  2362. break;
  2363. case cmGeneratorTarget::SourceKindModuleDefinition:
  2364. tool = "None";
  2365. break;
  2366. case cmGeneratorTarget::SourceKindCxxModuleSource:
  2367. case cmGeneratorTarget::SourceKindUnityBatched:
  2368. case cmGeneratorTarget::SourceKindObjectSource: {
  2369. const std::string& lang = si.Source->GetLanguage();
  2370. if (lang == "C"_s || lang == "CXX"_s) {
  2371. tool = "ClCompile";
  2372. } else if (lang == "ASM_MARMASM"_s &&
  2373. this->GlobalGenerator->IsMarmasmEnabled()) {
  2374. tool = "MARMASM";
  2375. } else if (lang == "ASM_MASM"_s &&
  2376. this->GlobalGenerator->IsMasmEnabled()) {
  2377. tool = "MASM";
  2378. } else if (lang == "ASM_NASM"_s &&
  2379. this->GlobalGenerator->IsNasmEnabled()) {
  2380. tool = "NASM";
  2381. } else if (lang == "RC"_s) {
  2382. tool = "ResourceCompile";
  2383. } else if (lang == "CSharp"_s) {
  2384. tool = "Compile";
  2385. } else if (lang == "CUDA"_s &&
  2386. this->GlobalGenerator->IsCudaEnabled()) {
  2387. tool = "CudaCompile";
  2388. } else {
  2389. tool = "None";
  2390. }
  2391. } break;
  2392. case cmGeneratorTarget::SourceKindResx:
  2393. this->ResxObjs.push_back(si.Source);
  2394. break;
  2395. case cmGeneratorTarget::SourceKindXaml:
  2396. this->XamlObjs.push_back(si.Source);
  2397. break;
  2398. }
  2399. }
  2400. std::string config;
  2401. if (!this->Configurations.empty()) {
  2402. config = this->Configurations[si.Configs[0]];
  2403. }
  2404. auto const* fs =
  2405. this->GeneratorTarget->GetFileSetForSource(config, si.Source);
  2406. if (tool) {
  2407. // Compute set of configurations to exclude, if any.
  2408. std::vector<size_t> const& include_configs = si.Configs;
  2409. std::vector<size_t> exclude_configs;
  2410. std::set_difference(all_configs.begin(), all_configs.end(),
  2411. include_configs.begin(), include_configs.end(),
  2412. std::back_inserter(exclude_configs));
  2413. Elem e2(e1, tool);
  2414. bool isCSharp = (si.Source->GetLanguage() == "CSharp"_s);
  2415. if (isCSharp && !exclude_configs.empty()) {
  2416. std::stringstream conditions;
  2417. bool firstConditionSet{ false };
  2418. for (const auto& ci : include_configs) {
  2419. if (firstConditionSet) {
  2420. conditions << " Or ";
  2421. }
  2422. conditions << "('$(Configuration)|$(Platform)'=='"
  2423. << this->Configurations[ci] << '|' << this->Platform
  2424. << "')";
  2425. firstConditionSet = true;
  2426. }
  2427. e2.Attribute("Condition", conditions.str());
  2428. }
  2429. this->WriteSource(e2, si.Source);
  2430. bool useNativeUnityBuild = false;
  2431. if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
  2432. // Magic value taken from cmGlobalVisualStudioVersionedGenerator.cxx
  2433. static const std::string vs15 = "141";
  2434. std::string toolset =
  2435. this->GlobalGenerator->GetPlatformToolsetString();
  2436. cmSystemTools::ReplaceString(toolset, "v", "");
  2437. if (toolset.empty() ||
  2438. cmSystemTools::VersionCompareGreaterEq(toolset, vs15)) {
  2439. useNativeUnityBuild = true;
  2440. }
  2441. }
  2442. if (haveUnityBuild && strcmp(tool, "ClCompile") == 0 &&
  2443. si.Source->GetProperty("UNITY_SOURCE_FILE")) {
  2444. if (useNativeUnityBuild) {
  2445. e2.Attribute(
  2446. "IncludeInUnityFile",
  2447. si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")
  2448. ? "false"
  2449. : "true");
  2450. e2.Attribute("CustomUnityFile", "true");
  2451. std::string unityDir = cmSystemTools::GetFilenamePath(
  2452. *si.Source->GetProperty("UNITY_SOURCE_FILE"));
  2453. e2.Attribute("UnityFilesDirectory", unityDir);
  2454. } else {
  2455. // Visual Studio versions prior to 2017 15.8 do not know about unity
  2456. // builds, thus we exclude the files already part of unity sources.
  2457. if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
  2458. exclude_configs = all_configs;
  2459. }
  2460. }
  2461. }
  2462. if (haveUnityBuild && strcmp(tool, "CudaCompile") == 0 &&
  2463. si.Source->GetProperty("UNITY_SOURCE_FILE")) {
  2464. if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
  2465. exclude_configs = all_configs;
  2466. }
  2467. }
  2468. if (si.Kind == cmGeneratorTarget::SourceKindObjectSource ||
  2469. si.Kind == cmGeneratorTarget::SourceKindUnityBatched) {
  2470. this->OutputSourceSpecificFlags(e2, si.Source);
  2471. } else if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2472. this->GeneratorTarget->Makefile->IssueMessage(
  2473. MessageType::FATAL_ERROR,
  2474. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  2475. "\" has source file\n ", si.Source->GetFullPath(),
  2476. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  2477. "scheduled for compilation."));
  2478. }
  2479. if (si.Source->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  2480. e2.Element("PrecompiledHeader", "NotUsing");
  2481. }
  2482. if (!isCSharp && !exclude_configs.empty()) {
  2483. this->WriteExcludeFromBuild(e2, exclude_configs);
  2484. }
  2485. this->FinishWritingSource(e2, toolSettings);
  2486. } else if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2487. this->GeneratorTarget->Makefile->IssueMessage(
  2488. MessageType::FATAL_ERROR,
  2489. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  2490. "\" has source file\n ", si.Source->GetFullPath(),
  2491. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  2492. "scheduled for compilation."));
  2493. }
  2494. }
  2495. if (this->IsMissingFiles) {
  2496. this->WriteMissingFiles(e1);
  2497. }
  2498. }
  2499. void cmVisualStudio10TargetGenerator::FinishWritingSource(
  2500. Elem& e2, ConfigToSettings const& toolSettings)
  2501. {
  2502. std::vector<std::string> writtenSettings;
  2503. for (const auto& configSettings : toolSettings) {
  2504. for (const auto& setting : configSettings.second) {
  2505. if (std::find(writtenSettings.begin(), writtenSettings.end(),
  2506. setting.first) != writtenSettings.end()) {
  2507. continue;
  2508. }
  2509. if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
  2510. e2.Element(setting.first, setting.second);
  2511. writtenSettings.push_back(setting.first);
  2512. } else {
  2513. e2.WritePlatformConfigTag(setting.first,
  2514. cmStrCat("'$(Configuration)|$(Platform)'=='",
  2515. configSettings.first, '|',
  2516. this->Platform, '\''),
  2517. setting.second);
  2518. }
  2519. }
  2520. }
  2521. }
  2522. void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
  2523. Elem& e2, cmSourceFile const* source)
  2524. {
  2525. cmSourceFile const& sf = *source;
  2526. std::string objectName;
  2527. if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
  2528. objectName = this->GeneratorTarget->GetObjectName(&sf);
  2529. }
  2530. std::string flags;
  2531. bool configDependentFlags = false;
  2532. std::string options;
  2533. bool configDependentOptions = false;
  2534. std::string defines;
  2535. bool configDependentDefines = false;
  2536. std::string includes;
  2537. bool configDependentIncludes = false;
  2538. if (cmValue cflags = sf.GetProperty("COMPILE_FLAGS")) {
  2539. configDependentFlags =
  2540. cmGeneratorExpression::Find(*cflags) != std::string::npos;
  2541. flags += *cflags;
  2542. }
  2543. if (cmValue coptions = sf.GetProperty("COMPILE_OPTIONS")) {
  2544. configDependentOptions =
  2545. cmGeneratorExpression::Find(*coptions) != std::string::npos;
  2546. options += *coptions;
  2547. }
  2548. if (cmValue cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
  2549. configDependentDefines =
  2550. cmGeneratorExpression::Find(*cdefs) != std::string::npos;
  2551. defines += *cdefs;
  2552. }
  2553. if (cmValue cincludes = sf.GetProperty("INCLUDE_DIRECTORIES")) {
  2554. configDependentIncludes =
  2555. cmGeneratorExpression::Find(*cincludes) != std::string::npos;
  2556. includes += *cincludes;
  2557. }
  2558. // Force language if the file extension does not match.
  2559. // Note that MSVC treats the upper-case '.C' extension as C and not C++.
  2560. std::string const ext = sf.GetExtension();
  2561. std::string const extLang = ext == "C"_s
  2562. ? "C"
  2563. : this->GlobalGenerator->GetLanguageFromExtension(ext.c_str());
  2564. std::string lang = this->LocalGenerator->GetSourceFileLanguage(sf);
  2565. const char* compileAs = nullptr;
  2566. if (lang != extLang) {
  2567. if (lang == "CXX"_s) {
  2568. // force a C++ file type
  2569. compileAs = "CompileAsCpp";
  2570. } else if (lang == "C"_s) {
  2571. // force to c
  2572. compileAs = "CompileAsC";
  2573. }
  2574. }
  2575. bool noWinRT = this->TargetCompileAsWinRT && lang == "C"_s;
  2576. // for the first time we need a new line if there is something
  2577. // produced here.
  2578. if (!objectName.empty()) {
  2579. if (lang == "CUDA"_s) {
  2580. e2.Element("CompileOut", cmStrCat("$(IntDir)/", objectName));
  2581. } else {
  2582. e2.Element("ObjectFileName", cmStrCat("$(IntDir)/", objectName));
  2583. }
  2584. }
  2585. if (lang == "ASM_NASM"_s) {
  2586. if (cmValue objectDeps = sf.GetProperty("OBJECT_DEPENDS")) {
  2587. cmList depends{ *objectDeps };
  2588. for (auto& d : depends) {
  2589. ConvertToWindowsSlash(d);
  2590. }
  2591. e2.Element("AdditionalDependencies", depends.join(";"));
  2592. }
  2593. }
  2594. bool isCppModule = false;
  2595. for (std::string const& config : this->Configurations) {
  2596. this->GeneratorTarget->NeedCxxModuleSupport(lang, config);
  2597. std::string configUpper = cmSystemTools::UpperCase(config);
  2598. std::string configDefines = defines;
  2599. std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
  2600. if (cmValue ccdefs = sf.GetProperty(defPropName)) {
  2601. if (!configDefines.empty()) {
  2602. configDefines += ';';
  2603. }
  2604. configDependentDefines |=
  2605. cmGeneratorExpression::Find(*ccdefs) != std::string::npos;
  2606. configDefines += *ccdefs;
  2607. }
  2608. bool const shouldScanForModules = lang == "CXX"_s &&
  2609. this->GeneratorTarget->NeedDyndepForSource(lang, config, source);
  2610. auto const* fs =
  2611. this->GeneratorTarget->GetFileSetForSource(config, source);
  2612. const char* compileAsPerConfig = compileAs;
  2613. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2614. if (lang == "CXX"_s) {
  2615. if (fs->GetType() == "CXX_MODULES"_s) {
  2616. isCppModule = true;
  2617. if (shouldScanForModules &&
  2618. this->GlobalGenerator->IsScanDependenciesSupported()) {
  2619. // ScanSourceForModuleDependencies uses 'cl /scanDependencies' and
  2620. // can distinguish module interface units and internal partitions.
  2621. compileAsPerConfig = "CompileAsCpp";
  2622. } else {
  2623. compileAsPerConfig = "CompileAsCppModule";
  2624. }
  2625. } else {
  2626. compileAsPerConfig = "CompileAsHeaderUnit";
  2627. }
  2628. } else {
  2629. this->Makefile->IssueMessage(
  2630. MessageType::FATAL_ERROR,
  2631. cmStrCat(
  2632. "Target \"", this->GeneratorTarget->Target->GetName(),
  2633. "\" contains the source\n ", source->GetFullPath(),
  2634. "\nin a file set of type \"", fs->GetType(),
  2635. R"(" but the source is not classified as a "CXX" source.)"));
  2636. }
  2637. }
  2638. // We have pch state in the following situation:
  2639. // 1. We have SKIP_PRECOMPILE_HEADERS == true
  2640. // 2. We are creating the pre-compiled header
  2641. // 3. We are a different language than the linker language AND pch is
  2642. // enabled.
  2643. std::string const& linkLanguage =
  2644. this->GeneratorTarget->GetLinkerLanguage(config);
  2645. std::string const& pchSource =
  2646. this->GeneratorTarget->GetPchSource(config, lang);
  2647. const bool skipPCH =
  2648. pchSource.empty() || sf.GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS");
  2649. const bool makePCH = (sf.GetFullPath() == pchSource);
  2650. const bool useSharedPCH = !skipPCH && (lang == linkLanguage);
  2651. const bool useDifferentLangPCH = !skipPCH && (lang != linkLanguage);
  2652. const bool useNoPCH = skipPCH && (lang != linkLanguage) &&
  2653. !this->GeneratorTarget->GetPchHeader(config, linkLanguage).empty();
  2654. const bool needsPCHFlags =
  2655. (makePCH || useSharedPCH || useDifferentLangPCH || useNoPCH);
  2656. // if we have flags or defines for this config then
  2657. // use them
  2658. if (!flags.empty() || !options.empty() || !configDefines.empty() ||
  2659. !includes.empty() || compileAsPerConfig || noWinRT ||
  2660. !options.empty() || needsPCHFlags ||
  2661. (shouldScanForModules !=
  2662. this->ScanSourceForModuleDependencies[config])) {
  2663. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  2664. cmIDEFlagTable const* flagtable = nullptr;
  2665. const std::string& srclang = source->GetLanguage();
  2666. if (srclang == "C"_s || srclang == "CXX"_s) {
  2667. flagtable = gg->GetClFlagTable();
  2668. } else if (srclang == "ASM_MARMASM"_s &&
  2669. this->GlobalGenerator->IsMarmasmEnabled()) {
  2670. flagtable = gg->GetMarmasmFlagTable();
  2671. } else if (srclang == "ASM_MASM"_s &&
  2672. this->GlobalGenerator->IsMasmEnabled()) {
  2673. flagtable = gg->GetMasmFlagTable();
  2674. } else if (lang == "ASM_NASM"_s &&
  2675. this->GlobalGenerator->IsNasmEnabled()) {
  2676. flagtable = gg->GetNasmFlagTable();
  2677. } else if (srclang == "RC"_s) {
  2678. flagtable = gg->GetRcFlagTable();
  2679. } else if (srclang == "CSharp"_s) {
  2680. flagtable = gg->GetCSharpFlagTable();
  2681. }
  2682. cmGeneratorExpressionInterpreter genexInterpreter(
  2683. this->LocalGenerator, config, this->GeneratorTarget, lang);
  2684. cmVS10GeneratorOptions clOptions(
  2685. this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
  2686. flagtable, this);
  2687. if (compileAsPerConfig) {
  2688. clOptions.AddFlag("CompileAs", compileAsPerConfig);
  2689. }
  2690. if (shouldScanForModules !=
  2691. this->ScanSourceForModuleDependencies[config]) {
  2692. clOptions.AddFlag("ScanSourceForModuleDependencies",
  2693. shouldScanForModules ? "true" : "false");
  2694. }
  2695. if (noWinRT) {
  2696. clOptions.AddFlag("CompileAsWinRT", "false");
  2697. }
  2698. if (configDependentFlags) {
  2699. clOptions.Parse(genexInterpreter.Evaluate(flags, "COMPILE_FLAGS"));
  2700. } else {
  2701. clOptions.Parse(flags);
  2702. }
  2703. if (needsPCHFlags) {
  2704. // Add precompile headers compile options.
  2705. if (makePCH) {
  2706. clOptions.AddFlag("PrecompiledHeader", "Create");
  2707. std::string pchHeader =
  2708. this->GeneratorTarget->GetPchHeader(config, lang);
  2709. clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
  2710. std::string pchFile =
  2711. this->GeneratorTarget->GetPchFile(config, lang);
  2712. clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
  2713. clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
  2714. } else if (useNoPCH) {
  2715. clOptions.AddFlag("PrecompiledHeader", "NotUsing");
  2716. } else if (useSharedPCH) {
  2717. std::string pchHeader =
  2718. this->GeneratorTarget->GetPchHeader(config, lang);
  2719. clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
  2720. } else if (useDifferentLangPCH) {
  2721. clOptions.AddFlag("PrecompiledHeader", "Use");
  2722. std::string pchHeader =
  2723. this->GeneratorTarget->GetPchHeader(config, lang);
  2724. clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
  2725. std::string pchFile =
  2726. this->GeneratorTarget->GetPchFile(config, lang);
  2727. clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
  2728. clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
  2729. }
  2730. }
  2731. if (!options.empty()) {
  2732. std::string expandedOptions;
  2733. if (configDependentOptions) {
  2734. this->LocalGenerator->AppendCompileOptions(
  2735. expandedOptions,
  2736. genexInterpreter.Evaluate(options, "COMPILE_OPTIONS"));
  2737. } else {
  2738. this->LocalGenerator->AppendCompileOptions(expandedOptions, options);
  2739. }
  2740. clOptions.Parse(expandedOptions);
  2741. }
  2742. if (clOptions.HasFlag("DisableSpecificWarnings")) {
  2743. clOptions.AppendFlag("DisableSpecificWarnings",
  2744. "%(DisableSpecificWarnings)");
  2745. }
  2746. if (clOptions.HasFlag("ForcedIncludeFiles")) {
  2747. clOptions.AppendFlag("ForcedIncludeFiles", "%(ForcedIncludeFiles)");
  2748. }
  2749. if (configDependentDefines) {
  2750. clOptions.AddDefines(
  2751. genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS"));
  2752. } else {
  2753. clOptions.AddDefines(configDefines);
  2754. }
  2755. std::vector<std::string> includeList;
  2756. if (configDependentIncludes) {
  2757. this->LocalGenerator->AppendIncludeDirectories(
  2758. includeList,
  2759. genexInterpreter.Evaluate(includes, "INCLUDE_DIRECTORIES"), *source);
  2760. } else {
  2761. this->LocalGenerator->AppendIncludeDirectories(includeList, includes,
  2762. *source);
  2763. }
  2764. clOptions.AddIncludes(includeList);
  2765. clOptions.SetConfiguration(config);
  2766. OptionsHelper oh(clOptions, e2);
  2767. oh.PrependInheritedString("AdditionalOptions");
  2768. oh.OutputAdditionalIncludeDirectories(lang);
  2769. oh.OutputFlagMap();
  2770. oh.OutputPreprocessorDefinitions(lang);
  2771. }
  2772. }
  2773. if (isCppModule && !objectName.empty()) {
  2774. std::string baseName = cmStrCat("$(IntDir)/", objectName);
  2775. cmStripSuffixIfExists(baseName, ".obj");
  2776. e2.Element("ModuleOutputFile", cmStrCat(baseName, ".ifc"));
  2777. e2.Element("ModuleDependenciesFile", cmStrCat(baseName, ".module.json"));
  2778. }
  2779. if (this->IsXamlSource(source->GetFullPath())) {
  2780. const std::string& fileName = source->GetFullPath();
  2781. e2.Element("DependentUpon",
  2782. fileName.substr(0, fileName.find_last_of('.')));
  2783. }
  2784. if (this->ProjectType == VsProjectType::csproj) {
  2785. using CsPropMap = std::map<std::string, std::string>;
  2786. CsPropMap sourceFileTags;
  2787. this->GetCSharpSourceProperties(&sf, sourceFileTags);
  2788. // write source file specific tags
  2789. if (!sourceFileTags.empty()) {
  2790. this->WriteCSharpSourceProperties(e2, sourceFileTags);
  2791. }
  2792. }
  2793. }
  2794. void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild(
  2795. Elem& e2, std::vector<size_t> const& exclude_configs)
  2796. {
  2797. for (size_t ci : exclude_configs) {
  2798. e2.WritePlatformConfigTag("ExcludedFromBuild",
  2799. cmStrCat("'$(Configuration)|$(Platform)'=='",
  2800. this->Configurations[ci], '|',
  2801. this->Platform, '\''),
  2802. "true");
  2803. }
  2804. }
  2805. void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions(
  2806. Elem& e0)
  2807. {
  2808. cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
  2809. if (ttype > cmStateEnums::INTERFACE_LIBRARY) {
  2810. return;
  2811. }
  2812. if (this->ProjectType == VsProjectType::csproj) {
  2813. return;
  2814. }
  2815. Elem e1(e0, "PropertyGroup");
  2816. e1.Element("_ProjectFileVersion", "10.0.20506.1");
  2817. for (std::string const& config : this->Configurations) {
  2818. const std::string cond = this->CalcCondition(config);
  2819. if (ttype >= cmStateEnums::UTILITY) {
  2820. e1.WritePlatformConfigTag(
  2821. "IntDir", cond, R"($(Platform)\$(Configuration)\$(ProjectName)\)");
  2822. } else {
  2823. if (ttype == cmStateEnums::SHARED_LIBRARY ||
  2824. ttype == cmStateEnums::MODULE_LIBRARY ||
  2825. ttype == cmStateEnums::EXECUTABLE) {
  2826. auto linker = this->GeneratorTarget->GetLinkerTool(config);
  2827. if (!linker.empty()) {
  2828. ConvertToWindowsSlash(linker);
  2829. e1.WritePlatformConfigTag("LinkToolExe", cond, linker);
  2830. }
  2831. }
  2832. std::string intermediateDir = cmStrCat(
  2833. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/',
  2834. config, '/');
  2835. std::string outDir;
  2836. std::string targetNameFull;
  2837. if (ttype == cmStateEnums::OBJECT_LIBRARY) {
  2838. outDir = intermediateDir;
  2839. targetNameFull = cmStrCat(this->GeneratorTarget->GetName(), ".lib");
  2840. } else {
  2841. outDir = cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
  2842. targetNameFull = this->GeneratorTarget->GetFullName(config);
  2843. }
  2844. ConvertToWindowsSlash(intermediateDir);
  2845. ConvertToWindowsSlash(outDir);
  2846. e1.WritePlatformConfigTag("OutDir", cond, outDir);
  2847. e1.WritePlatformConfigTag("IntDir", cond, intermediateDir);
  2848. if (cmValue sdkExecutableDirectories = this->Makefile->GetDefinition(
  2849. "CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES")) {
  2850. e1.WritePlatformConfigTag("ExecutablePath", cond,
  2851. *sdkExecutableDirectories);
  2852. }
  2853. if (cmValue sdkIncludeDirectories = this->Makefile->GetDefinition(
  2854. "CMAKE_VS_SDK_INCLUDE_DIRECTORIES")) {
  2855. e1.WritePlatformConfigTag("IncludePath", cond, *sdkIncludeDirectories);
  2856. }
  2857. if (cmValue sdkReferenceDirectories = this->Makefile->GetDefinition(
  2858. "CMAKE_VS_SDK_REFERENCE_DIRECTORIES")) {
  2859. e1.WritePlatformConfigTag("ReferencePath", cond,
  2860. *sdkReferenceDirectories);
  2861. }
  2862. if (cmValue sdkLibraryDirectories = this->Makefile->GetDefinition(
  2863. "CMAKE_VS_SDK_LIBRARY_DIRECTORIES")) {
  2864. e1.WritePlatformConfigTag("LibraryPath", cond, *sdkLibraryDirectories);
  2865. }
  2866. if (cmValue sdkLibraryWDirectories = this->Makefile->GetDefinition(
  2867. "CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES")) {
  2868. e1.WritePlatformConfigTag("LibraryWPath", cond,
  2869. *sdkLibraryWDirectories);
  2870. }
  2871. if (cmValue sdkSourceDirectories =
  2872. this->Makefile->GetDefinition("CMAKE_VS_SDK_SOURCE_DIRECTORIES")) {
  2873. e1.WritePlatformConfigTag("SourcePath", cond, *sdkSourceDirectories);
  2874. }
  2875. if (cmValue sdkExcludeDirectories = this->Makefile->GetDefinition(
  2876. "CMAKE_VS_SDK_EXCLUDE_DIRECTORIES")) {
  2877. e1.WritePlatformConfigTag("ExcludePath", cond, *sdkExcludeDirectories);
  2878. }
  2879. std::string name =
  2880. cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
  2881. e1.WritePlatformConfigTag("TargetName", cond, name);
  2882. std::string ext =
  2883. cmSystemTools::GetFilenameLastExtension(targetNameFull);
  2884. if (ext.empty()) {
  2885. // An empty TargetExt causes a default extension to be used.
  2886. // A single "." appears to be treated as an empty extension.
  2887. ext = ".";
  2888. }
  2889. e1.WritePlatformConfigTag("TargetExt", cond, ext);
  2890. this->OutputLinkIncremental(e1, config);
  2891. }
  2892. if (ttype <= cmStateEnums::UTILITY) {
  2893. if (cmValue workingDir = this->GeneratorTarget->GetProperty(
  2894. "VS_DEBUGGER_WORKING_DIRECTORY")) {
  2895. std::string genWorkingDir = cmGeneratorExpression::Evaluate(
  2896. *workingDir, this->LocalGenerator, config);
  2897. e1.WritePlatformConfigTag("LocalDebuggerWorkingDirectory", cond,
  2898. genWorkingDir);
  2899. }
  2900. if (cmValue environment =
  2901. this->GeneratorTarget->GetProperty("VS_DEBUGGER_ENVIRONMENT")) {
  2902. std::string genEnvironment = cmGeneratorExpression::Evaluate(
  2903. *environment, this->LocalGenerator, config);
  2904. e1.WritePlatformConfigTag("LocalDebuggerEnvironment", cond,
  2905. genEnvironment);
  2906. }
  2907. if (cmValue debuggerCommand =
  2908. this->GeneratorTarget->GetProperty("VS_DEBUGGER_COMMAND")) {
  2909. std::string genDebuggerCommand = cmGeneratorExpression::Evaluate(
  2910. *debuggerCommand, this->LocalGenerator, config);
  2911. e1.WritePlatformConfigTag("LocalDebuggerCommand", cond,
  2912. genDebuggerCommand);
  2913. }
  2914. if (cmValue commandArguments = this->GeneratorTarget->GetProperty(
  2915. "VS_DEBUGGER_COMMAND_ARGUMENTS")) {
  2916. std::string genCommandArguments = cmGeneratorExpression::Evaluate(
  2917. *commandArguments, this->LocalGenerator, config);
  2918. e1.WritePlatformConfigTag("LocalDebuggerCommandArguments", cond,
  2919. genCommandArguments);
  2920. }
  2921. }
  2922. }
  2923. }
  2924. void cmVisualStudio10TargetGenerator::WritePublicProjectContentOptions(
  2925. Elem& e0)
  2926. {
  2927. cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
  2928. if (ttype != cmStateEnums::SHARED_LIBRARY) {
  2929. return;
  2930. }
  2931. if (this->ProjectType != VsProjectType::vcxproj) {
  2932. return;
  2933. }
  2934. Elem e1(e0, "PropertyGroup");
  2935. for (std::string const& config : this->Configurations) {
  2936. if (this->GeneratorTarget->HaveCxx20ModuleSources() &&
  2937. this->GeneratorTarget->HaveCxxModuleSupport(config) ==
  2938. cmGeneratorTarget::Cxx20SupportLevel::Supported) {
  2939. const std::string cond = this->CalcCondition(config);
  2940. // For DLL projects, we export all BMIs for now
  2941. e1.WritePlatformConfigTag("AllProjectBMIsArePublic", cond, "true");
  2942. }
  2943. }
  2944. }
  2945. void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
  2946. Elem& e1, std::string const& configName)
  2947. {
  2948. if (!this->MSTools) {
  2949. return;
  2950. }
  2951. if (this->ProjectType == VsProjectType::csproj) {
  2952. return;
  2953. }
  2954. // static libraries and things greater than modules do not need
  2955. // to set this option
  2956. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2957. this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
  2958. return;
  2959. }
  2960. Options& linkOptions = *(this->LinkOptions[configName]);
  2961. const std::string cond = this->CalcCondition(configName);
  2962. if (this->IPOEnabledConfigurations.count(configName) > 0) {
  2963. // Suppress LinkIncremental in favor of WholeProgramOptimization.
  2964. e1.WritePlatformConfigTag("LinkIncremental", cond, "");
  2965. } else {
  2966. const char* incremental = linkOptions.GetFlag("LinkIncremental");
  2967. e1.WritePlatformConfigTag("LinkIncremental", cond,
  2968. (incremental ? incremental : "true"));
  2969. }
  2970. linkOptions.RemoveFlag("LinkIncremental");
  2971. const char* manifest = linkOptions.GetFlag("GenerateManifest");
  2972. e1.WritePlatformConfigTag("GenerateManifest", cond,
  2973. (manifest ? manifest : "true"));
  2974. linkOptions.RemoveFlag("GenerateManifest");
  2975. // Some link options belong here. Use them now and remove them so that
  2976. // WriteLinkOptions does not use them.
  2977. static const std::vector<std::string> flags{ "LinkDelaySign",
  2978. "LinkKeyFile" };
  2979. for (const std::string& flag : flags) {
  2980. if (const char* value = linkOptions.GetFlag(flag)) {
  2981. e1.WritePlatformConfigTag(flag, cond, value);
  2982. linkOptions.RemoveFlag(flag);
  2983. }
  2984. }
  2985. }
  2986. std::vector<std::string> cmVisualStudio10TargetGenerator::GetIncludes(
  2987. std::string const& config, std::string const& lang) const
  2988. {
  2989. std::vector<std::string> includes;
  2990. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  2991. lang, config);
  2992. for (std::string& i : includes) {
  2993. ConvertToWindowsSlash(i);
  2994. }
  2995. return includes;
  2996. }
  2997. std::string cmVisualStudio10TargetGenerator::GetTargetOutputName() const
  2998. {
  2999. std::string config;
  3000. if (!this->Configurations.empty()) {
  3001. config = this->Configurations[0];
  3002. }
  3003. const auto& nameComponents =
  3004. this->GeneratorTarget->GetFullNameComponents(config);
  3005. return cmStrCat(nameComponents.prefix, nameComponents.base);
  3006. }
  3007. std::string cmVisualStudio10TargetGenerator::GetAssemblyName(
  3008. std::string const& config) const
  3009. {
  3010. std::string postfixName =
  3011. cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
  3012. std::string assemblyName = this->GeneratorTarget->GetOutputName(
  3013. config, cmStateEnums::RuntimeBinaryArtifact);
  3014. if (cmValue postfix = this->GeneratorTarget->GetProperty(postfixName)) {
  3015. assemblyName += *postfix;
  3016. }
  3017. return assemblyName;
  3018. }
  3019. bool cmVisualStudio10TargetGenerator::ComputeClOptions()
  3020. {
  3021. return std::all_of(
  3022. this->Configurations.begin(), this->Configurations.end(),
  3023. [this](std::string const& c) { return this->ComputeClOptions(c); });
  3024. }
  3025. bool cmVisualStudio10TargetGenerator::ComputeClOptions(
  3026. std::string const& configName)
  3027. {
  3028. // much of this was copied from here:
  3029. // copied from cmLocalVisualStudio7Generator.cxx 805
  3030. // TODO: Integrate code below with cmLocalVisualStudio7Generator.
  3031. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3032. std::unique_ptr<Options> pOptions;
  3033. switch (this->ProjectType) {
  3034. case VsProjectType::vcxproj:
  3035. pOptions = cm::make_unique<Options>(
  3036. this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
  3037. break;
  3038. case VsProjectType::csproj:
  3039. pOptions =
  3040. cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
  3041. gg->GetCSharpFlagTable());
  3042. break;
  3043. default:
  3044. break;
  3045. }
  3046. Options& clOptions = *pOptions;
  3047. std::string flags;
  3048. const std::string& linkLanguage =
  3049. this->GeneratorTarget->GetLinkerLanguage(configName);
  3050. if (linkLanguage.empty()) {
  3051. cmSystemTools::Error(cmStrCat(
  3052. "CMake can not determine linker language for target: ", this->Name));
  3053. return false;
  3054. }
  3055. // Choose a language whose flags to use for ClCompile.
  3056. static const char* clLangs[] = { "CXX", "C", "Fortran" };
  3057. std::string langForClCompile;
  3058. if (this->ProjectType == VsProjectType::csproj) {
  3059. langForClCompile = "CSharp";
  3060. } else if (cm::contains(clLangs, linkLanguage)) {
  3061. langForClCompile = linkLanguage;
  3062. } else {
  3063. std::set<std::string> languages;
  3064. this->GeneratorTarget->GetLanguages(languages, configName);
  3065. for (const char* l : clLangs) {
  3066. if (languages.count(l)) {
  3067. langForClCompile = l;
  3068. break;
  3069. }
  3070. }
  3071. }
  3072. this->LangForClCompile = langForClCompile;
  3073. if (!langForClCompile.empty()) {
  3074. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3075. cmBuildStep::Compile,
  3076. langForClCompile, configName);
  3077. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3078. langForClCompile, configName);
  3079. }
  3080. // Put the IPO enabled configurations into a set.
  3081. if (this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName)) {
  3082. this->IPOEnabledConfigurations.insert(configName);
  3083. }
  3084. // Check if ASan is enabled.
  3085. if (flags.find("/fsanitize=address") != std::string::npos ||
  3086. flags.find("-fsanitize=address") != std::string::npos) {
  3087. this->ASanEnabledConfigurations.insert(configName);
  3088. }
  3089. // Check if (lib)Fuzzer is enabled.
  3090. if (flags.find("/fsanitize=fuzzer") != std::string::npos ||
  3091. flags.find("-fsanitize=fuzzer") != std::string::npos) {
  3092. this->FuzzerEnabledConfigurations.insert(configName);
  3093. }
  3094. // Precompile Headers
  3095. std::string pchHeader =
  3096. this->GeneratorTarget->GetPchHeader(configName, linkLanguage);
  3097. if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
  3098. pchHeader.empty()) {
  3099. clOptions.AddFlag("PrecompiledHeader", "NotUsing");
  3100. } else if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
  3101. !pchHeader.empty()) {
  3102. clOptions.AddFlag("PrecompiledHeader", "Use");
  3103. clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
  3104. std::string pchFile =
  3105. this->GeneratorTarget->GetPchFile(configName, linkLanguage);
  3106. clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
  3107. }
  3108. // Get preprocessor definitions for this directory.
  3109. std::string defineFlags = this->Makefile->GetDefineFlags();
  3110. if (this->MSTools) {
  3111. if (this->ProjectType == VsProjectType::vcxproj) {
  3112. clOptions.FixExceptionHandlingDefault();
  3113. if (this->GlobalGenerator->GetVersion() >=
  3114. cmGlobalVisualStudioGenerator::VSVersion::VS15) {
  3115. // Toolsets that come with VS 2017 may now enable UseFullPaths
  3116. // by default and there is no negative /FC option that projects
  3117. // can use to switch it back. Older toolsets disable this by
  3118. // default anyway so this will not hurt them. If the project
  3119. // is using an explicit /FC option then parsing flags will
  3120. // replace this setting with "true" below.
  3121. clOptions.AddFlag("UseFullPaths", "false");
  3122. }
  3123. clOptions.AddFlag("AssemblerListingLocation", "$(IntDir)");
  3124. }
  3125. }
  3126. // check for managed C++ assembly compiler flag. This overrides any
  3127. // /clr* compiler flags which may be defined in the flags variable(s).
  3128. if (this->ProjectType != VsProjectType::csproj) {
  3129. // Warn if /clr was added manually. This should not be done
  3130. // anymore, because cmGeneratorTarget may not be aware that the
  3131. // target uses C++/CLI.
  3132. if (flags.find("/clr") != std::string::npos ||
  3133. flags.find("-clr") != std::string::npos ||
  3134. defineFlags.find("/clr") != std::string::npos ||
  3135. defineFlags.find("-clr") != std::string::npos) {
  3136. if (configName == this->Configurations[0]) {
  3137. std::string message =
  3138. cmStrCat("For the target \"", this->GeneratorTarget->GetName(),
  3139. "\" the /clr compiler flag was added manually. ",
  3140. "Set usage of C++/CLI by setting COMMON_LANGUAGE_RUNTIME "
  3141. "target property.");
  3142. this->Makefile->IssueMessage(MessageType::WARNING, message);
  3143. }
  3144. }
  3145. if (cmValue clr =
  3146. this->GeneratorTarget->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  3147. std::string clrString = *clr;
  3148. if (!clrString.empty()) {
  3149. clrString = cmStrCat(':', clrString);
  3150. }
  3151. flags += cmStrCat(" /clr", clrString);
  3152. }
  3153. }
  3154. // Get includes for this target
  3155. if (!this->LangForClCompile.empty()) {
  3156. auto includeList = this->GetIncludes(configName, this->LangForClCompile);
  3157. auto sysIncludeFlag = this->Makefile->GetDefinition(
  3158. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile));
  3159. if (sysIncludeFlag) {
  3160. bool gotOneSys = false;
  3161. for (auto i : includeList) {
  3162. cmSystemTools::ConvertToUnixSlashes(i);
  3163. if (this->GeneratorTarget->IsSystemIncludeDirectory(
  3164. i, configName, this->LangForClCompile)) {
  3165. auto flag = cmTrimWhitespace(*sysIncludeFlag);
  3166. if (this->MSTools) {
  3167. cmSystemTools::ReplaceString(flag, "-external:I", "/external:I");
  3168. }
  3169. clOptions.AppendFlagString("AdditionalOptions",
  3170. cmStrCat(flag, " \"", i, '"'));
  3171. gotOneSys = true;
  3172. } else {
  3173. clOptions.AddInclude(i);
  3174. }
  3175. }
  3176. if (gotOneSys) {
  3177. if (auto sysIncludeFlagWarning = this->Makefile->GetDefinition(
  3178. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile,
  3179. "_WARNING"))) {
  3180. flags = cmStrCat(flags, ' ', *sysIncludeFlagWarning);
  3181. }
  3182. }
  3183. } else {
  3184. clOptions.AddIncludes(includeList);
  3185. }
  3186. }
  3187. clOptions.Parse(flags);
  3188. clOptions.Parse(defineFlags);
  3189. std::vector<std::string> targetDefines;
  3190. switch (this->ProjectType) {
  3191. case VsProjectType::vcxproj:
  3192. if (!langForClCompile.empty()) {
  3193. this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
  3194. langForClCompile);
  3195. }
  3196. break;
  3197. case VsProjectType::csproj:
  3198. this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
  3199. "CSharp");
  3200. cm::erase_if(targetDefines, [](std::string const& def) {
  3201. return def.find('=') != std::string::npos;
  3202. });
  3203. break;
  3204. default:
  3205. break;
  3206. }
  3207. clOptions.AddDefines(targetDefines);
  3208. if (this->ProjectType == VsProjectType::csproj) {
  3209. clOptions.AppendFlag("DefineConstants", targetDefines);
  3210. }
  3211. if (this->MSTools) {
  3212. clOptions.SetVerboseMakefile(
  3213. this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
  3214. }
  3215. // Add C-specific flags expressible in a ClCompile meant for C++.
  3216. if (langForClCompile == "CXX"_s) {
  3217. std::set<std::string> languages;
  3218. this->GeneratorTarget->GetLanguages(languages, configName);
  3219. if (languages.count("C")) {
  3220. std::string flagsC;
  3221. this->LocalGenerator->AddLanguageFlags(
  3222. flagsC, this->GeneratorTarget, cmBuildStep::Compile, "C", configName);
  3223. this->LocalGenerator->AddCompileOptions(flagsC, this->GeneratorTarget,
  3224. "C", configName);
  3225. Options optC(this->LocalGenerator, Options::Compiler,
  3226. gg->GetClFlagTable());
  3227. optC.Parse(flagsC);
  3228. if (const char* stdC = optC.GetFlag("LanguageStandard_C")) {
  3229. clOptions.AddFlag("LanguageStandard_C", stdC);
  3230. }
  3231. }
  3232. }
  3233. // Add a definition for the configuration name.
  3234. std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
  3235. clOptions.AddDefine(configDefine);
  3236. if (const std::string* exportMacro =
  3237. this->GeneratorTarget->GetExportMacro()) {
  3238. clOptions.AddDefine(*exportMacro);
  3239. }
  3240. if (this->MSTools) {
  3241. // If we have the VS_WINRT_COMPONENT set then force Compile as WinRT
  3242. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
  3243. clOptions.AddFlag("CompileAsWinRT", "true");
  3244. // For WinRT components, add the _WINRT_DLL define to produce a lib
  3245. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3246. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3247. clOptions.AddDefine("_WINRT_DLL");
  3248. }
  3249. } else if (this->GlobalGenerator->TargetsWindowsStore() ||
  3250. this->GlobalGenerator->TargetsWindowsPhone() ||
  3251. this->Makefile->IsOn("CMAKE_VS_WINRT_BY_DEFAULT")) {
  3252. if (!clOptions.IsWinRt()) {
  3253. clOptions.AddFlag("CompileAsWinRT", "false");
  3254. }
  3255. }
  3256. if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) {
  3257. if (cmIsOn(winRT)) {
  3258. this->TargetCompileAsWinRT = true;
  3259. }
  3260. }
  3261. }
  3262. if (this->ProjectType != VsProjectType::csproj &&
  3263. (clOptions.IsManaged() || clOptions.HasFlag("CLRSupport"))) {
  3264. this->Managed = true;
  3265. std::string managedType = clOptions.HasFlag("CompileAsManaged")
  3266. ? clOptions.GetFlag("CompileAsManaged")
  3267. : "Mixed";
  3268. if (managedType == "Safe"_s || managedType == "Pure"_s) {
  3269. // force empty calling convention if safe clr is used
  3270. clOptions.AddFlag("CallingConvention", "");
  3271. }
  3272. // The default values of these flags are incompatible to
  3273. // managed assemblies. We have to force valid values if
  3274. // the target is a managed C++ target.
  3275. clOptions.AddFlag("ExceptionHandling", "Async");
  3276. clOptions.AddFlag("BasicRuntimeChecks", "Default");
  3277. }
  3278. if (this->ProjectType == VsProjectType::csproj) {
  3279. // /nowin32manifest overrides /win32manifest: parameter
  3280. if (clOptions.HasFlag("NoWin32Manifest")) {
  3281. clOptions.RemoveFlag("ApplicationManifest");
  3282. }
  3283. }
  3284. if (const char* s = clOptions.GetFlag("SpectreMitigation")) {
  3285. this->SpectreMitigation[configName] = s;
  3286. clOptions.RemoveFlag("SpectreMitigation");
  3287. }
  3288. // Remove any target-wide -TC or -TP flag added by the project.
  3289. // Such flags are unnecessary and break our model of language selection.
  3290. if (langForClCompile == "C"_s || langForClCompile == "CXX"_s) {
  3291. clOptions.RemoveFlag("CompileAs");
  3292. }
  3293. if (this->ProjectType == VsProjectType::vcxproj && this->MSTools) {
  3294. // Suppress Microsoft.Cl.Common.props default settings for which the
  3295. // project specifies no flags. Do not let UseDebugLibraries affect them.
  3296. if (!clOptions.HasFlag("BasicRuntimeChecks")) {
  3297. clOptions.AddFlag("BasicRuntimeChecks", "Default");
  3298. }
  3299. if (!clOptions.HasFlag("MinimalRebuild")) {
  3300. clOptions.AddFlag("MinimalRebuild", "");
  3301. }
  3302. if (!clOptions.HasFlag("Optimization")) {
  3303. clOptions.AddFlag("Optimization", "");
  3304. }
  3305. if (!clOptions.HasFlag("RuntimeLibrary")) {
  3306. clOptions.AddFlag("RuntimeLibrary", "");
  3307. }
  3308. if (!clOptions.HasFlag("SupportJustMyCode")) {
  3309. clOptions.AddFlag("SupportJustMyCode", "");
  3310. }
  3311. }
  3312. this->ClOptions[configName] = std::move(pOptions);
  3313. return true;
  3314. }
  3315. void cmVisualStudio10TargetGenerator::WriteClOptions(
  3316. Elem& e1, std::string const& configName)
  3317. {
  3318. Options& clOptions = *(this->ClOptions[configName]);
  3319. if (this->ProjectType == VsProjectType::csproj) {
  3320. return;
  3321. }
  3322. Elem e2(e1, "ClCompile");
  3323. OptionsHelper oh(clOptions, e2);
  3324. oh.PrependInheritedString("AdditionalOptions");
  3325. oh.OutputAdditionalIncludeDirectories(this->LangForClCompile);
  3326. oh.OutputFlagMap();
  3327. oh.OutputPreprocessorDefinitions(this->LangForClCompile);
  3328. if (this->NsightTegra) {
  3329. if (cmValue processMax =
  3330. this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) {
  3331. e2.Element("ProcessMax", *processMax);
  3332. }
  3333. }
  3334. if (this->Android) {
  3335. e2.Element("ObjectFileName", "$(IntDir)%(filename).o");
  3336. } else if (this->MSTools) {
  3337. cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
  3338. const char* toolset = this->GlobalGenerator->GetPlatformToolset();
  3339. cmValue noCompileBatching =
  3340. this->GeneratorTarget->GetProperty("VS_NO_COMPILE_BATCHING");
  3341. if (noCompileBatching.IsOn() || (toolset && clangToolset.find(toolset))) {
  3342. e2.Element("ObjectFileName", "$(IntDir)%(filename).obj");
  3343. } else {
  3344. e2.Element("ObjectFileName", "$(IntDir)");
  3345. }
  3346. // If not in debug mode, write the DebugInformationFormat field
  3347. // without value so PDBs don't get generated uselessly. Each tag
  3348. // goes on its own line because Visual Studio corrects it this
  3349. // way when saving the project after CMake generates it.
  3350. if (!clOptions.UsingDebugInfo()) {
  3351. Elem e3(e2, "DebugInformationFormat");
  3352. e3.SetHasElements();
  3353. }
  3354. // Specify the compiler program database file if configured.
  3355. std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
  3356. if (!pdb.empty()) {
  3357. if (this->GlobalGenerator->IsCudaEnabled()) {
  3358. // CUDA does not quote paths with spaces correctly when forwarding
  3359. // this to the host compiler. Use a relative path to avoid spaces.
  3360. // FIXME: We can likely do this even when CUDA is not involved,
  3361. // but for now we will make a minimal change.
  3362. pdb = this->ConvertPath(pdb, true);
  3363. }
  3364. ConvertToWindowsSlash(pdb);
  3365. e2.Element("ProgramDataBaseFileName", pdb);
  3366. }
  3367. // add AdditionalUsingDirectories
  3368. if (this->AdditionalUsingDirectories.count(configName) > 0) {
  3369. std::string dirs;
  3370. for (auto const& u : this->AdditionalUsingDirectories[configName]) {
  3371. if (!dirs.empty()) {
  3372. dirs.append(";");
  3373. }
  3374. dirs.append(u);
  3375. }
  3376. e2.Element("AdditionalUsingDirectories", dirs);
  3377. }
  3378. }
  3379. e2.Element("ScanSourceForModuleDependencies",
  3380. this->ScanSourceForModuleDependencies[configName] ? "true"
  3381. : "false");
  3382. }
  3383. bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
  3384. {
  3385. return std::all_of(
  3386. this->Configurations.begin(), this->Configurations.end(),
  3387. [this](std::string const& c) { return this->ComputeRcOptions(c); });
  3388. }
  3389. bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
  3390. std::string const& configName)
  3391. {
  3392. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3393. auto pOptions = cm::make_unique<Options>(
  3394. this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
  3395. Options& rcOptions = *pOptions;
  3396. std::string CONFIG = cmSystemTools::UpperCase(configName);
  3397. std::string rcConfigFlagsVar = cmStrCat("CMAKE_RC_FLAGS_", CONFIG);
  3398. std::string flags =
  3399. cmStrCat(this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS"), ' ',
  3400. this->Makefile->GetSafeDefinition(rcConfigFlagsVar));
  3401. rcOptions.Parse(flags);
  3402. // For historical reasons, add the C preprocessor defines to RC.
  3403. Options& clOptions = *(this->ClOptions[configName]);
  3404. rcOptions.AddDefines(clOptions.GetDefines());
  3405. // Get includes for this target
  3406. rcOptions.AddIncludes(this->GetIncludes(configName, "RC"));
  3407. this->RcOptions[configName] = std::move(pOptions);
  3408. return true;
  3409. }
  3410. void cmVisualStudio10TargetGenerator::WriteRCOptions(
  3411. Elem& e1, std::string const& configName)
  3412. {
  3413. if (!this->MSTools) {
  3414. return;
  3415. }
  3416. Elem e2(e1, "ResourceCompile");
  3417. OptionsHelper rcOptions(*(this->RcOptions[configName]), e2);
  3418. rcOptions.OutputPreprocessorDefinitions("RC");
  3419. rcOptions.OutputAdditionalIncludeDirectories("RC");
  3420. rcOptions.PrependInheritedString("AdditionalOptions");
  3421. rcOptions.OutputFlagMap();
  3422. }
  3423. bool cmVisualStudio10TargetGenerator::ComputeCudaOptions()
  3424. {
  3425. if (!this->GlobalGenerator->IsCudaEnabled()) {
  3426. return true;
  3427. }
  3428. return std::all_of(this->Configurations.begin(), this->Configurations.end(),
  3429. [this](std::string const& c) {
  3430. return !this->GeneratorTarget->IsLanguageUsed("CUDA",
  3431. c) ||
  3432. this->ComputeCudaOptions(c);
  3433. });
  3434. }
  3435. bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
  3436. std::string const& configName)
  3437. {
  3438. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3439. auto pOptions = cm::make_unique<Options>(
  3440. this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
  3441. Options& cudaOptions = *pOptions;
  3442. auto cudaVersion = this->GlobalGenerator->GetPlatformToolsetCudaString();
  3443. // Get compile flags for CUDA in this directory.
  3444. std::string flags;
  3445. this->LocalGenerator->AddLanguageFlags(
  3446. flags, this->GeneratorTarget, cmBuildStep::Compile, "CUDA", configName);
  3447. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, "CUDA",
  3448. configName);
  3449. // Get preprocessor definitions for this directory.
  3450. std::string defineFlags = this->Makefile->GetDefineFlags();
  3451. cudaOptions.Parse(flags);
  3452. cudaOptions.Parse(defineFlags);
  3453. cudaOptions.ParseFinish();
  3454. // If we haven't explicitly enabled GPU debug information
  3455. // explicitly disable it
  3456. if (!cudaOptions.HasFlag("GPUDebugInfo")) {
  3457. cudaOptions.AddFlag("GPUDebugInfo", "false");
  3458. }
  3459. // The extension on object libraries the CUDA gives isn't
  3460. // consistent with how MSVC generates object libraries for C+, so set
  3461. // the default to not have any extension
  3462. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).obj");
  3463. if (this->GeneratorTarget->GetPropertyAsBool("CUDA_SEPARABLE_COMPILATION")) {
  3464. cudaOptions.AddFlag("GenerateRelocatableDeviceCode", "true");
  3465. }
  3466. bool notPtxLike = true;
  3467. if (this->GeneratorTarget->GetPropertyAsBool("CUDA_PTX_COMPILATION")) {
  3468. cudaOptions.AddFlag("NvccCompilation", "ptx");
  3469. // We drop the %(Extension) component as CMake expects all PTX files
  3470. // to not have the source file extension at all
  3471. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
  3472. notPtxLike = false;
  3473. if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  3474. cudaVersion, "9.0") &&
  3475. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, cudaVersion,
  3476. "11.5")) {
  3477. // The DriverApi flag before 11.5 ( verified back to 9.0 ) which controls
  3478. // PTX compilation doesn't propagate user defines causing
  3479. // target_compile_definitions to behave differently for VS +
  3480. // PTX compared to other generators so we patch the rules
  3481. // to normalize behavior
  3482. cudaOptions.AddFlag("DriverApiCommandLineTemplate",
  3483. "%(BaseCommandLineTemplate) [CompileOut] [FastMath] "
  3484. "[Defines] \"%(FullPath)\"");
  3485. }
  3486. } else if (this->GeneratorTarget->GetPropertyAsBool(
  3487. "CUDA_CUBIN_COMPILATION")) {
  3488. cudaOptions.AddFlag("NvccCompilation", "cubin");
  3489. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).cubin");
  3490. notPtxLike = false;
  3491. } else if (this->GeneratorTarget->GetPropertyAsBool(
  3492. "CUDA_FATBIN_COMPILATION")) {
  3493. cudaOptions.AddFlag("NvccCompilation", "fatbin");
  3494. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).fatbin");
  3495. notPtxLike = false;
  3496. } else if (this->GeneratorTarget->GetPropertyAsBool(
  3497. "CUDA_OPTIX_COMPILATION")) {
  3498. cudaOptions.AddFlag("NvccCompilation", "optix-ir");
  3499. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).optixir");
  3500. notPtxLike = false;
  3501. }
  3502. if (notPtxLike &&
  3503. cmSystemTools::VersionCompareGreaterEq(
  3504. "8.0", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
  3505. // Explicitly state that we want this file to be treated as a
  3506. // CUDA file no matter what the file extensions is
  3507. // This is only needed for < CUDA 9
  3508. cudaOptions.AppendFlagString("AdditionalOptions", "-x cu");
  3509. }
  3510. // Specify the compiler program database file if configured.
  3511. std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
  3512. if (!pdb.empty()) {
  3513. // CUDA does not make the directory if it is non-standard.
  3514. std::string const pdbDir = cmSystemTools::GetFilenamePath(pdb);
  3515. cmSystemTools::MakeDirectory(pdbDir);
  3516. if (cmSystemTools::VersionCompareGreaterEq(
  3517. "9.2", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
  3518. // CUDA does not have a field for this and does not honor the
  3519. // ProgramDataBaseFileName field in ClCompile. Work around this
  3520. // limitation by creating the directory and passing the flag ourselves.
  3521. pdb = this->ConvertPath(pdb, true);
  3522. ConvertToWindowsSlash(pdb);
  3523. std::string const clFd = cmStrCat(R"(-Xcompiler="-Fd\")", pdb, R"(\"")");
  3524. cudaOptions.AppendFlagString("AdditionalOptions", clFd);
  3525. }
  3526. }
  3527. // CUDA automatically passes the proper '--machine' flag to nvcc
  3528. // for the current architecture, but does not reflect this default
  3529. // in the user-visible IDE settings. Set it explicitly.
  3530. if (this->Platform == "x64"_s) {
  3531. cudaOptions.AddFlag("TargetMachinePlatform", "64");
  3532. }
  3533. // Convert the host compiler options to the toolset's abstractions
  3534. // using a secondary flag table.
  3535. cudaOptions.ClearTables();
  3536. cudaOptions.AddTable(gg->GetCudaHostFlagTable());
  3537. cudaOptions.Reparse("AdditionalCompilerOptions");
  3538. // `CUDA 8.0.targets` places AdditionalCompilerOptions before nvcc!
  3539. // Pass them through -Xcompiler in AdditionalOptions instead.
  3540. if (const char* acoPtr = cudaOptions.GetFlag("AdditionalCompilerOptions")) {
  3541. std::string aco = acoPtr;
  3542. cudaOptions.RemoveFlag("AdditionalCompilerOptions");
  3543. if (!aco.empty()) {
  3544. aco = this->LocalGenerator->EscapeForShell(aco, false);
  3545. cudaOptions.AppendFlagString("AdditionalOptions",
  3546. cmStrCat("-Xcompiler=", aco));
  3547. }
  3548. }
  3549. cudaOptions.FixCudaCodeGeneration();
  3550. std::vector<std::string> targetDefines;
  3551. this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
  3552. "CUDA");
  3553. cudaOptions.AddDefines(targetDefines);
  3554. // Add a definition for the configuration name.
  3555. std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
  3556. cudaOptions.AddDefine(configDefine);
  3557. if (const std::string* exportMacro =
  3558. this->GeneratorTarget->GetExportMacro()) {
  3559. cudaOptions.AddDefine(*exportMacro);
  3560. }
  3561. // Get includes for this target
  3562. cudaOptions.AddIncludes(this->GetIncludes(configName, "CUDA"));
  3563. cudaOptions.AddFlag("UseHostInclude", "false");
  3564. // Add runtime library selection flag.
  3565. std::string const& cudaRuntime =
  3566. this->GeneratorTarget->GetRuntimeLinkLibrary("CUDA", configName);
  3567. if (cudaRuntime == "STATIC"_s) {
  3568. cudaOptions.AddFlag("CudaRuntime", "Static");
  3569. } else if (cudaRuntime == "SHARED"_s) {
  3570. cudaOptions.AddFlag("CudaRuntime", "Shared");
  3571. } else if (cudaRuntime == "NONE"_s) {
  3572. cudaOptions.AddFlag("CudaRuntime", "None");
  3573. }
  3574. if (this->ProjectType == VsProjectType::vcxproj && this->MSTools) {
  3575. // Suppress inheritance of host compiler optimization flags
  3576. // when the project does not specify any optimization flags for CUDA.
  3577. if (!cudaOptions.HasFlag("Optimization")) {
  3578. cudaOptions.AddFlag("Optimization", "");
  3579. }
  3580. }
  3581. this->CudaOptions[configName] = std::move(pOptions);
  3582. return true;
  3583. }
  3584. void cmVisualStudio10TargetGenerator::WriteCudaOptions(
  3585. Elem& e1, std::string const& configName)
  3586. {
  3587. if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled() ||
  3588. !this->GeneratorTarget->IsLanguageUsed("CUDA", configName)) {
  3589. return;
  3590. }
  3591. Elem e2(e1, "CudaCompile");
  3592. OptionsHelper cudaOptions(*(this->CudaOptions[configName]), e2);
  3593. cudaOptions.OutputAdditionalIncludeDirectories("CUDA");
  3594. cudaOptions.OutputPreprocessorDefinitions("CUDA");
  3595. cudaOptions.PrependInheritedString("AdditionalOptions");
  3596. cudaOptions.OutputFlagMap();
  3597. }
  3598. bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
  3599. {
  3600. if (!this->GlobalGenerator->IsCudaEnabled()) {
  3601. return true;
  3602. }
  3603. return std::all_of(
  3604. this->Configurations.begin(), this->Configurations.end(),
  3605. [this](std::string const& c) { return this->ComputeCudaLinkOptions(c); });
  3606. }
  3607. bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
  3608. std::string const& configName)
  3609. {
  3610. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3611. auto pOptions = cm::make_unique<Options>(
  3612. this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
  3613. Options& cudaLinkOptions = *pOptions;
  3614. cmGeneratorTarget::DeviceLinkSetter setter(*this->GeneratorTarget);
  3615. // Determine if we need to do a device link
  3616. const bool doDeviceLinking = requireDeviceLinking(
  3617. *this->GeneratorTarget, *this->LocalGenerator, configName);
  3618. cudaLinkOptions.AddFlag("PerformDeviceLink",
  3619. doDeviceLinking ? "true" : "false");
  3620. // Add extra flags for device linking
  3621. cudaLinkOptions.AppendFlagString(
  3622. "AdditionalOptions",
  3623. this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_FLAGS"));
  3624. cudaLinkOptions.AppendFlagString(
  3625. "AdditionalOptions",
  3626. this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS"));
  3627. std::vector<std::string> linkOpts;
  3628. std::string linkFlags;
  3629. this->GeneratorTarget->GetLinkOptions(linkOpts, configName, "CUDA");
  3630. // LINK_OPTIONS are escaped.
  3631. this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
  3632. cmComputeLinkInformation* pcli =
  3633. this->GeneratorTarget->GetLinkInformation(configName);
  3634. if (doDeviceLinking && pcli) {
  3635. cmLinkLineDeviceComputer computer(
  3636. this->LocalGenerator,
  3637. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  3638. std::string ignored_;
  3639. this->LocalGenerator->GetDeviceLinkFlags(computer, configName, ignored_,
  3640. linkFlags, ignored_, ignored_,
  3641. this->GeneratorTarget);
  3642. this->LocalGenerator->AddLanguageFlagsForLinking(
  3643. linkFlags, this->GeneratorTarget, "CUDA", configName);
  3644. }
  3645. cudaLinkOptions.AppendFlagString("AdditionalOptions", linkFlags);
  3646. if (doDeviceLinking) {
  3647. std::vector<std::string> libVec;
  3648. auto const& kinded = this->GeneratorTarget->GetKindedSources(configName);
  3649. // CMake conversion uses full paths when possible to allow deeper trees.
  3650. // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
  3651. // we must use relative paths.
  3652. const bool forceRelative = true;
  3653. for (cmGeneratorTarget::SourceAndKind const& si : kinded.Sources) {
  3654. switch (si.Kind) {
  3655. case cmGeneratorTarget::SourceKindExternalObject: {
  3656. std::string path =
  3657. this->ConvertPath(si.Source.Value->GetFullPath(), forceRelative);
  3658. ConvertToWindowsSlash(path);
  3659. libVec.emplace_back(std::move(path));
  3660. } break;
  3661. default:
  3662. break;
  3663. }
  3664. }
  3665. // For static libraries that have device linking enabled compute
  3666. // the libraries
  3667. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3668. cmComputeLinkInformation& cli = *pcli;
  3669. cmLinkLineDeviceComputer computer(
  3670. this->LocalGenerator,
  3671. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  3672. std::vector<BT<std::string>> btLibVec;
  3673. computer.ComputeLinkLibraries(cli, std::string{}, btLibVec);
  3674. for (auto const& item : btLibVec) {
  3675. libVec.emplace_back(item.Value);
  3676. }
  3677. }
  3678. if (!libVec.empty()) {
  3679. cudaLinkOptions.AddFlag("AdditionalDependencies", libVec);
  3680. }
  3681. }
  3682. this->CudaLinkOptions[configName] = std::move(pOptions);
  3683. return true;
  3684. }
  3685. void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
  3686. Elem& e1, std::string const& configName)
  3687. {
  3688. // We need to write link options for OBJECT libraries so that
  3689. // we override the default device link behavior ( enabled ) when
  3690. // building object libraries with ptx/optix-ir/etc
  3691. if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  3692. return;
  3693. }
  3694. if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
  3695. return;
  3696. }
  3697. Elem e2(e1, "CudaLink");
  3698. OptionsHelper cudaLinkOptions(*(this->CudaLinkOptions[configName]), e2);
  3699. cudaLinkOptions.OutputFlagMap();
  3700. }
  3701. bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions()
  3702. {
  3703. if (!this->GlobalGenerator->IsMarmasmEnabled()) {
  3704. return true;
  3705. }
  3706. return std::all_of(
  3707. this->Configurations.begin(), this->Configurations.end(),
  3708. [this](std::string const& c) { return this->ComputeMarmasmOptions(c); });
  3709. }
  3710. bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions(
  3711. std::string const& configName)
  3712. {
  3713. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3714. auto pOptions = cm::make_unique<Options>(
  3715. this->LocalGenerator, Options::MarmasmCompiler, gg->GetMarmasmFlagTable());
  3716. Options& marmasmOptions = *pOptions;
  3717. std::string flags;
  3718. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3719. cmBuildStep::Compile, "ASM_MARMASM",
  3720. configName);
  3721. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3722. "ASM_MARMASM", configName);
  3723. marmasmOptions.Parse(flags);
  3724. // Get includes for this target
  3725. marmasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MARMASM"));
  3726. this->MarmasmOptions[configName] = std::move(pOptions);
  3727. return true;
  3728. }
  3729. void cmVisualStudio10TargetGenerator::WriteMarmasmOptions(
  3730. Elem& e1, std::string const& configName)
  3731. {
  3732. if (!this->MSTools || !this->GlobalGenerator->IsMarmasmEnabled()) {
  3733. return;
  3734. }
  3735. Elem e2(e1, "MARMASM");
  3736. // Preprocessor definitions and includes are shared with clOptions.
  3737. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3738. clOptions.OutputPreprocessorDefinitions("ASM_MARMASM");
  3739. OptionsHelper marmasmOptions(*(this->MarmasmOptions[configName]), e2);
  3740. marmasmOptions.OutputAdditionalIncludeDirectories("ASM_MARMASM");
  3741. marmasmOptions.PrependInheritedString("AdditionalOptions");
  3742. marmasmOptions.OutputFlagMap();
  3743. }
  3744. bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
  3745. {
  3746. if (!this->GlobalGenerator->IsMasmEnabled()) {
  3747. return true;
  3748. }
  3749. return std::all_of(
  3750. this->Configurations.begin(), this->Configurations.end(),
  3751. [this](std::string const& c) { return this->ComputeMasmOptions(c); });
  3752. }
  3753. bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
  3754. std::string const& configName)
  3755. {
  3756. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3757. auto pOptions = cm::make_unique<Options>(
  3758. this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
  3759. Options& masmOptions = *pOptions;
  3760. // MSBuild enables debug information by default.
  3761. // Disable it explicitly unless a flag parsed below re-enables it.
  3762. masmOptions.AddFlag("GenerateDebugInformation", "false");
  3763. std::string flags;
  3764. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3765. cmBuildStep::Compile, "ASM_MASM",
  3766. configName);
  3767. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3768. "ASM_MASM", configName);
  3769. masmOptions.Parse(flags);
  3770. // Get includes for this target
  3771. masmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MASM"));
  3772. this->MasmOptions[configName] = std::move(pOptions);
  3773. return true;
  3774. }
  3775. void cmVisualStudio10TargetGenerator::WriteMasmOptions(
  3776. Elem& e1, std::string const& configName)
  3777. {
  3778. if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
  3779. return;
  3780. }
  3781. Elem e2(e1, "MASM");
  3782. // Preprocessor definitions and includes are shared with clOptions.
  3783. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3784. clOptions.OutputPreprocessorDefinitions("ASM_MASM");
  3785. OptionsHelper masmOptions(*(this->MasmOptions[configName]), e2);
  3786. masmOptions.OutputAdditionalIncludeDirectories("ASM_MASM");
  3787. masmOptions.PrependInheritedString("AdditionalOptions");
  3788. masmOptions.OutputFlagMap();
  3789. }
  3790. bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
  3791. {
  3792. if (!this->GlobalGenerator->IsNasmEnabled()) {
  3793. return true;
  3794. }
  3795. return std::all_of(
  3796. this->Configurations.begin(), this->Configurations.end(),
  3797. [this](std::string const& c) { return this->ComputeNasmOptions(c); });
  3798. }
  3799. bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
  3800. std::string const& configName)
  3801. {
  3802. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3803. auto pOptions = cm::make_unique<Options>(
  3804. this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
  3805. Options& nasmOptions = *pOptions;
  3806. std::string flags;
  3807. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3808. cmBuildStep::Compile, "ASM_NASM",
  3809. configName);
  3810. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3811. "ASM_NASM", configName);
  3812. flags += " -f";
  3813. flags += this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_OBJECT_FORMAT");
  3814. nasmOptions.Parse(flags);
  3815. // Get includes for this target
  3816. nasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_NASM"));
  3817. this->NasmOptions[configName] = std::move(pOptions);
  3818. return true;
  3819. }
  3820. void cmVisualStudio10TargetGenerator::WriteNasmOptions(
  3821. Elem& e1, std::string const& configName)
  3822. {
  3823. if (!this->GlobalGenerator->IsNasmEnabled()) {
  3824. return;
  3825. }
  3826. Elem e2(e1, "NASM");
  3827. OptionsHelper nasmOptions(*(this->NasmOptions[configName]), e2);
  3828. nasmOptions.OutputAdditionalIncludeDirectories("ASM_NASM");
  3829. nasmOptions.OutputFlagMap();
  3830. nasmOptions.PrependInheritedString("AdditionalOptions");
  3831. nasmOptions.OutputPreprocessorDefinitions("ASM_NASM");
  3832. // Preprocessor definitions and includes are shared with clOptions.
  3833. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3834. clOptions.OutputPreprocessorDefinitions("ASM_NASM");
  3835. }
  3836. void cmVisualStudio10TargetGenerator::WriteLibOptions(
  3837. Elem& e1, std::string const& config)
  3838. {
  3839. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3840. this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  3841. return;
  3842. }
  3843. const std::string& linkLanguage =
  3844. this->GeneratorTarget->GetLinkClosure(config)->LinkerLanguage;
  3845. std::string libflags;
  3846. this->LocalGenerator->GetStaticLibraryFlags(libflags, config, linkLanguage,
  3847. this->GeneratorTarget);
  3848. if (!libflags.empty()) {
  3849. Elem e2(e1, "Lib");
  3850. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3851. cmVS10GeneratorOptions libOptions(this->LocalGenerator,
  3852. cmVisualStudioGeneratorOptions::Linker,
  3853. gg->GetLibFlagTable(), this);
  3854. libOptions.Parse(libflags);
  3855. OptionsHelper oh(libOptions, e2);
  3856. oh.PrependInheritedString("AdditionalOptions");
  3857. oh.OutputFlagMap();
  3858. }
  3859. // We cannot generate metadata for static libraries. WindowsPhone
  3860. // and WindowsStore tools look at GenerateWindowsMetadata in the
  3861. // Link tool options even for static libraries.
  3862. if (this->GlobalGenerator->TargetsWindowsPhone() ||
  3863. this->GlobalGenerator->TargetsWindowsStore()) {
  3864. Elem e2(e1, "Link");
  3865. e2.Element("GenerateWindowsMetadata", "false");
  3866. }
  3867. }
  3868. void cmVisualStudio10TargetGenerator::WriteManifestOptions(
  3869. Elem& e1, std::string const& config)
  3870. {
  3871. if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
  3872. this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3873. this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
  3874. return;
  3875. }
  3876. std::vector<cmSourceFile const*> manifest_srcs;
  3877. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  3878. cmValue dpiAware = this->GeneratorTarget->GetProperty("VS_DPI_AWARE");
  3879. if (!manifest_srcs.empty() || dpiAware) {
  3880. Elem e2(e1, "Manifest");
  3881. if (!manifest_srcs.empty()) {
  3882. std::ostringstream oss;
  3883. for (cmSourceFile const* mi : manifest_srcs) {
  3884. std::string m = this->ConvertPath(mi->GetFullPath(), false);
  3885. ConvertToWindowsSlash(m);
  3886. oss << m << ";";
  3887. }
  3888. e2.Element("AdditionalManifestFiles", oss.str());
  3889. }
  3890. if (dpiAware) {
  3891. if (*dpiAware == "PerMonitor"_s) {
  3892. e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware");
  3893. } else if (dpiAware.IsOn()) {
  3894. e2.Element("EnableDpiAwareness", "true");
  3895. } else if (dpiAware.IsOff()) {
  3896. e2.Element("EnableDpiAwareness", "false");
  3897. } else {
  3898. cmSystemTools::Error(
  3899. cmStrCat("Bad parameter for VS_DPI_AWARE: ", *dpiAware));
  3900. }
  3901. }
  3902. }
  3903. }
  3904. void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
  3905. Elem& e1, std::string const& configName)
  3906. {
  3907. // Look through the sources for AndroidManifest.xml and use
  3908. // its location as the root source directory.
  3909. std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
  3910. {
  3911. for (cmGeneratorTarget::AllConfigSource const& source :
  3912. this->GeneratorTarget->GetAllConfigSources()) {
  3913. if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
  3914. "androidmanifest.xml" ==
  3915. cmSystemTools::LowerCase(source.Source->GetLocation().GetName())) {
  3916. rootDir = source.Source->GetLocation().GetDirectory();
  3917. break;
  3918. }
  3919. }
  3920. }
  3921. // Tell MSBuild to launch Ant.
  3922. Elem e2(e1, "AntBuild");
  3923. {
  3924. std::string antBuildPath = rootDir;
  3925. ConvertToWindowsSlash(antBuildPath);
  3926. e2.Element("AntBuildPath", antBuildPath);
  3927. }
  3928. if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
  3929. e2.Element("SkipAntStep", "true");
  3930. }
  3931. if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
  3932. e2.Element("EnableProGuard", "true");
  3933. }
  3934. if (cmValue proGuardConfigLocation =
  3935. this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
  3936. e2.Element("ProGuardConfigLocation", *proGuardConfigLocation);
  3937. }
  3938. if (cmValue securePropertiesLocation =
  3939. this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
  3940. e2.Element("SecurePropertiesLocation", *securePropertiesLocation);
  3941. }
  3942. if (cmValue nativeLibDirectoriesExpression =
  3943. this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
  3944. std::string nativeLibDirs = cmGeneratorExpression::Evaluate(
  3945. *nativeLibDirectoriesExpression, this->LocalGenerator, configName);
  3946. e2.Element("NativeLibDirectories", nativeLibDirs);
  3947. }
  3948. if (cmValue nativeLibDependenciesExpression =
  3949. this->GeneratorTarget->GetProperty(
  3950. "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
  3951. std::string nativeLibDeps = cmGeneratorExpression::Evaluate(
  3952. *nativeLibDependenciesExpression, this->LocalGenerator, configName);
  3953. e2.Element("NativeLibDependencies", nativeLibDeps);
  3954. }
  3955. if (cmValue javaSourceDir =
  3956. this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
  3957. e2.Element("JavaSourceDir", *javaSourceDir);
  3958. }
  3959. if (cmValue jarDirectoriesExpression =
  3960. this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
  3961. std::string jarDirectories = cmGeneratorExpression::Evaluate(
  3962. *jarDirectoriesExpression, this->LocalGenerator, configName);
  3963. e2.Element("JarDirectories", jarDirectories);
  3964. }
  3965. if (cmValue jarDeps =
  3966. this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
  3967. e2.Element("JarDependencies", *jarDeps);
  3968. }
  3969. if (cmValue assetsDirectories =
  3970. this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
  3971. e2.Element("AssetsDirectories", *assetsDirectories);
  3972. }
  3973. {
  3974. std::string manifest_xml = cmStrCat(rootDir, "/AndroidManifest.xml");
  3975. ConvertToWindowsSlash(manifest_xml);
  3976. e2.Element("AndroidManifestLocation", manifest_xml);
  3977. }
  3978. if (cmValue antAdditionalOptions =
  3979. this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
  3980. e2.Element("AdditionalOptions",
  3981. cmStrCat(*antAdditionalOptions, " %(AdditionalOptions)"));
  3982. }
  3983. }
  3984. bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
  3985. {
  3986. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  3987. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3988. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3989. for (std::string const& c : this->Configurations) {
  3990. if (!this->ComputeLinkOptions(c)) {
  3991. return false;
  3992. }
  3993. }
  3994. }
  3995. return true;
  3996. }
  3997. bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
  3998. std::string const& config)
  3999. {
  4000. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  4001. auto pOptions = cm::make_unique<Options>(
  4002. this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this);
  4003. Options& linkOptions = *pOptions;
  4004. cmGeneratorTarget::LinkClosure const* linkClosure =
  4005. this->GeneratorTarget->GetLinkClosure(config);
  4006. const std::string& linkLanguage = linkClosure->LinkerLanguage;
  4007. if (linkLanguage.empty()) {
  4008. cmSystemTools::Error(cmStrCat(
  4009. "CMake can not determine linker language for target: ", this->Name));
  4010. return false;
  4011. }
  4012. std::string CONFIG = cmSystemTools::UpperCase(config);
  4013. const char* linkType = "SHARED";
  4014. if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4015. linkType = "MODULE";
  4016. }
  4017. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4018. linkType = "EXE";
  4019. }
  4020. std::string flags;
  4021. std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS");
  4022. flags += ' ';
  4023. flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase);
  4024. std::string linkFlagVar = cmStrCat(linkFlagVarBase, '_', CONFIG);
  4025. flags += ' ';
  4026. flags += this->Makefile->GetRequiredDefinition(linkFlagVar);
  4027. cmValue targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS");
  4028. if (targetLinkFlags) {
  4029. flags += ' ';
  4030. flags += *targetLinkFlags;
  4031. }
  4032. std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG);
  4033. if (cmValue flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) {
  4034. flags += ' ';
  4035. flags += *flagsConfig;
  4036. }
  4037. std::vector<std::string> opts;
  4038. this->GeneratorTarget->GetLinkOptions(opts, config, linkLanguage);
  4039. // LINK_OPTIONS are escaped.
  4040. this->LocalGenerator->AppendCompileOptions(flags, opts);
  4041. cmComputeLinkInformation* pcli =
  4042. this->GeneratorTarget->GetLinkInformation(config);
  4043. if (!pcli) {
  4044. cmSystemTools::Error(
  4045. cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
  4046. this->Name));
  4047. return false;
  4048. }
  4049. cmComputeLinkInformation& cli = *pcli;
  4050. std::vector<std::string> libVec;
  4051. std::vector<std::string> vsTargetVec;
  4052. this->AddLibraries(cli, libVec, vsTargetVec, config);
  4053. std::string standardLibsVar =
  4054. cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
  4055. std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar);
  4056. cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
  4057. linkOptions.AddFlag("AdditionalDependencies", libVec);
  4058. // Populate TargetsFileAndConfigsVec
  4059. for (std::string const& ti : vsTargetVec) {
  4060. this->AddTargetsFileAndConfigPair(ti, config);
  4061. }
  4062. std::vector<std::string> linkDirs;
  4063. std::vector<std::string> const& ldirs = cli.GetDirectories();
  4064. for (std::string const& d : ldirs) {
  4065. // first just full path
  4066. linkDirs.push_back(d);
  4067. // next path with configuration type Debug, Release, etc
  4068. linkDirs.emplace_back(cmStrCat(d, "/$(Configuration)"));
  4069. }
  4070. std::string const& linkDirsString = this->Makefile->GetSafeDefinition(
  4071. cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LINK_DIRECTORIES"));
  4072. for (const std::string& d : cmList(linkDirsString)) {
  4073. linkDirs.push_back(d);
  4074. }
  4075. linkDirs.push_back("%(AdditionalLibraryDirectories)");
  4076. linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
  4077. cmGeneratorTarget::Names targetNames;
  4078. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4079. targetNames = this->GeneratorTarget->GetExecutableNames(config);
  4080. } else {
  4081. targetNames = this->GeneratorTarget->GetLibraryNames(config);
  4082. }
  4083. if (this->MSTools) {
  4084. if (this->GeneratorTarget->IsWin32Executable(config)) {
  4085. if (this->GlobalGenerator->TargetsWindowsCE()) {
  4086. linkOptions.AddFlag("SubSystem", "WindowsCE");
  4087. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4088. if (this->ClOptions[config]->UsingUnicode()) {
  4089. linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
  4090. } else {
  4091. linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
  4092. }
  4093. }
  4094. } else {
  4095. linkOptions.AddFlag("SubSystem", "Windows");
  4096. }
  4097. } else {
  4098. if (this->GlobalGenerator->TargetsWindowsCE()) {
  4099. linkOptions.AddFlag("SubSystem", "WindowsCE");
  4100. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4101. if (this->ClOptions[config]->UsingUnicode()) {
  4102. linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
  4103. } else {
  4104. linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
  4105. }
  4106. }
  4107. } else {
  4108. linkOptions.AddFlag("SubSystem", "Console");
  4109. };
  4110. }
  4111. if (cmValue stackVal = this->Makefile->GetDefinition(
  4112. cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"))) {
  4113. linkOptions.AddFlag("StackReserveSize", *stackVal);
  4114. }
  4115. linkOptions.AddFlag("GenerateDebugInformation", "false");
  4116. std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config),
  4117. '/', targetNames.PDB);
  4118. if (!targetNames.ImportLibrary.empty()) {
  4119. std::string imLib =
  4120. cmStrCat(this->GeneratorTarget->GetDirectory(
  4121. config, cmStateEnums::ImportLibraryArtifact),
  4122. '/', targetNames.ImportLibrary);
  4123. linkOptions.AddFlag("ImportLibrary", imLib);
  4124. }
  4125. linkOptions.AddFlag("ProgramDataBaseFile", pdb);
  4126. // A Windows Runtime component uses internal .NET metadata,
  4127. // so does not have an import library.
  4128. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
  4129. this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
  4130. linkOptions.AddFlag("GenerateWindowsMetadata", "true");
  4131. } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
  4132. this->GlobalGenerator->TargetsWindowsStore()) {
  4133. // WindowsPhone and WindowsStore components are in an app container
  4134. // and produce WindowsMetadata. If we are not producing a WINRT
  4135. // component, then do not generate the metadata here.
  4136. linkOptions.AddFlag("GenerateWindowsMetadata", "false");
  4137. }
  4138. if (this->GlobalGenerator->TargetsWindowsPhone() &&
  4139. this->GlobalGenerator->GetSystemVersion() == "8.0"_s) {
  4140. // WindowsPhone 8.0 does not have ole32.
  4141. linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
  4142. }
  4143. } else if (this->NsightTegra) {
  4144. linkOptions.AddFlag("SoName", targetNames.SharedObject);
  4145. }
  4146. linkOptions.Parse(flags);
  4147. linkOptions.FixManifestUACFlags();
  4148. if (this->MSTools) {
  4149. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  4150. this->GeneratorTarget->GetModuleDefinitionInfo(config);
  4151. if (mdi && !mdi->DefFile.empty()) {
  4152. linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile);
  4153. }
  4154. linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
  4155. "%(IgnoreSpecificDefaultLibraries)");
  4156. }
  4157. // VS 2015 without all updates has a v140 toolset whose
  4158. // GenerateDebugInformation expects No/Debug instead of false/true.
  4159. if (gg->GetPlatformToolsetNeedsDebugEnum()) {
  4160. if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
  4161. if (strcmp(debug, "false") == 0) {
  4162. linkOptions.AddFlag("GenerateDebugInformation", "No");
  4163. } else if (strcmp(debug, "true") == 0) {
  4164. linkOptions.AddFlag("GenerateDebugInformation", "Debug");
  4165. }
  4166. }
  4167. }
  4168. // Managed code cannot be linked with /DEBUG:FASTLINK
  4169. if (this->Managed) {
  4170. if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
  4171. if (strcmp(debug, "DebugFastLink") == 0) {
  4172. linkOptions.AddFlag("GenerateDebugInformation", "Debug");
  4173. }
  4174. }
  4175. }
  4176. this->LinkOptions[config] = std::move(pOptions);
  4177. return true;
  4178. }
  4179. bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
  4180. {
  4181. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4182. for (std::string const& c : this->Configurations) {
  4183. if (!this->ComputeLibOptions(c)) {
  4184. return false;
  4185. }
  4186. }
  4187. }
  4188. return true;
  4189. }
  4190. bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
  4191. std::string const& config)
  4192. {
  4193. cmComputeLinkInformation* pcli =
  4194. this->GeneratorTarget->GetLinkInformation(config);
  4195. if (!pcli) {
  4196. cmSystemTools::Error(
  4197. cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
  4198. this->Name));
  4199. return false;
  4200. }
  4201. cmComputeLinkInformation& cli = *pcli;
  4202. using ItemVector = cmComputeLinkInformation::ItemVector;
  4203. const ItemVector& libs = cli.GetItems();
  4204. for (cmComputeLinkInformation::Item const& l : libs) {
  4205. if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  4206. cmVS10IsTargetsFile(l.Value.Value)) {
  4207. std::string path =
  4208. this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
  4209. ConvertToWindowsSlash(path);
  4210. this->AddTargetsFileAndConfigPair(path, config);
  4211. }
  4212. }
  4213. return true;
  4214. }
  4215. void cmVisualStudio10TargetGenerator::WriteLinkOptions(
  4216. Elem& e1, std::string const& config)
  4217. {
  4218. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4219. this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
  4220. return;
  4221. }
  4222. if (this->ProjectType == VsProjectType::csproj) {
  4223. return;
  4224. }
  4225. {
  4226. Elem e2(e1, "Link");
  4227. OptionsHelper linkOptions(*(this->LinkOptions[config]), e2);
  4228. linkOptions.PrependInheritedString("AdditionalOptions");
  4229. linkOptions.OutputFlagMap();
  4230. }
  4231. if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
  4232. this->GeneratorTarget)) {
  4233. Elem e2(e1, "ProjectReference");
  4234. e2.Element("LinkLibraryDependencies", "false");
  4235. }
  4236. }
  4237. void cmVisualStudio10TargetGenerator::AddLibraries(
  4238. const cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
  4239. std::vector<std::string>& vsTargetVec, const std::string& config)
  4240. {
  4241. using ItemVector = cmComputeLinkInformation::ItemVector;
  4242. ItemVector const& libs = cli.GetItems();
  4243. for (cmComputeLinkInformation::Item const& l : libs) {
  4244. if (l.Target) {
  4245. auto managedType = l.Target->GetManagedType(config);
  4246. if (managedType != cmGeneratorTarget::ManagedType::Native &&
  4247. this->GeneratorTarget->GetManagedType(config) !=
  4248. cmGeneratorTarget::ManagedType::Native &&
  4249. l.Target->IsImported() &&
  4250. l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  4251. auto location = l.Target->GetFullPath(config);
  4252. if (!location.empty()) {
  4253. ConvertToWindowsSlash(location);
  4254. switch (this->ProjectType) {
  4255. case VsProjectType::csproj:
  4256. // If the target we want to "link" to is an imported managed
  4257. // target and this is a C# project, we add a hint reference. This
  4258. // reference is written to project file in
  4259. // WriteDotNetReferences().
  4260. this->DotNetHintReferences[config].push_back(
  4261. DotNetHintReference(l.Target->GetName(), location));
  4262. break;
  4263. case VsProjectType::vcxproj:
  4264. // Add path of assembly to list of using-directories, so the
  4265. // managed assembly can be used by '#using <assembly.dll>' in
  4266. // code.
  4267. this->AdditionalUsingDirectories[config].insert(
  4268. cmSystemTools::GetFilenamePath(location));
  4269. break;
  4270. default:
  4271. // In .proj files, we wouldn't be referencing libraries.
  4272. break;
  4273. }
  4274. }
  4275. }
  4276. // Do not allow C# targets to be added to the LIB listing. LIB files are
  4277. // used for linking C++ dependencies. C# libraries do not have lib files.
  4278. // Instead, they compile down to C# reference libraries (DLL files). The
  4279. // `<ProjectReference>` elements added to the vcxproj are enough for the
  4280. // IDE to deduce the DLL file required by other C# projects that need its
  4281. // reference library.
  4282. if (managedType == cmGeneratorTarget::ManagedType::Managed) {
  4283. continue;
  4284. }
  4285. }
  4286. if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  4287. std::string path =
  4288. this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
  4289. ConvertToWindowsSlash(path);
  4290. if (cmVS10IsTargetsFile(l.Value.Value)) {
  4291. vsTargetVec.push_back(path);
  4292. } else {
  4293. libVec.push_back(l.HasFeature() ? l.GetFormattedItem(path).Value
  4294. : path);
  4295. }
  4296. } else if (!l.Target ||
  4297. (l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4298. l.Target->GetType() != cmStateEnums::OBJECT_LIBRARY)) {
  4299. libVec.push_back(l.Value.Value);
  4300. }
  4301. }
  4302. }
  4303. void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
  4304. std::string const& targetsFile, std::string const& config)
  4305. {
  4306. for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) {
  4307. if (cmSystemTools::ComparePath(targetsFile, i.File)) {
  4308. if (!cm::contains(i.Configs, config)) {
  4309. i.Configs.push_back(config);
  4310. }
  4311. return;
  4312. }
  4313. }
  4314. TargetsFileAndConfigs entry;
  4315. entry.File = targetsFile;
  4316. entry.Configs.push_back(config);
  4317. this->TargetsFileAndConfigsVec.push_back(entry);
  4318. }
  4319. void cmVisualStudio10TargetGenerator::WriteMidlOptions(
  4320. Elem& e1, std::string const& configName)
  4321. {
  4322. if (!this->MSTools) {
  4323. return;
  4324. }
  4325. if (this->ProjectType == VsProjectType::csproj) {
  4326. return;
  4327. }
  4328. if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
  4329. return;
  4330. }
  4331. // This processes *any* of the .idl files specified in the project's file
  4332. // list (and passed as the item metadata %(Filename) expressing the rule
  4333. // input filename) into output files at the per-config *build* dir
  4334. // ($(IntDir)) each.
  4335. //
  4336. // IOW, this MIDL section is intended to provide a fully generic syntax
  4337. // content suitable for most cases (read: if you get errors, then it's quite
  4338. // probable that the error is on your side of the .idl setup).
  4339. //
  4340. // Also, note that the marked-as-generated _i.c file in the Visual Studio
  4341. // generator case needs to be referred to as $(IntDir)\foo_i.c at the
  4342. // project's file list, otherwise the compiler-side processing won't pick it
  4343. // up (for non-directory form, it ends up looking in project binary dir
  4344. // only). Perhaps there's something to be done to make this more automatic
  4345. // on the CMake side?
  4346. std::vector<std::string> const includes =
  4347. this->GetIncludes(configName, "MIDL");
  4348. std::ostringstream oss;
  4349. for (std::string const& i : includes) {
  4350. oss << i << ";";
  4351. }
  4352. oss << "%(AdditionalIncludeDirectories)";
  4353. Elem e2(e1, "Midl");
  4354. e2.Element("AdditionalIncludeDirectories", oss.str());
  4355. e2.Element("OutputDirectory", "$(ProjectDir)/$(IntDir)");
  4356. e2.Element("HeaderFileName", "%(Filename).h");
  4357. e2.Element("TypeLibraryName", "%(Filename).tlb");
  4358. e2.Element("InterfaceIdentifierFileName", "%(Filename)_i.c");
  4359. e2.Element("ProxyFileName", "%(Filename)_p.c");
  4360. }
  4361. void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups(Elem& e0)
  4362. {
  4363. if (this->ProjectType == VsProjectType::csproj) {
  4364. return;
  4365. }
  4366. for (const std::string& c : this->Configurations) {
  4367. Elem e1(e0, "ItemDefinitionGroup");
  4368. e1.Attribute("Condition", this->CalcCondition(c));
  4369. // output cl compile flags <ClCompile></ClCompile>
  4370. if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  4371. this->WriteClOptions(e1, c);
  4372. // output rc compile flags <ResourceCompile></ResourceCompile>
  4373. this->WriteRCOptions(e1, c);
  4374. this->WriteCudaOptions(e1, c);
  4375. this->WriteMarmasmOptions(e1, c);
  4376. this->WriteMasmOptions(e1, c);
  4377. this->WriteNasmOptions(e1, c);
  4378. }
  4379. // output midl flags <Midl></Midl>
  4380. this->WriteMidlOptions(e1, c);
  4381. // write events
  4382. if (this->ProjectType != VsProjectType::csproj) {
  4383. this->WriteEvents(e1, c);
  4384. }
  4385. // output link flags <Link></Link>
  4386. this->WriteLinkOptions(e1, c);
  4387. this->WriteCudaLinkOptions(e1, c);
  4388. // output lib flags <Lib></Lib>
  4389. this->WriteLibOptions(e1, c);
  4390. // output manifest flags <Manifest></Manifest>
  4391. this->WriteManifestOptions(e1, c);
  4392. if (this->NsightTegra &&
  4393. this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
  4394. this->WriteAntBuildOptions(e1, c);
  4395. }
  4396. }
  4397. }
  4398. void cmVisualStudio10TargetGenerator::WriteEvents(
  4399. Elem& e1, std::string const& configName)
  4400. {
  4401. bool addedPrelink = false;
  4402. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  4403. this->GeneratorTarget->GetModuleDefinitionInfo(configName);
  4404. if (mdi && mdi->DefFileGenerated) {
  4405. addedPrelink = true;
  4406. std::vector<cmCustomCommand> commands =
  4407. this->GeneratorTarget->GetPreLinkCommands();
  4408. this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
  4409. commands, configName);
  4410. this->WriteEvent(e1, "PreLinkEvent", commands, configName);
  4411. }
  4412. if (!addedPrelink) {
  4413. this->WriteEvent(e1, "PreLinkEvent",
  4414. this->GeneratorTarget->GetPreLinkCommands(), configName);
  4415. }
  4416. this->WriteEvent(e1, "PreBuildEvent",
  4417. this->GeneratorTarget->GetPreBuildCommands(), configName);
  4418. this->WriteEvent(e1, "PostBuildEvent",
  4419. this->GeneratorTarget->GetPostBuildCommands(), configName);
  4420. }
  4421. void cmVisualStudio10TargetGenerator::WriteEvent(
  4422. Elem& e1, const std::string& name,
  4423. std::vector<cmCustomCommand> const& commands, std::string const& configName)
  4424. {
  4425. if (commands.empty()) {
  4426. return;
  4427. }
  4428. cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
  4429. std::string script;
  4430. const char* pre = "";
  4431. std::string comment;
  4432. bool stdPipesUTF8 = false;
  4433. for (cmCustomCommand const& cc : commands) {
  4434. cmCustomCommandGenerator ccg(cc, configName, lg);
  4435. if (!ccg.HasOnlyEmptyCommandLines()) {
  4436. comment += pre;
  4437. comment += lg->ConstructComment(ccg);
  4438. script += pre;
  4439. pre = "\n";
  4440. script += lg->ConstructScript(ccg);
  4441. stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
  4442. }
  4443. }
  4444. if (!script.empty()) {
  4445. script += lg->FinishConstructScript(this->ProjectType);
  4446. }
  4447. comment = cmVS10EscapeComment(comment);
  4448. if (this->ProjectType != VsProjectType::csproj) {
  4449. Elem e2(e1, name);
  4450. if (stdPipesUTF8) {
  4451. this->WriteStdOutEncodingUtf8(e2);
  4452. }
  4453. e2.Element("Message", comment);
  4454. e2.Element("Command", script);
  4455. } else {
  4456. std::string strippedComment = comment;
  4457. strippedComment.erase(
  4458. std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
  4459. strippedComment.end());
  4460. std::ostringstream oss;
  4461. if (!comment.empty() && !strippedComment.empty()) {
  4462. oss << "echo " << comment << "\n";
  4463. }
  4464. oss << script << "\n";
  4465. e1.Element(name, oss.str());
  4466. }
  4467. }
  4468. void cmVisualStudio10TargetGenerator::WriteSdkStyleEvents(
  4469. Elem& e0, std::string const& configName)
  4470. {
  4471. this->WriteSdkStyleEvent(e0, "PreLink", "BeforeTargets", "Link",
  4472. this->GeneratorTarget->GetPreLinkCommands(),
  4473. configName);
  4474. this->WriteSdkStyleEvent(e0, "PreBuild", "BeforeTargets", "PreBuildEvent",
  4475. this->GeneratorTarget->GetPreBuildCommands(),
  4476. configName);
  4477. this->WriteSdkStyleEvent(e0, "PostBuild", "AfterTargets", "PostBuildEvent",
  4478. this->GeneratorTarget->GetPostBuildCommands(),
  4479. configName);
  4480. }
  4481. void cmVisualStudio10TargetGenerator::WriteSdkStyleEvent(
  4482. Elem& e0, const std::string& name, const std::string& when,
  4483. const std::string& target, std::vector<cmCustomCommand> const& commands,
  4484. std::string const& configName)
  4485. {
  4486. if (commands.empty()) {
  4487. return;
  4488. }
  4489. Elem e1(e0, "Target");
  4490. e1.Attribute("Condition",
  4491. cmStrCat("'$(Configuration)' == '", configName, '\''));
  4492. e1.Attribute("Name", name + configName);
  4493. e1.Attribute(when.c_str(), target);
  4494. e1.SetHasElements();
  4495. cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
  4496. std::string script;
  4497. const char* pre = "";
  4498. std::string comment;
  4499. bool stdPipesUTF8 = false;
  4500. for (cmCustomCommand const& cc : commands) {
  4501. cmCustomCommandGenerator ccg(cc, configName, lg);
  4502. if (!ccg.HasOnlyEmptyCommandLines()) {
  4503. comment += pre;
  4504. comment += lg->ConstructComment(ccg);
  4505. script += pre;
  4506. pre = "\n";
  4507. script += lg->ConstructScript(ccg);
  4508. stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
  4509. }
  4510. }
  4511. if (!script.empty()) {
  4512. script += lg->FinishConstructScript(this->ProjectType);
  4513. }
  4514. comment = cmVS10EscapeComment(comment);
  4515. std::string strippedComment = comment;
  4516. strippedComment.erase(
  4517. std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
  4518. strippedComment.end());
  4519. std::ostringstream oss;
  4520. if (!comment.empty() && !strippedComment.empty()) {
  4521. oss << "echo " << comment << "\n";
  4522. }
  4523. oss << script << "\n";
  4524. Elem e2(e1, "Exec");
  4525. e2.Attribute("Command", oss.str());
  4526. }
  4527. void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0)
  4528. {
  4529. cmGlobalGenerator::TargetDependSet const& unordered =
  4530. this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
  4531. using OrderedTargetDependSet =
  4532. cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
  4533. OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  4534. Elem e1(e0, "ItemGroup");
  4535. e1.SetHasElements();
  4536. for (cmGeneratorTarget const* dt : depends) {
  4537. if (!dt->IsInBuildSystem()) {
  4538. continue;
  4539. }
  4540. // skip fortran targets as they can not be processed by MSBuild
  4541. // the only reference will be in the .sln file
  4542. if (this->GlobalGenerator->TargetIsFortranOnly(dt)) {
  4543. continue;
  4544. }
  4545. cmLocalGenerator* lg = dt->GetLocalGenerator();
  4546. std::string name = dt->GetName();
  4547. std::string path;
  4548. if (cmValue p = dt->GetProperty("EXTERNAL_MSPROJECT")) {
  4549. path = *p;
  4550. } else {
  4551. path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(),
  4552. computeProjectFileExtension(dt));
  4553. }
  4554. ConvertToWindowsSlash(path);
  4555. Elem e2(e1, "ProjectReference");
  4556. e2.Attribute("Include", path);
  4557. e2.Element("Project",
  4558. cmStrCat('{', this->GlobalGenerator->GetGUID(name), '}'));
  4559. e2.Element("Name", name);
  4560. this->WriteDotNetReferenceCustomTags(e2, name);
  4561. if (dt->IsCSharpOnly() || cmHasLiteralSuffix(path, "csproj")) {
  4562. e2.Element("SkipGetTargetFrameworkProperties", "true");
  4563. }
  4564. // Don't reference targets that don't produce any output.
  4565. else if (this->Configurations.empty() ||
  4566. dt->GetManagedType(this->Configurations[0]) ==
  4567. cmGeneratorTarget::ManagedType::Undefined) {
  4568. e2.Element("ReferenceOutputAssembly", "false");
  4569. e2.Element("CopyToOutputDirectory", "Never");
  4570. }
  4571. }
  4572. }
  4573. void cmVisualStudio10TargetGenerator::WritePlatformExtensions(Elem& e1)
  4574. {
  4575. // This only applies to Windows 10 apps
  4576. if (this->GlobalGenerator->TargetsWindowsStore() &&
  4577. cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
  4578. cmValue desktopExtensionsVersion =
  4579. this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
  4580. if (desktopExtensionsVersion) {
  4581. this->WriteSinglePlatformExtension(e1, "WindowsDesktop",
  4582. *desktopExtensionsVersion);
  4583. }
  4584. cmValue mobileExtensionsVersion =
  4585. this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
  4586. if (mobileExtensionsVersion) {
  4587. this->WriteSinglePlatformExtension(e1, "WindowsMobile",
  4588. *mobileExtensionsVersion);
  4589. }
  4590. }
  4591. }
  4592. void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
  4593. Elem& e1, std::string const& extension, std::string const& version)
  4594. {
  4595. const std::string s =
  4596. cmStrCat("$([Microsoft.Build.Utilities.ToolLocationHelper]"
  4597. "::GetPlatformExtensionSDKLocation(`",
  4598. extension, ", Version=", version,
  4599. "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
  4600. "$(ExtensionSDKDirectoryRoot), null))"
  4601. "\\DesignTime\\CommonConfiguration\\Neutral\\",
  4602. extension, ".props");
  4603. Elem e2(e1, "Import");
  4604. e2.Attribute("Project", s);
  4605. e2.Attribute("Condition", cmStrCat("exists('", s, "')"));
  4606. }
  4607. void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0)
  4608. {
  4609. cmList sdkReferences;
  4610. std::unique_ptr<Elem> spe1;
  4611. if (cmValue vsSDKReferences =
  4612. this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
  4613. sdkReferences.assign(*vsSDKReferences);
  4614. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  4615. for (auto const& ri : sdkReferences) {
  4616. Elem(*spe1, "SDKReference").Attribute("Include", ri);
  4617. }
  4618. }
  4619. // This only applies to Windows 10 apps
  4620. if (this->GlobalGenerator->TargetsWindowsStore() &&
  4621. cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
  4622. cmValue desktopExtensionsVersion =
  4623. this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
  4624. cmValue mobileExtensionsVersion =
  4625. this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
  4626. cmValue iotExtensionsVersion =
  4627. this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
  4628. if (desktopExtensionsVersion || mobileExtensionsVersion ||
  4629. iotExtensionsVersion) {
  4630. if (!spe1) {
  4631. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  4632. }
  4633. if (desktopExtensionsVersion) {
  4634. this->WriteSingleSDKReference(*spe1, "WindowsDesktop",
  4635. *desktopExtensionsVersion);
  4636. }
  4637. if (mobileExtensionsVersion) {
  4638. this->WriteSingleSDKReference(*spe1, "WindowsMobile",
  4639. *mobileExtensionsVersion);
  4640. }
  4641. if (iotExtensionsVersion) {
  4642. this->WriteSingleSDKReference(*spe1, "WindowsIoT",
  4643. *iotExtensionsVersion);
  4644. }
  4645. }
  4646. }
  4647. }
  4648. void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
  4649. Elem& e1, std::string const& extension, std::string const& version)
  4650. {
  4651. Elem(e1, "SDKReference")
  4652. .Attribute("Include", cmStrCat(extension, ", Version=", version));
  4653. }
  4654. namespace {
  4655. std::string ComputeCertificateThumbprint(const std::string& source)
  4656. {
  4657. std::string thumbprint;
  4658. CRYPT_INTEGER_BLOB cryptBlob;
  4659. HCERTSTORE certStore = nullptr;
  4660. PCCERT_CONTEXT certContext = nullptr;
  4661. HANDLE certFile = CreateFileW(
  4662. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  4663. FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  4664. if (certFile != INVALID_HANDLE_VALUE && certFile) {
  4665. DWORD fileSize = GetFileSize(certFile, nullptr);
  4666. if (fileSize != INVALID_FILE_SIZE) {
  4667. auto certData = cm::make_unique<BYTE[]>(fileSize);
  4668. if (certData) {
  4669. DWORD dwRead = 0;
  4670. if (ReadFile(certFile, certData.get(), fileSize, &dwRead, nullptr)) {
  4671. cryptBlob.cbData = fileSize;
  4672. cryptBlob.pbData = certData.get();
  4673. // Verify that this is a valid cert
  4674. if (PFXIsPFXBlob(&cryptBlob)) {
  4675. // Open the certificate as a store
  4676. certStore =
  4677. PFXImportCertStore(&cryptBlob, nullptr, CRYPT_EXPORTABLE);
  4678. if (certStore) {
  4679. // There should only be 1 cert.
  4680. certContext =
  4681. CertEnumCertificatesInStore(certStore, certContext);
  4682. if (certContext) {
  4683. // The hash is 20 bytes
  4684. BYTE hashData[20];
  4685. DWORD hashLength = 20;
  4686. // Buffer to print the hash. Each byte takes 2 chars +
  4687. // terminating character
  4688. char hashPrint[41];
  4689. char* pHashPrint = hashPrint;
  4690. // Get the hash property from the certificate
  4691. if (CertGetCertificateContextProperty(
  4692. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  4693. for (DWORD i = 0; i < hashLength; i++) {
  4694. // Convert each byte to hexadecimal
  4695. snprintf(pHashPrint, 3, "%02X", hashData[i]);
  4696. pHashPrint += 2;
  4697. }
  4698. *pHashPrint = '\0';
  4699. thumbprint = hashPrint;
  4700. }
  4701. CertFreeCertificateContext(certContext);
  4702. }
  4703. CertCloseStore(certStore, 0);
  4704. }
  4705. }
  4706. }
  4707. }
  4708. }
  4709. CloseHandle(certFile);
  4710. }
  4711. return thumbprint;
  4712. }
  4713. }
  4714. void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile(
  4715. Elem& e0)
  4716. {
  4717. if ((this->GlobalGenerator->TargetsWindowsStore() ||
  4718. this->GlobalGenerator->TargetsWindowsPhone()) &&
  4719. (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
  4720. std::string pfxFile;
  4721. for (cmGeneratorTarget::AllConfigSource const& source :
  4722. this->GeneratorTarget->GetAllConfigSources()) {
  4723. if (source.Kind == cmGeneratorTarget::SourceKindCertificate) {
  4724. pfxFile = this->ConvertPath(source.Source->GetFullPath(), false);
  4725. ConvertToWindowsSlash(pfxFile);
  4726. break;
  4727. }
  4728. }
  4729. if (this->IsMissingFiles &&
  4730. !(this->GlobalGenerator->TargetsWindowsPhone() &&
  4731. this->GlobalGenerator->GetSystemVersion() == "8.0"_s)) {
  4732. // Move the manifest to a project directory to avoid clashes
  4733. std::string artifactDir =
  4734. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4735. ConvertToWindowsSlash(artifactDir);
  4736. Elem e1(e0, "PropertyGroup");
  4737. e1.Element("AppxPackageArtifactsDir", cmStrCat(artifactDir, '\\'));
  4738. std::string resourcePriFile =
  4739. cmStrCat(this->DefaultArtifactDir, "/resources.pri");
  4740. ConvertToWindowsSlash(resourcePriFile);
  4741. e1.Element("ProjectPriFullPath", resourcePriFile);
  4742. // If we are missing files and we don't have a certificate and
  4743. // aren't targeting WP8.0, add a default certificate
  4744. if (pfxFile.empty()) {
  4745. std::string templateFolder =
  4746. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  4747. pfxFile =
  4748. cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
  4749. cmSystemTools::CopyAFile(
  4750. cmStrCat(templateFolder, "/Windows_TemporaryKey.pfx"), pfxFile,
  4751. false);
  4752. ConvertToWindowsSlash(pfxFile);
  4753. this->AddedFiles.push_back(pfxFile);
  4754. this->AddedDefaultCertificate = true;
  4755. }
  4756. e1.Element("PackageCertificateKeyFile", pfxFile);
  4757. std::string thumb = ComputeCertificateThumbprint(pfxFile);
  4758. if (!thumb.empty()) {
  4759. e1.Element("PackageCertificateThumbprint", thumb);
  4760. }
  4761. } else if (!pfxFile.empty()) {
  4762. Elem e1(e0, "PropertyGroup");
  4763. e1.Element("PackageCertificateKeyFile", pfxFile);
  4764. std::string thumb = ComputeCertificateThumbprint(pfxFile);
  4765. if (!thumb.empty()) {
  4766. e1.Element("PackageCertificateThumbprint", thumb);
  4767. }
  4768. }
  4769. }
  4770. }
  4771. void cmVisualStudio10TargetGenerator::ClassifyAllConfigSources()
  4772. {
  4773. for (cmGeneratorTarget::AllConfigSource const& source :
  4774. this->GeneratorTarget->GetAllConfigSources()) {
  4775. this->ClassifyAllConfigSource(source);
  4776. }
  4777. }
  4778. void cmVisualStudio10TargetGenerator::ClassifyAllConfigSource(
  4779. cmGeneratorTarget::AllConfigSource const& acs)
  4780. {
  4781. switch (acs.Kind) {
  4782. case cmGeneratorTarget::SourceKindResx: {
  4783. // Build and save the name of the corresponding .h file
  4784. // This relationship will be used later when building the project files.
  4785. // Both names would have been auto generated from Visual Studio
  4786. // where the user supplied the file name and Visual Studio
  4787. // appended the suffix.
  4788. std::string resx = acs.Source->ResolveFullPath();
  4789. std::string hFileName =
  4790. cmStrCat(resx.substr(0, resx.find_last_of('.')), ".h");
  4791. this->ExpectedResxHeaders.insert(hFileName);
  4792. } break;
  4793. case cmGeneratorTarget::SourceKindXaml: {
  4794. // Build and save the name of the corresponding .h and .cpp file
  4795. // This relationship will be used later when building the project files.
  4796. // Both names would have been auto generated from Visual Studio
  4797. // where the user supplied the file name and Visual Studio
  4798. // appended the suffix.
  4799. std::string xaml = acs.Source->ResolveFullPath();
  4800. std::string hFileName = cmStrCat(xaml, ".h");
  4801. std::string cppFileName = cmStrCat(xaml, ".cpp");
  4802. this->ExpectedXamlHeaders.insert(hFileName);
  4803. this->ExpectedXamlSources.insert(cppFileName);
  4804. } break;
  4805. default:
  4806. break;
  4807. }
  4808. }
  4809. bool cmVisualStudio10TargetGenerator::IsResxHeader(
  4810. const std::string& headerFile)
  4811. {
  4812. return this->ExpectedResxHeaders.count(headerFile) > 0;
  4813. }
  4814. bool cmVisualStudio10TargetGenerator::IsXamlHeader(
  4815. const std::string& headerFile)
  4816. {
  4817. return this->ExpectedXamlHeaders.count(headerFile) > 0;
  4818. }
  4819. bool cmVisualStudio10TargetGenerator::IsXamlSource(
  4820. const std::string& sourceFile)
  4821. {
  4822. return this->ExpectedXamlSources.count(sourceFile) > 0;
  4823. }
  4824. void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1)
  4825. {
  4826. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  4827. bool isAppContainer = false;
  4828. bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
  4829. bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
  4830. bool const isAndroid = this->GlobalGenerator->TargetsAndroid();
  4831. std::string const& rev = this->GlobalGenerator->GetApplicationTypeRevision();
  4832. if (isWindowsPhone || isWindowsStore) {
  4833. e1.Element("ApplicationType",
  4834. (isWindowsPhone ? "Windows Phone" : "Windows Store"));
  4835. e1.Element("DefaultLanguage", "en-US");
  4836. if (rev == "10.0"_s) {
  4837. e1.Element("ApplicationTypeRevision", rev);
  4838. // Visual Studio 14.0 is necessary for building 10.0 apps
  4839. e1.Element("MinimumVisualStudioVersion", "14.0");
  4840. if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4841. isAppContainer = true;
  4842. }
  4843. } else if (rev == "8.1"_s) {
  4844. e1.Element("ApplicationTypeRevision", rev);
  4845. // Visual Studio 12.0 is necessary for building 8.1 apps
  4846. e1.Element("MinimumVisualStudioVersion", "12.0");
  4847. if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4848. isAppContainer = true;
  4849. }
  4850. } else if (rev == "8.0"_s) {
  4851. e1.Element("ApplicationTypeRevision", rev);
  4852. // Visual Studio 11.0 is necessary for building 8.0 apps
  4853. e1.Element("MinimumVisualStudioVersion", "11.0");
  4854. if (isWindowsStore &&
  4855. this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4856. isAppContainer = true;
  4857. } else if (isWindowsPhone &&
  4858. this->GeneratorTarget->GetType() ==
  4859. cmStateEnums::EXECUTABLE) {
  4860. e1.Element("XapOutputs", "true");
  4861. e1.Element("XapFilename",
  4862. cmStrCat(this->Name, "_$(Configuration)_$(Platform).xap"));
  4863. }
  4864. }
  4865. } else if (isAndroid) {
  4866. e1.Element("ApplicationType", "Android");
  4867. e1.Element("ApplicationTypeRevision",
  4868. gg->GetAndroidApplicationTypeRevision());
  4869. }
  4870. if (isAppContainer) {
  4871. e1.Element("AppContainerApplication", "true");
  4872. } else if (!isAndroid) {
  4873. if (this->Platform == "ARM64"_s) {
  4874. e1.Element("WindowsSDKDesktopARM64Support", "true");
  4875. } else if (this->Platform == "ARM"_s) {
  4876. e1.Element("WindowsSDKDesktopARMSupport", "true");
  4877. }
  4878. }
  4879. std::string const& targetPlatformVersion =
  4880. gg->GetWindowsTargetPlatformVersion();
  4881. if (!targetPlatformVersion.empty()) {
  4882. e1.Element("WindowsTargetPlatformVersion", targetPlatformVersion);
  4883. }
  4884. cmValue targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
  4885. "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
  4886. if (targetPlatformMinVersion) {
  4887. e1.Element("WindowsTargetPlatformMinVersion", *targetPlatformMinVersion);
  4888. } else if (isWindowsStore && rev == "10.0"_s) {
  4889. // If the min version is not set, then use the TargetPlatformVersion
  4890. if (!targetPlatformVersion.empty()) {
  4891. e1.Element("WindowsTargetPlatformMinVersion", targetPlatformVersion);
  4892. }
  4893. }
  4894. // Added IoT Startup Task support
  4895. if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
  4896. e1.Element("ContainsStartupTask", "true");
  4897. }
  4898. }
  4899. void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
  4900. {
  4901. // For Windows and Windows Phone executables, we will assume that if a
  4902. // manifest is not present that we need to add all the necessary files
  4903. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4904. std::vector<cmGeneratorTarget::AllConfigSource> manifestSources =
  4905. this->GeneratorTarget->GetAllConfigSources(
  4906. cmGeneratorTarget::SourceKindAppManifest);
  4907. std::string const& v = this->GlobalGenerator->GetSystemVersion();
  4908. if (this->GlobalGenerator->TargetsWindowsPhone()) {
  4909. if (v == "8.0"_s) {
  4910. // Look through the sources for WMAppManifest.xml
  4911. bool foundManifest = false;
  4912. for (cmGeneratorTarget::AllConfigSource const& source :
  4913. this->GeneratorTarget->GetAllConfigSources()) {
  4914. if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
  4915. "wmappmanifest.xml" ==
  4916. cmSystemTools::LowerCase(
  4917. source.Source->GetLocation().GetName())) {
  4918. foundManifest = true;
  4919. break;
  4920. }
  4921. }
  4922. if (!foundManifest) {
  4923. this->IsMissingFiles = true;
  4924. }
  4925. } else if (v == "8.1"_s) {
  4926. if (manifestSources.empty()) {
  4927. this->IsMissingFiles = true;
  4928. }
  4929. }
  4930. } else if (this->GlobalGenerator->TargetsWindowsStore()) {
  4931. if (manifestSources.empty()) {
  4932. if (v == "8.0"_s) {
  4933. this->IsMissingFiles = true;
  4934. } else if (v == "8.1"_s || cmHasLiteralPrefix(v, "10.0")) {
  4935. this->IsMissingFiles = true;
  4936. }
  4937. }
  4938. }
  4939. }
  4940. }
  4941. void cmVisualStudio10TargetGenerator::WriteMissingFiles(Elem& e1)
  4942. {
  4943. std::string const& v = this->GlobalGenerator->GetSystemVersion();
  4944. if (this->GlobalGenerator->TargetsWindowsPhone()) {
  4945. if (v == "8.0"_s) {
  4946. this->WriteMissingFilesWP80(e1);
  4947. } else if (v == "8.1"_s) {
  4948. this->WriteMissingFilesWP81(e1);
  4949. }
  4950. } else if (this->GlobalGenerator->TargetsWindowsStore()) {
  4951. if (v == "8.0"_s) {
  4952. this->WriteMissingFilesWS80(e1);
  4953. } else if (v == "8.1"_s) {
  4954. this->WriteMissingFilesWS81(e1);
  4955. } else if (cmHasLiteralPrefix(v, "10.0")) {
  4956. this->WriteMissingFilesWS10_0(e1);
  4957. }
  4958. }
  4959. }
  4960. void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80(Elem& e1)
  4961. {
  4962. std::string templateFolder =
  4963. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  4964. // For WP80, the manifest needs to be in the same folder as the project
  4965. // this can cause an overwrite problem if projects aren't organized in
  4966. // folders
  4967. std::string manifestFile = cmStrCat(
  4968. this->LocalGenerator->GetCurrentBinaryDirectory(), "/WMAppManifest.xml");
  4969. std::string artifactDir =
  4970. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4971. ConvertToWindowsSlash(artifactDir);
  4972. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  4973. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  4974. cmGeneratedFileStream fout(manifestFile);
  4975. fout.SetCopyIfDifferent(true);
  4976. /* clang-format off */
  4977. fout <<
  4978. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  4979. "<Deployment"
  4980. " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
  4981. " AppPlatformVersion=\"8.0\">\n"
  4982. "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
  4983. "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
  4984. " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
  4985. " Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"CMake\""
  4986. " Description=\"Default CMake App\" Publisher=\"CMake\""
  4987. " PublisherID=\"{" << this->GUID << "}\">\n"
  4988. "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
  4989. << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
  4990. "\t\t<Capabilities/>\n"
  4991. "\t\t<Tasks>\n"
  4992. "\t\t\t<DefaultTask Name=\"_default\""
  4993. " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
  4994. "\t\t</Tasks>\n"
  4995. "\t\t<Tokens>\n"
  4996. "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
  4997. " TaskName=\"_default\">\n"
  4998. "\t\t\t\t<TemplateFlip>\n"
  4999. "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
  5000. << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
  5001. "\t\t\t\t\t<Count>0</Count>\n"
  5002. "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
  5003. << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
  5004. "\t\t\t\t</TemplateFlip>\n"
  5005. "\t\t\t</PrimaryToken>\n"
  5006. "\t\t</Tokens>\n"
  5007. "\t\t<ScreenResolutions>\n"
  5008. "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
  5009. "\t\t</ScreenResolutions>\n"
  5010. "\t</App>\n"
  5011. "</Deployment>\n";
  5012. /* clang-format on */
  5013. std::string sourceFile = this->ConvertPath(manifestFile, false);
  5014. ConvertToWindowsSlash(sourceFile);
  5015. {
  5016. Elem e2(e1, "Xml");
  5017. e2.Attribute("Include", sourceFile);
  5018. e2.Element("SubType", "Designer");
  5019. }
  5020. this->AddedFiles.push_back(sourceFile);
  5021. std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
  5022. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
  5023. smallLogo, false);
  5024. ConvertToWindowsSlash(smallLogo);
  5025. Elem(e1, "Image").Attribute("Include", smallLogo);
  5026. this->AddedFiles.push_back(smallLogo);
  5027. std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
  5028. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
  5029. ConvertToWindowsSlash(logo);
  5030. Elem(e1, "Image").Attribute("Include", logo);
  5031. this->AddedFiles.push_back(logo);
  5032. std::string applicationIcon =
  5033. cmStrCat(this->DefaultArtifactDir, "/ApplicationIcon.png");
  5034. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/ApplicationIcon.png"),
  5035. applicationIcon, false);
  5036. ConvertToWindowsSlash(applicationIcon);
  5037. Elem(e1, "Image").Attribute("Include", applicationIcon);
  5038. this->AddedFiles.push_back(applicationIcon);
  5039. }
  5040. void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81(Elem& e1)
  5041. {
  5042. std::string manifestFile =
  5043. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5044. std::string artifactDir =
  5045. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5046. ConvertToWindowsSlash(artifactDir);
  5047. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5048. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5049. cmGeneratedFileStream fout(manifestFile);
  5050. fout.SetCopyIfDifferent(true);
  5051. /* clang-format off */
  5052. fout <<
  5053. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5054. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
  5055. " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
  5056. " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
  5057. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5058. " Version=\"1.0.0.0\" />\n"
  5059. "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
  5060. " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
  5061. "\t<Properties>\n"
  5062. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5063. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5064. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5065. "\t</Properties>\n"
  5066. "\t<Prerequisites>\n"
  5067. "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
  5068. "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
  5069. "\t</Prerequisites>\n"
  5070. "\t<Resources>\n"
  5071. "\t\t<Resource Language=\"x-generate\" />\n"
  5072. "\t</Resources>\n"
  5073. "\t<Applications>\n"
  5074. "\t\t<Application Id=\"App\""
  5075. " Executable=\"" << targetNameXML << ".exe\""
  5076. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5077. "\t\t\t<m2:VisualElements\n"
  5078. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5079. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5080. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5081. "\t\t\t\tForegroundText=\"light\"\n"
  5082. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5083. "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5084. "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
  5085. "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
  5086. "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
  5087. "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
  5088. "\t\t\t\t</m2:DefaultTile>\n"
  5089. "\t\t\t\t<m2:SplashScreen"
  5090. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5091. "\t\t\t</m2:VisualElements>\n"
  5092. "\t\t</Application>\n"
  5093. "\t</Applications>\n"
  5094. "</Package>\n";
  5095. /* clang-format on */
  5096. this->WriteCommonMissingFiles(e1, manifestFile);
  5097. }
  5098. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80(Elem& e1)
  5099. {
  5100. std::string manifestFile =
  5101. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5102. std::string artifactDir =
  5103. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5104. ConvertToWindowsSlash(artifactDir);
  5105. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5106. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5107. cmGeneratedFileStream fout(manifestFile);
  5108. fout.SetCopyIfDifferent(true);
  5109. /* clang-format off */
  5110. fout <<
  5111. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5112. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
  5113. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5114. " Version=\"1.0.0.0\" />\n"
  5115. "\t<Properties>\n"
  5116. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5117. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5118. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5119. "\t</Properties>\n"
  5120. "\t<Prerequisites>\n"
  5121. "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
  5122. "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
  5123. "\t</Prerequisites>\n"
  5124. "\t<Resources>\n"
  5125. "\t\t<Resource Language=\"x-generate\" />\n"
  5126. "\t</Resources>\n"
  5127. "\t<Applications>\n"
  5128. "\t\t<Application Id=\"App\""
  5129. " Executable=\"" << targetNameXML << ".exe\""
  5130. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5131. "\t\t\t<VisualElements"
  5132. " DisplayName=\"" << targetNameXML << "\""
  5133. " Description=\"" << targetNameXML << "\""
  5134. " BackgroundColor=\"#336699\" ForegroundText=\"light\""
  5135. " Logo=\"" << artifactDirXML << "\\Logo.png\""
  5136. " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5137. "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
  5138. " ShortName=\"" << targetNameXML << "\" />\n"
  5139. "\t\t\t\t<SplashScreen"
  5140. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5141. "\t\t\t</VisualElements>\n"
  5142. "\t\t</Application>\n"
  5143. "\t</Applications>\n"
  5144. "</Package>\n";
  5145. /* clang-format on */
  5146. this->WriteCommonMissingFiles(e1, manifestFile);
  5147. }
  5148. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81(Elem& e1)
  5149. {
  5150. std::string manifestFile =
  5151. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5152. std::string artifactDir =
  5153. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5154. ConvertToWindowsSlash(artifactDir);
  5155. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5156. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5157. cmGeneratedFileStream fout(manifestFile);
  5158. fout.SetCopyIfDifferent(true);
  5159. /* clang-format off */
  5160. fout <<
  5161. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5162. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
  5163. " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
  5164. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5165. " Version=\"1.0.0.0\" />\n"
  5166. "\t<Properties>\n"
  5167. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5168. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5169. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5170. "\t</Properties>\n"
  5171. "\t<Prerequisites>\n"
  5172. "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
  5173. "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
  5174. "\t</Prerequisites>\n"
  5175. "\t<Resources>\n"
  5176. "\t\t<Resource Language=\"x-generate\" />\n"
  5177. "\t</Resources>\n"
  5178. "\t<Applications>\n"
  5179. "\t\t<Application Id=\"App\""
  5180. " Executable=\"" << targetNameXML << ".exe\""
  5181. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5182. "\t\t\t<m2:VisualElements\n"
  5183. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5184. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5185. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5186. "\t\t\t\tForegroundText=\"light\"\n"
  5187. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5188. "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5189. "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
  5190. "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
  5191. "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
  5192. "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
  5193. "\t\t\t\t</m2:DefaultTile>\n"
  5194. "\t\t\t\t<m2:SplashScreen"
  5195. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5196. "\t\t\t</m2:VisualElements>\n"
  5197. "\t\t</Application>\n"
  5198. "\t</Applications>\n"
  5199. "</Package>\n";
  5200. /* clang-format on */
  5201. this->WriteCommonMissingFiles(e1, manifestFile);
  5202. }
  5203. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0(Elem& e1)
  5204. {
  5205. std::string manifestFile =
  5206. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5207. std::string artifactDir =
  5208. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5209. ConvertToWindowsSlash(artifactDir);
  5210. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5211. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5212. cmGeneratedFileStream fout(manifestFile);
  5213. fout.SetCopyIfDifferent(true);
  5214. /* clang-format off */
  5215. fout <<
  5216. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5217. "<Package\n\t"
  5218. "xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
  5219. "\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
  5220. "\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
  5221. "\n\tIgnorableNamespaces=\"uap mp\">\n\n"
  5222. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5223. " Version=\"1.0.0.0\" />\n"
  5224. "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
  5225. "\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
  5226. "\t<Properties>\n"
  5227. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5228. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5229. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5230. "\t</Properties>\n"
  5231. "\t<Dependencies>\n"
  5232. "\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
  5233. "MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
  5234. "\t</Dependencies>\n"
  5235. "\t<Resources>\n"
  5236. "\t\t<Resource Language=\"x-generate\" />\n"
  5237. "\t</Resources>\n"
  5238. "\t<Applications>\n"
  5239. "\t\t<Application Id=\"App\""
  5240. " Executable=\"" << targetNameXML << ".exe\""
  5241. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5242. "\t\t\t<uap:VisualElements\n"
  5243. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5244. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5245. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5246. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5247. "\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
  5248. "\\SmallLogo44x44.png\">\n"
  5249. "\t\t\t\t<uap:SplashScreen"
  5250. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5251. "\t\t\t</uap:VisualElements>\n"
  5252. "\t\t</Application>\n"
  5253. "\t</Applications>\n"
  5254. "</Package>\n";
  5255. /* clang-format on */
  5256. this->WriteCommonMissingFiles(e1, manifestFile);
  5257. }
  5258. void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
  5259. Elem& e1, const std::string& manifestFile)
  5260. {
  5261. std::string templateFolder =
  5262. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  5263. std::string sourceFile = this->ConvertPath(manifestFile, false);
  5264. ConvertToWindowsSlash(sourceFile);
  5265. {
  5266. Elem e2(e1, "AppxManifest");
  5267. e2.Attribute("Include", sourceFile);
  5268. e2.Element("SubType", "Designer");
  5269. }
  5270. this->AddedFiles.push_back(sourceFile);
  5271. std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
  5272. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
  5273. smallLogo, false);
  5274. ConvertToWindowsSlash(smallLogo);
  5275. Elem(e1, "Image").Attribute("Include", smallLogo);
  5276. this->AddedFiles.push_back(smallLogo);
  5277. std::string smallLogo44 =
  5278. cmStrCat(this->DefaultArtifactDir, "/SmallLogo44x44.png");
  5279. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo44x44.png"),
  5280. smallLogo44, false);
  5281. ConvertToWindowsSlash(smallLogo44);
  5282. Elem(e1, "Image").Attribute("Include", smallLogo44);
  5283. this->AddedFiles.push_back(smallLogo44);
  5284. std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
  5285. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
  5286. ConvertToWindowsSlash(logo);
  5287. Elem(e1, "Image").Attribute("Include", logo);
  5288. this->AddedFiles.push_back(logo);
  5289. std::string storeLogo = cmStrCat(this->DefaultArtifactDir, "/StoreLogo.png");
  5290. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/StoreLogo.png"),
  5291. storeLogo, false);
  5292. ConvertToWindowsSlash(storeLogo);
  5293. Elem(e1, "Image").Attribute("Include", storeLogo);
  5294. this->AddedFiles.push_back(storeLogo);
  5295. std::string splashScreen =
  5296. cmStrCat(this->DefaultArtifactDir, "/SplashScreen.png");
  5297. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SplashScreen.png"),
  5298. splashScreen, false);
  5299. ConvertToWindowsSlash(splashScreen);
  5300. Elem(e1, "Image").Attribute("Include", splashScreen);
  5301. this->AddedFiles.push_back(splashScreen);
  5302. if (this->AddedDefaultCertificate) {
  5303. // This file has already been added to the build so don't copy it
  5304. std::string keyFile =
  5305. cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
  5306. ConvertToWindowsSlash(keyFile);
  5307. Elem(e1, "None").Attribute("Include", keyFile);
  5308. }
  5309. }
  5310. bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
  5311. {
  5312. HANDLE h =
  5313. CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
  5314. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
  5315. FILE_FLAG_BACKUP_SEMANTICS, 0);
  5316. if (!h) {
  5317. return false;
  5318. }
  5319. FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
  5320. if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
  5321. CloseHandle(h);
  5322. return false;
  5323. }
  5324. CloseHandle(h);
  5325. return true;
  5326. }
  5327. void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
  5328. cmSourceFile const* sf, std::map<std::string, std::string>& tags)
  5329. {
  5330. if (this->ProjectType == VsProjectType::csproj) {
  5331. const cmPropertyMap& props = sf->GetProperties();
  5332. for (const std::string& p : props.GetKeys()) {
  5333. static const cm::string_view propNamePrefix = "VS_CSHARP_";
  5334. if (cmHasPrefix(p, propNamePrefix)) {
  5335. std::string tagName = p.substr(propNamePrefix.length());
  5336. if (!tagName.empty()) {
  5337. cmValue val = props.GetPropertyValue(p);
  5338. if (cmNonempty(val)) {
  5339. tags[tagName] = *val;
  5340. } else {
  5341. tags.erase(tagName);
  5342. }
  5343. }
  5344. }
  5345. }
  5346. }
  5347. }
  5348. void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
  5349. Elem& e2, const std::map<std::string, std::string>& tags)
  5350. {
  5351. for (const auto& i : tags) {
  5352. e2.Element(i.first, i.second);
  5353. }
  5354. }
  5355. std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
  5356. cmSourceFile const* source)
  5357. {
  5358. // For out of source files, we first check if a matching source group
  5359. // for this file exists, otherwise we check if the path relative to current
  5360. // source- or binary-dir is used within the link and return that.
  5361. // In case of .cs files we can't do that automatically for files in the
  5362. // binary directory, because this leads to compilation errors.
  5363. std::string link;
  5364. std::string sourceGroupedFile;
  5365. std::string const& fullFileName = source->GetFullPath();
  5366. std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory();
  5367. std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory();
  5368. // unfortunately we have to copy the source groups, because
  5369. // FindSourceGroup uses a regex which is modifying the group
  5370. std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
  5371. cmSourceGroup* sourceGroup =
  5372. this->Makefile->FindSourceGroup(fullFileName, sourceGroups);
  5373. if (sourceGroup && !sourceGroup->GetFullName().empty()) {
  5374. sourceGroupedFile =
  5375. cmStrCat(sourceGroup->GetFullName(), '/',
  5376. cmsys::SystemTools::GetFilenameName(fullFileName));
  5377. cmsys::SystemTools::ConvertToUnixSlashes(sourceGroupedFile);
  5378. }
  5379. if (!sourceGroupedFile.empty() &&
  5380. cmHasSuffix(fullFileName, sourceGroupedFile)) {
  5381. link = sourceGroupedFile;
  5382. } else if (cmHasPrefix(fullFileName, srcDir)) {
  5383. link = fullFileName.substr(srcDir.length() + 1);
  5384. } else if (!cmHasSuffix(fullFileName, ".cs") &&
  5385. cmHasPrefix(fullFileName, binDir)) {
  5386. link = fullFileName.substr(binDir.length() + 1);
  5387. } else if (cmValue l = source->GetProperty("VS_CSHARP_Link")) {
  5388. link = *l;
  5389. }
  5390. ConvertToWindowsSlash(link);
  5391. return link;
  5392. }
  5393. std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
  5394. const char* relativeFilePath) const
  5395. {
  5396. // Always search in the standard modules location.
  5397. std::string path =
  5398. cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath);
  5399. ConvertToWindowsSlash(path);
  5400. return path;
  5401. }
  5402. void cmVisualStudio10TargetGenerator::WriteStdOutEncodingUtf8(Elem& e1)
  5403. {
  5404. if (this->GlobalGenerator->IsUtf8EncodingSupported()) {
  5405. e1.Element("UseUtf8Encoding", "Always");
  5406. } else if (this->GlobalGenerator->IsStdOutEncodingSupported()) {
  5407. e1.Element("StdOutEncoding", "UTF-8");
  5408. }
  5409. }
  5410. void cmVisualStudio10TargetGenerator::UpdateCache()
  5411. {
  5412. std::vector<std::string> packageReferences;
  5413. if (this->GeneratorTarget->IsDotNetSdkTarget() ||
  5414. this->GeneratorTarget->HasPackageReferences()) {
  5415. // Store a cache entry that later determines, if a package restore is
  5416. // required.
  5417. this->GeneratorTarget->Makefile->AddCacheDefinition(
  5418. cmStrCat(this->GeneratorTarget->GetName(),
  5419. "_REQUIRES_VS_PACKAGE_RESTORE"),
  5420. "ON", "Value Computed by CMake", cmStateEnums::STATIC);
  5421. } else {
  5422. // If there are any dependencies that require package restore, inherit the
  5423. // cache variable.
  5424. cmGlobalGenerator::TargetDependSet const& unordered =
  5425. this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
  5426. using OrderedTargetDependSet =
  5427. cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
  5428. OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  5429. for (cmGeneratorTarget const* dt : depends) {
  5430. if (dt->IsDotNetSdkTarget() || dt->HasPackageReferences()) {
  5431. this->GeneratorTarget->Makefile->AddCacheDefinition(
  5432. cmStrCat(this->GeneratorTarget->GetName(),
  5433. "_REQUIRES_VS_PACKAGE_RESTORE"),
  5434. "ON", "Value Computed by CMake", cmStateEnums::STATIC);
  5435. }
  5436. }
  5437. }
  5438. }