cmVisualStudio10TargetGenerator.cxx 213 KB

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