cmVisualStudio10TargetGenerator.cxx 213 KB

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