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