cmVisualStudio10TargetGenerator.cxx 211 KB

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