cmVisualStudio10TargetGenerator.cxx 214 KB

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