1
0

cmVisualStudio10TargetGenerator.cxx 213 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953
  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 (haveUnityBuild && strcmp(tool, "CudaCompile") == 0 &&
  2471. si.Source->GetProperty("UNITY_SOURCE_FILE")) {
  2472. if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
  2473. exclude_configs = all_configs;
  2474. }
  2475. }
  2476. if (si.Kind == cmGeneratorTarget::SourceKindObjectSource ||
  2477. si.Kind == cmGeneratorTarget::SourceKindUnityBatched) {
  2478. this->OutputSourceSpecificFlags(e2, si.Source);
  2479. } else if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2480. this->GeneratorTarget->Makefile->IssueMessage(
  2481. MessageType::FATAL_ERROR,
  2482. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  2483. "\" has source file\n ", si.Source->GetFullPath(),
  2484. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  2485. "scheduled for compilation."));
  2486. }
  2487. if (si.Source->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  2488. e2.Element("PrecompiledHeader", "NotUsing");
  2489. }
  2490. if (!isCSharp && !exclude_configs.empty()) {
  2491. this->WriteExcludeFromBuild(e2, exclude_configs);
  2492. }
  2493. this->FinishWritingSource(e2, toolSettings);
  2494. } else if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2495. this->GeneratorTarget->Makefile->IssueMessage(
  2496. MessageType::FATAL_ERROR,
  2497. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  2498. "\" has source file\n ", si.Source->GetFullPath(),
  2499. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  2500. "scheduled for compilation."));
  2501. }
  2502. }
  2503. if (this->IsMissingFiles) {
  2504. this->WriteMissingFiles(e1);
  2505. }
  2506. }
  2507. void cmVisualStudio10TargetGenerator::FinishWritingSource(
  2508. Elem& e2, ConfigToSettings const& toolSettings)
  2509. {
  2510. std::vector<std::string> writtenSettings;
  2511. for (const auto& configSettings : toolSettings) {
  2512. for (const auto& setting : configSettings.second) {
  2513. if (std::find(writtenSettings.begin(), writtenSettings.end(),
  2514. setting.first) != writtenSettings.end()) {
  2515. continue;
  2516. }
  2517. if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
  2518. e2.Element(setting.first, setting.second);
  2519. writtenSettings.push_back(setting.first);
  2520. } else {
  2521. e2.WritePlatformConfigTag(setting.first,
  2522. cmStrCat("'$(Configuration)|$(Platform)'=='",
  2523. configSettings.first, '|',
  2524. this->Platform, '\''),
  2525. setting.second);
  2526. }
  2527. }
  2528. }
  2529. }
  2530. void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
  2531. Elem& e2, cmSourceFile const* source)
  2532. {
  2533. cmSourceFile const& sf = *source;
  2534. std::string objectName;
  2535. if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
  2536. objectName = this->GeneratorTarget->GetObjectName(&sf);
  2537. }
  2538. std::string flags;
  2539. bool configDependentFlags = false;
  2540. std::string options;
  2541. bool configDependentOptions = false;
  2542. std::string defines;
  2543. bool configDependentDefines = false;
  2544. std::string includes;
  2545. bool configDependentIncludes = false;
  2546. if (cmValue cflags = sf.GetProperty("COMPILE_FLAGS")) {
  2547. configDependentFlags =
  2548. cmGeneratorExpression::Find(*cflags) != std::string::npos;
  2549. flags += *cflags;
  2550. }
  2551. if (cmValue coptions = sf.GetProperty("COMPILE_OPTIONS")) {
  2552. configDependentOptions =
  2553. cmGeneratorExpression::Find(*coptions) != std::string::npos;
  2554. options += *coptions;
  2555. }
  2556. if (cmValue cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
  2557. configDependentDefines =
  2558. cmGeneratorExpression::Find(*cdefs) != std::string::npos;
  2559. defines += *cdefs;
  2560. }
  2561. if (cmValue cincludes = sf.GetProperty("INCLUDE_DIRECTORIES")) {
  2562. configDependentIncludes =
  2563. cmGeneratorExpression::Find(*cincludes) != std::string::npos;
  2564. includes += *cincludes;
  2565. }
  2566. // Force language if the file extension does not match.
  2567. // Note that MSVC treats the upper-case '.C' extension as C and not C++.
  2568. std::string const ext = sf.GetExtension();
  2569. std::string const extLang = ext == "C"_s
  2570. ? "C"
  2571. : this->GlobalGenerator->GetLanguageFromExtension(ext.c_str());
  2572. std::string lang = this->LocalGenerator->GetSourceFileLanguage(sf);
  2573. const char* compileAs = nullptr;
  2574. if (lang != extLang) {
  2575. if (lang == "CXX"_s) {
  2576. // force a C++ file type
  2577. compileAs = "CompileAsCpp";
  2578. } else if (lang == "C"_s) {
  2579. // force to c
  2580. compileAs = "CompileAsC";
  2581. }
  2582. }
  2583. bool noWinRT = this->TargetCompileAsWinRT && lang == "C"_s;
  2584. // for the first time we need a new line if there is something
  2585. // produced here.
  2586. if (!objectName.empty()) {
  2587. if (lang == "CUDA"_s) {
  2588. e2.Element("CompileOut", cmStrCat("$(IntDir)/", objectName));
  2589. } else {
  2590. e2.Element("ObjectFileName", cmStrCat("$(IntDir)/", objectName));
  2591. }
  2592. }
  2593. if (lang == "ASM_NASM"_s) {
  2594. if (cmValue objectDeps = sf.GetProperty("OBJECT_DEPENDS")) {
  2595. cmList depends{ *objectDeps };
  2596. for (auto& d : depends) {
  2597. ConvertToWindowsSlash(d);
  2598. }
  2599. e2.Element("AdditionalDependencies", depends.join(";"));
  2600. }
  2601. }
  2602. bool isCppModule = false;
  2603. for (std::string const& config : this->Configurations) {
  2604. this->GeneratorTarget->NeedCxxModuleSupport(lang, config);
  2605. std::string configUpper = cmSystemTools::UpperCase(config);
  2606. std::string configDefines = defines;
  2607. std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
  2608. if (cmValue ccdefs = sf.GetProperty(defPropName)) {
  2609. if (!configDefines.empty()) {
  2610. configDefines += ';';
  2611. }
  2612. configDependentDefines |=
  2613. cmGeneratorExpression::Find(*ccdefs) != std::string::npos;
  2614. configDefines += *ccdefs;
  2615. }
  2616. bool const shouldScanForModules = lang == "CXX"_s &&
  2617. this->GeneratorTarget->NeedDyndepForSource(lang, config, source);
  2618. auto const* fs =
  2619. this->GeneratorTarget->GetFileSetForSource(config, source);
  2620. const char* compileAsPerConfig = compileAs;
  2621. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2622. if (lang == "CXX"_s) {
  2623. if (fs->GetType() == "CXX_MODULES"_s) {
  2624. isCppModule = true;
  2625. if (shouldScanForModules &&
  2626. this->GlobalGenerator->IsScanDependenciesSupported()) {
  2627. // ScanSourceForModuleDependencies uses 'cl /scanDependencies' and
  2628. // can distinguish module interface units and internal partitions.
  2629. compileAsPerConfig = "CompileAsCpp";
  2630. } else {
  2631. compileAsPerConfig = "CompileAsCppModule";
  2632. }
  2633. } else {
  2634. compileAsPerConfig = "CompileAsHeaderUnit";
  2635. }
  2636. } else {
  2637. this->Makefile->IssueMessage(
  2638. MessageType::FATAL_ERROR,
  2639. cmStrCat(
  2640. "Target \"", this->GeneratorTarget->Target->GetName(),
  2641. "\" contains the source\n ", source->GetFullPath(),
  2642. "\nin a file set of type \"", fs->GetType(),
  2643. R"(" but the source is not classified as a "CXX" source.)"));
  2644. }
  2645. }
  2646. // We have pch state in the following situation:
  2647. // 1. We have SKIP_PRECOMPILE_HEADERS == true
  2648. // 2. We are creating the pre-compiled header
  2649. // 3. We are a different language than the linker language AND pch is
  2650. // enabled.
  2651. std::string const& linkLanguage =
  2652. this->GeneratorTarget->GetLinkerLanguage(config);
  2653. std::string const& pchSource =
  2654. this->GeneratorTarget->GetPchSource(config, lang);
  2655. const bool skipPCH =
  2656. pchSource.empty() || sf.GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS");
  2657. const bool makePCH = (sf.GetFullPath() == pchSource);
  2658. const bool useSharedPCH = !skipPCH && (lang == linkLanguage);
  2659. const bool useDifferentLangPCH = !skipPCH && (lang != linkLanguage);
  2660. const bool useNoPCH = skipPCH && (lang != linkLanguage) &&
  2661. !this->GeneratorTarget->GetPchHeader(config, linkLanguage).empty();
  2662. const bool needsPCHFlags =
  2663. (makePCH || useSharedPCH || useDifferentLangPCH || useNoPCH);
  2664. // if we have flags or defines for this config then
  2665. // use them
  2666. if (!flags.empty() || !options.empty() || !configDefines.empty() ||
  2667. !includes.empty() || compileAsPerConfig || noWinRT ||
  2668. !options.empty() || needsPCHFlags ||
  2669. (shouldScanForModules !=
  2670. this->ScanSourceForModuleDependencies[config])) {
  2671. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  2672. cmIDEFlagTable const* flagtable = nullptr;
  2673. const std::string& srclang = source->GetLanguage();
  2674. if (srclang == "C"_s || srclang == "CXX"_s) {
  2675. flagtable = gg->GetClFlagTable();
  2676. } else if (srclang == "ASM_MARMASM"_s &&
  2677. this->GlobalGenerator->IsMarmasmEnabled()) {
  2678. flagtable = gg->GetMarmasmFlagTable();
  2679. } else if (srclang == "ASM_MASM"_s &&
  2680. this->GlobalGenerator->IsMasmEnabled()) {
  2681. flagtable = gg->GetMasmFlagTable();
  2682. } else if (lang == "ASM_NASM"_s &&
  2683. this->GlobalGenerator->IsNasmEnabled()) {
  2684. flagtable = gg->GetNasmFlagTable();
  2685. } else if (srclang == "RC"_s) {
  2686. flagtable = gg->GetRcFlagTable();
  2687. } else if (srclang == "CSharp"_s) {
  2688. flagtable = gg->GetCSharpFlagTable();
  2689. }
  2690. cmGeneratorExpressionInterpreter genexInterpreter(
  2691. this->LocalGenerator, config, this->GeneratorTarget, lang);
  2692. cmVS10GeneratorOptions clOptions(
  2693. this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
  2694. flagtable, this);
  2695. if (compileAsPerConfig) {
  2696. clOptions.AddFlag("CompileAs", compileAsPerConfig);
  2697. }
  2698. if (shouldScanForModules !=
  2699. this->ScanSourceForModuleDependencies[config]) {
  2700. clOptions.AddFlag("ScanSourceForModuleDependencies",
  2701. shouldScanForModules ? "true" : "false");
  2702. }
  2703. if (noWinRT) {
  2704. clOptions.AddFlag("CompileAsWinRT", "false");
  2705. }
  2706. if (configDependentFlags) {
  2707. clOptions.Parse(genexInterpreter.Evaluate(flags, "COMPILE_FLAGS"));
  2708. } else {
  2709. clOptions.Parse(flags);
  2710. }
  2711. if (needsPCHFlags) {
  2712. // Add precompile headers compile options.
  2713. if (makePCH) {
  2714. clOptions.AddFlag("PrecompiledHeader", "Create");
  2715. std::string pchHeader =
  2716. this->GeneratorTarget->GetPchHeader(config, lang);
  2717. clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
  2718. std::string pchFile =
  2719. this->GeneratorTarget->GetPchFile(config, lang);
  2720. clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
  2721. clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
  2722. } else if (useNoPCH) {
  2723. clOptions.AddFlag("PrecompiledHeader", "NotUsing");
  2724. } else if (useSharedPCH) {
  2725. std::string pchHeader =
  2726. this->GeneratorTarget->GetPchHeader(config, lang);
  2727. clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
  2728. } else if (useDifferentLangPCH) {
  2729. clOptions.AddFlag("PrecompiledHeader", "Use");
  2730. std::string pchHeader =
  2731. this->GeneratorTarget->GetPchHeader(config, lang);
  2732. clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
  2733. std::string pchFile =
  2734. this->GeneratorTarget->GetPchFile(config, lang);
  2735. clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
  2736. clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
  2737. }
  2738. }
  2739. if (!options.empty()) {
  2740. std::string expandedOptions;
  2741. if (configDependentOptions) {
  2742. this->LocalGenerator->AppendCompileOptions(
  2743. expandedOptions,
  2744. genexInterpreter.Evaluate(options, "COMPILE_OPTIONS"));
  2745. } else {
  2746. this->LocalGenerator->AppendCompileOptions(expandedOptions, options);
  2747. }
  2748. clOptions.Parse(expandedOptions);
  2749. }
  2750. if (clOptions.HasFlag("DisableSpecificWarnings")) {
  2751. clOptions.AppendFlag("DisableSpecificWarnings",
  2752. "%(DisableSpecificWarnings)");
  2753. }
  2754. if (clOptions.HasFlag("ForcedIncludeFiles")) {
  2755. clOptions.AppendFlag("ForcedIncludeFiles", "%(ForcedIncludeFiles)");
  2756. }
  2757. if (configDependentDefines) {
  2758. clOptions.AddDefines(
  2759. genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS"));
  2760. } else {
  2761. clOptions.AddDefines(configDefines);
  2762. }
  2763. std::vector<std::string> includeList;
  2764. if (configDependentIncludes) {
  2765. this->LocalGenerator->AppendIncludeDirectories(
  2766. includeList,
  2767. genexInterpreter.Evaluate(includes, "INCLUDE_DIRECTORIES"), *source);
  2768. } else {
  2769. this->LocalGenerator->AppendIncludeDirectories(includeList, includes,
  2770. *source);
  2771. }
  2772. clOptions.AddIncludes(includeList);
  2773. clOptions.SetConfiguration(config);
  2774. OptionsHelper oh(clOptions, e2);
  2775. oh.PrependInheritedString("AdditionalOptions");
  2776. oh.OutputAdditionalIncludeDirectories(lang);
  2777. oh.OutputFlagMap();
  2778. oh.OutputPreprocessorDefinitions(lang);
  2779. }
  2780. }
  2781. if (isCppModule && !objectName.empty()) {
  2782. std::string baseName = cmStrCat("$(IntDir)/", objectName);
  2783. cmStripSuffixIfExists(baseName, ".obj");
  2784. e2.Element("ModuleOutputFile", cmStrCat(baseName, ".ifc"));
  2785. e2.Element("ModuleDependenciesFile", cmStrCat(baseName, ".module.json"));
  2786. }
  2787. if (this->IsXamlSource(source->GetFullPath())) {
  2788. const std::string& fileName = source->GetFullPath();
  2789. e2.Element("DependentUpon",
  2790. fileName.substr(0, fileName.find_last_of('.')));
  2791. }
  2792. if (this->ProjectType == VsProjectType::csproj) {
  2793. using CsPropMap = std::map<std::string, std::string>;
  2794. CsPropMap sourceFileTags;
  2795. this->GetCSharpSourceProperties(&sf, sourceFileTags);
  2796. // write source file specific tags
  2797. if (!sourceFileTags.empty()) {
  2798. this->WriteCSharpSourceProperties(e2, sourceFileTags);
  2799. }
  2800. }
  2801. }
  2802. void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild(
  2803. Elem& e2, std::vector<size_t> const& exclude_configs)
  2804. {
  2805. for (size_t ci : exclude_configs) {
  2806. e2.WritePlatformConfigTag("ExcludedFromBuild",
  2807. cmStrCat("'$(Configuration)|$(Platform)'=='",
  2808. this->Configurations[ci], '|',
  2809. this->Platform, '\''),
  2810. "true");
  2811. }
  2812. }
  2813. void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions(
  2814. Elem& e0)
  2815. {
  2816. cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
  2817. if (ttype > cmStateEnums::INTERFACE_LIBRARY) {
  2818. return;
  2819. }
  2820. if (this->ProjectType == VsProjectType::csproj) {
  2821. return;
  2822. }
  2823. Elem e1(e0, "PropertyGroup");
  2824. e1.Element("_ProjectFileVersion", "10.0.20506.1");
  2825. for (std::string const& config : this->Configurations) {
  2826. const std::string cond = this->CalcCondition(config);
  2827. if (ttype >= cmStateEnums::UTILITY) {
  2828. e1.WritePlatformConfigTag(
  2829. "IntDir", cond, R"($(Platform)\$(Configuration)\$(ProjectName)\)");
  2830. } else {
  2831. if (ttype == cmStateEnums::SHARED_LIBRARY ||
  2832. ttype == cmStateEnums::MODULE_LIBRARY ||
  2833. ttype == cmStateEnums::EXECUTABLE) {
  2834. auto linker = this->GeneratorTarget->GetLinkerTool(config);
  2835. if (!linker.empty()) {
  2836. ConvertToWindowsSlash(linker);
  2837. e1.WritePlatformConfigTag("LinkToolExe", cond, linker);
  2838. }
  2839. }
  2840. std::string intermediateDir = cmStrCat(
  2841. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/',
  2842. config, '/');
  2843. std::string outDir;
  2844. std::string targetNameFull;
  2845. if (ttype == cmStateEnums::OBJECT_LIBRARY) {
  2846. outDir = intermediateDir;
  2847. targetNameFull = cmStrCat(this->GeneratorTarget->GetName(), ".lib");
  2848. } else {
  2849. outDir = cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
  2850. targetNameFull = this->GeneratorTarget->GetFullName(config);
  2851. }
  2852. ConvertToWindowsSlash(intermediateDir);
  2853. ConvertToWindowsSlash(outDir);
  2854. e1.WritePlatformConfigTag("OutDir", cond, outDir);
  2855. e1.WritePlatformConfigTag("IntDir", cond, intermediateDir);
  2856. if (cmValue sdkExecutableDirectories = this->Makefile->GetDefinition(
  2857. "CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES")) {
  2858. e1.WritePlatformConfigTag("ExecutablePath", cond,
  2859. *sdkExecutableDirectories);
  2860. }
  2861. if (cmValue sdkIncludeDirectories = this->Makefile->GetDefinition(
  2862. "CMAKE_VS_SDK_INCLUDE_DIRECTORIES")) {
  2863. e1.WritePlatformConfigTag("IncludePath", cond, *sdkIncludeDirectories);
  2864. }
  2865. if (cmValue sdkReferenceDirectories = this->Makefile->GetDefinition(
  2866. "CMAKE_VS_SDK_REFERENCE_DIRECTORIES")) {
  2867. e1.WritePlatformConfigTag("ReferencePath", cond,
  2868. *sdkReferenceDirectories);
  2869. }
  2870. if (cmValue sdkLibraryDirectories = this->Makefile->GetDefinition(
  2871. "CMAKE_VS_SDK_LIBRARY_DIRECTORIES")) {
  2872. e1.WritePlatformConfigTag("LibraryPath", cond, *sdkLibraryDirectories);
  2873. }
  2874. if (cmValue sdkLibraryWDirectories = this->Makefile->GetDefinition(
  2875. "CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES")) {
  2876. e1.WritePlatformConfigTag("LibraryWPath", cond,
  2877. *sdkLibraryWDirectories);
  2878. }
  2879. if (cmValue sdkSourceDirectories =
  2880. this->Makefile->GetDefinition("CMAKE_VS_SDK_SOURCE_DIRECTORIES")) {
  2881. e1.WritePlatformConfigTag("SourcePath", cond, *sdkSourceDirectories);
  2882. }
  2883. if (cmValue sdkExcludeDirectories = this->Makefile->GetDefinition(
  2884. "CMAKE_VS_SDK_EXCLUDE_DIRECTORIES")) {
  2885. e1.WritePlatformConfigTag("ExcludePath", cond, *sdkExcludeDirectories);
  2886. }
  2887. std::string name =
  2888. cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
  2889. e1.WritePlatformConfigTag("TargetName", cond, name);
  2890. std::string ext =
  2891. cmSystemTools::GetFilenameLastExtension(targetNameFull);
  2892. if (ext.empty()) {
  2893. // An empty TargetExt causes a default extension to be used.
  2894. // A single "." appears to be treated as an empty extension.
  2895. ext = ".";
  2896. }
  2897. e1.WritePlatformConfigTag("TargetExt", cond, ext);
  2898. this->OutputLinkIncremental(e1, config);
  2899. }
  2900. if (ttype <= cmStateEnums::UTILITY) {
  2901. if (cmValue workingDir = this->GeneratorTarget->GetProperty(
  2902. "VS_DEBUGGER_WORKING_DIRECTORY")) {
  2903. std::string genWorkingDir = cmGeneratorExpression::Evaluate(
  2904. *workingDir, this->LocalGenerator, config);
  2905. e1.WritePlatformConfigTag("LocalDebuggerWorkingDirectory", cond,
  2906. genWorkingDir);
  2907. }
  2908. if (cmValue environment =
  2909. this->GeneratorTarget->GetProperty("VS_DEBUGGER_ENVIRONMENT")) {
  2910. std::string genEnvironment = cmGeneratorExpression::Evaluate(
  2911. *environment, this->LocalGenerator, config);
  2912. e1.WritePlatformConfigTag("LocalDebuggerEnvironment", cond,
  2913. genEnvironment);
  2914. }
  2915. if (cmValue debuggerCommand =
  2916. this->GeneratorTarget->GetProperty("VS_DEBUGGER_COMMAND")) {
  2917. std::string genDebuggerCommand = cmGeneratorExpression::Evaluate(
  2918. *debuggerCommand, this->LocalGenerator, config);
  2919. e1.WritePlatformConfigTag("LocalDebuggerCommand", cond,
  2920. genDebuggerCommand);
  2921. }
  2922. if (cmValue commandArguments = this->GeneratorTarget->GetProperty(
  2923. "VS_DEBUGGER_COMMAND_ARGUMENTS")) {
  2924. std::string genCommandArguments = cmGeneratorExpression::Evaluate(
  2925. *commandArguments, this->LocalGenerator, config);
  2926. e1.WritePlatformConfigTag("LocalDebuggerCommandArguments", cond,
  2927. genCommandArguments);
  2928. }
  2929. }
  2930. }
  2931. }
  2932. void cmVisualStudio10TargetGenerator::WritePublicProjectContentOptions(
  2933. Elem& e0)
  2934. {
  2935. cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
  2936. if (ttype != cmStateEnums::SHARED_LIBRARY) {
  2937. return;
  2938. }
  2939. if (this->ProjectType != VsProjectType::vcxproj) {
  2940. return;
  2941. }
  2942. Elem e1(e0, "PropertyGroup");
  2943. for (std::string const& config : this->Configurations) {
  2944. if (this->GeneratorTarget->HaveCxx20ModuleSources() &&
  2945. this->GeneratorTarget->HaveCxxModuleSupport(config) ==
  2946. cmGeneratorTarget::Cxx20SupportLevel::Supported) {
  2947. const std::string cond = this->CalcCondition(config);
  2948. // For DLL projects, we export all BMIs for now
  2949. e1.WritePlatformConfigTag("AllProjectBMIsArePublic", cond, "true");
  2950. }
  2951. }
  2952. }
  2953. void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
  2954. Elem& e1, std::string const& configName)
  2955. {
  2956. if (!this->MSTools) {
  2957. return;
  2958. }
  2959. if (this->ProjectType == VsProjectType::csproj) {
  2960. return;
  2961. }
  2962. // static libraries and things greater than modules do not need
  2963. // to set this option
  2964. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2965. this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
  2966. return;
  2967. }
  2968. Options& linkOptions = *(this->LinkOptions[configName]);
  2969. const std::string cond = this->CalcCondition(configName);
  2970. if (this->IPOEnabledConfigurations.count(configName) > 0) {
  2971. // Suppress LinkIncremental in favor of WholeProgramOptimization.
  2972. e1.WritePlatformConfigTag("LinkIncremental", cond, "");
  2973. } else {
  2974. const char* incremental = linkOptions.GetFlag("LinkIncremental");
  2975. e1.WritePlatformConfigTag("LinkIncremental", cond,
  2976. (incremental ? incremental : "true"));
  2977. }
  2978. linkOptions.RemoveFlag("LinkIncremental");
  2979. const char* manifest = linkOptions.GetFlag("GenerateManifest");
  2980. e1.WritePlatformConfigTag("GenerateManifest", cond,
  2981. (manifest ? manifest : "true"));
  2982. linkOptions.RemoveFlag("GenerateManifest");
  2983. // Some link options belong here. Use them now and remove them so that
  2984. // WriteLinkOptions does not use them.
  2985. static const std::vector<std::string> flags{ "LinkDelaySign",
  2986. "LinkKeyFile" };
  2987. for (const std::string& flag : flags) {
  2988. if (const char* value = linkOptions.GetFlag(flag)) {
  2989. e1.WritePlatformConfigTag(flag, cond, value);
  2990. linkOptions.RemoveFlag(flag);
  2991. }
  2992. }
  2993. }
  2994. std::vector<std::string> cmVisualStudio10TargetGenerator::GetIncludes(
  2995. std::string const& config, std::string const& lang) const
  2996. {
  2997. std::vector<std::string> includes;
  2998. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  2999. lang, config);
  3000. for (std::string& i : includes) {
  3001. ConvertToWindowsSlash(i);
  3002. }
  3003. return includes;
  3004. }
  3005. std::string cmVisualStudio10TargetGenerator::GetTargetOutputName() const
  3006. {
  3007. std::string config;
  3008. if (!this->Configurations.empty()) {
  3009. config = this->Configurations[0];
  3010. }
  3011. const auto& nameComponents =
  3012. this->GeneratorTarget->GetFullNameComponents(config);
  3013. return cmStrCat(nameComponents.prefix, nameComponents.base);
  3014. }
  3015. bool cmVisualStudio10TargetGenerator::ComputeClOptions()
  3016. {
  3017. return std::all_of(
  3018. this->Configurations.begin(), this->Configurations.end(),
  3019. [this](std::string const& c) { return this->ComputeClOptions(c); });
  3020. }
  3021. bool cmVisualStudio10TargetGenerator::ComputeClOptions(
  3022. std::string const& configName)
  3023. {
  3024. // much of this was copied from here:
  3025. // copied from cmLocalVisualStudio7Generator.cxx 805
  3026. // TODO: Integrate code below with cmLocalVisualStudio7Generator.
  3027. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3028. std::unique_ptr<Options> pOptions;
  3029. switch (this->ProjectType) {
  3030. case VsProjectType::vcxproj:
  3031. pOptions = cm::make_unique<Options>(
  3032. this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
  3033. break;
  3034. case VsProjectType::csproj:
  3035. pOptions =
  3036. cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
  3037. gg->GetCSharpFlagTable());
  3038. break;
  3039. default:
  3040. break;
  3041. }
  3042. Options& clOptions = *pOptions;
  3043. std::string flags;
  3044. const std::string& linkLanguage =
  3045. this->GeneratorTarget->GetLinkerLanguage(configName);
  3046. if (linkLanguage.empty()) {
  3047. cmSystemTools::Error(cmStrCat(
  3048. "CMake can not determine linker language for target: ", this->Name));
  3049. return false;
  3050. }
  3051. // Choose a language whose flags to use for ClCompile.
  3052. static const char* clLangs[] = { "CXX", "C", "Fortran" };
  3053. std::string langForClCompile;
  3054. if (this->ProjectType == VsProjectType::csproj) {
  3055. langForClCompile = "CSharp";
  3056. } else if (cm::contains(clLangs, linkLanguage)) {
  3057. langForClCompile = linkLanguage;
  3058. } else {
  3059. std::set<std::string> languages;
  3060. this->GeneratorTarget->GetLanguages(languages, configName);
  3061. for (const char* l : clLangs) {
  3062. if (languages.count(l)) {
  3063. langForClCompile = l;
  3064. break;
  3065. }
  3066. }
  3067. }
  3068. this->LangForClCompile = langForClCompile;
  3069. if (!langForClCompile.empty()) {
  3070. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3071. cmBuildStep::Compile,
  3072. langForClCompile, configName);
  3073. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3074. langForClCompile, configName);
  3075. }
  3076. // Put the IPO enabled configurations into a set.
  3077. if (this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName)) {
  3078. this->IPOEnabledConfigurations.insert(configName);
  3079. }
  3080. // Check if ASan is enabled.
  3081. if (flags.find("/fsanitize=address") != std::string::npos ||
  3082. flags.find("-fsanitize=address") != std::string::npos) {
  3083. this->ASanEnabledConfigurations.insert(configName);
  3084. }
  3085. // Check if (lib)Fuzzer is enabled.
  3086. if (flags.find("/fsanitize=fuzzer") != std::string::npos ||
  3087. flags.find("-fsanitize=fuzzer") != std::string::npos) {
  3088. this->FuzzerEnabledConfigurations.insert(configName);
  3089. }
  3090. // Precompile Headers
  3091. std::string pchHeader =
  3092. this->GeneratorTarget->GetPchHeader(configName, linkLanguage);
  3093. if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
  3094. pchHeader.empty()) {
  3095. clOptions.AddFlag("PrecompiledHeader", "NotUsing");
  3096. } else if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
  3097. !pchHeader.empty()) {
  3098. clOptions.AddFlag("PrecompiledHeader", "Use");
  3099. clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
  3100. std::string pchFile =
  3101. this->GeneratorTarget->GetPchFile(configName, linkLanguage);
  3102. clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
  3103. }
  3104. // Get preprocessor definitions for this directory.
  3105. std::string defineFlags = this->Makefile->GetDefineFlags();
  3106. if (this->MSTools) {
  3107. if (this->ProjectType == VsProjectType::vcxproj) {
  3108. clOptions.FixExceptionHandlingDefault();
  3109. if (this->GlobalGenerator->GetVersion() >=
  3110. cmGlobalVisualStudioGenerator::VSVersion::VS15) {
  3111. // Toolsets that come with VS 2017 may now enable UseFullPaths
  3112. // by default and there is no negative /FC option that projects
  3113. // can use to switch it back. Older toolsets disable this by
  3114. // default anyway so this will not hurt them. If the project
  3115. // is using an explicit /FC option then parsing flags will
  3116. // replace this setting with "true" below.
  3117. clOptions.AddFlag("UseFullPaths", "false");
  3118. }
  3119. clOptions.AddFlag("AssemblerListingLocation", "$(IntDir)");
  3120. }
  3121. }
  3122. // check for managed C++ assembly compiler flag. This overrides any
  3123. // /clr* compiler flags which may be defined in the flags variable(s).
  3124. if (this->ProjectType != VsProjectType::csproj) {
  3125. // Warn if /clr was added manually. This should not be done
  3126. // anymore, because cmGeneratorTarget may not be aware that the
  3127. // target uses C++/CLI.
  3128. if (flags.find("/clr") != std::string::npos ||
  3129. flags.find("-clr") != std::string::npos ||
  3130. defineFlags.find("/clr") != std::string::npos ||
  3131. defineFlags.find("-clr") != std::string::npos) {
  3132. if (configName == this->Configurations[0]) {
  3133. std::string message =
  3134. cmStrCat("For the target \"", this->GeneratorTarget->GetName(),
  3135. "\" the /clr compiler flag was added manually. ",
  3136. "Set usage of C++/CLI by setting COMMON_LANGUAGE_RUNTIME "
  3137. "target property.");
  3138. this->Makefile->IssueMessage(MessageType::WARNING, message);
  3139. }
  3140. }
  3141. if (cmValue clr =
  3142. this->GeneratorTarget->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  3143. std::string clrString = *clr;
  3144. if (!clrString.empty()) {
  3145. clrString = cmStrCat(':', clrString);
  3146. }
  3147. flags += cmStrCat(" /clr", clrString);
  3148. }
  3149. }
  3150. // Get includes for this target
  3151. if (!this->LangForClCompile.empty()) {
  3152. auto includeList = this->GetIncludes(configName, this->LangForClCompile);
  3153. auto sysIncludeFlag = this->Makefile->GetDefinition(
  3154. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile));
  3155. if (sysIncludeFlag) {
  3156. bool gotOneSys = false;
  3157. for (auto i : includeList) {
  3158. cmSystemTools::ConvertToUnixSlashes(i);
  3159. if (this->GeneratorTarget->IsSystemIncludeDirectory(
  3160. i, configName, this->LangForClCompile)) {
  3161. auto flag = cmTrimWhitespace(*sysIncludeFlag);
  3162. if (this->MSTools) {
  3163. cmSystemTools::ReplaceString(flag, "-external:I", "/external:I");
  3164. }
  3165. clOptions.AppendFlagString("AdditionalOptions",
  3166. cmStrCat(flag, " \"", i, '"'));
  3167. gotOneSys = true;
  3168. } else {
  3169. clOptions.AddInclude(i);
  3170. }
  3171. }
  3172. if (gotOneSys) {
  3173. if (auto sysIncludeFlagWarning = this->Makefile->GetDefinition(
  3174. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile,
  3175. "_WARNING"))) {
  3176. flags = cmStrCat(flags, ' ', *sysIncludeFlagWarning);
  3177. }
  3178. }
  3179. } else {
  3180. clOptions.AddIncludes(includeList);
  3181. }
  3182. }
  3183. clOptions.Parse(flags);
  3184. clOptions.Parse(defineFlags);
  3185. std::vector<std::string> targetDefines;
  3186. switch (this->ProjectType) {
  3187. case VsProjectType::vcxproj:
  3188. if (!langForClCompile.empty()) {
  3189. this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
  3190. langForClCompile);
  3191. }
  3192. break;
  3193. case VsProjectType::csproj:
  3194. this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
  3195. "CSharp");
  3196. cm::erase_if(targetDefines, [](std::string const& def) {
  3197. return def.find('=') != std::string::npos;
  3198. });
  3199. break;
  3200. default:
  3201. break;
  3202. }
  3203. clOptions.AddDefines(targetDefines);
  3204. if (this->ProjectType == VsProjectType::csproj) {
  3205. clOptions.AppendFlag("DefineConstants", targetDefines);
  3206. }
  3207. if (this->MSTools) {
  3208. clOptions.SetVerboseMakefile(
  3209. this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
  3210. }
  3211. // Add C-specific flags expressible in a ClCompile meant for C++.
  3212. if (langForClCompile == "CXX"_s) {
  3213. std::set<std::string> languages;
  3214. this->GeneratorTarget->GetLanguages(languages, configName);
  3215. if (languages.count("C")) {
  3216. std::string flagsC;
  3217. this->LocalGenerator->AddLanguageFlags(
  3218. flagsC, this->GeneratorTarget, cmBuildStep::Compile, "C", configName);
  3219. this->LocalGenerator->AddCompileOptions(flagsC, this->GeneratorTarget,
  3220. "C", configName);
  3221. Options optC(this->LocalGenerator, Options::Compiler,
  3222. gg->GetClFlagTable());
  3223. optC.Parse(flagsC);
  3224. if (const char* stdC = optC.GetFlag("LanguageStandard_C")) {
  3225. clOptions.AddFlag("LanguageStandard_C", stdC);
  3226. }
  3227. }
  3228. }
  3229. // Add a definition for the configuration name.
  3230. std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
  3231. clOptions.AddDefine(configDefine);
  3232. if (const std::string* exportMacro =
  3233. this->GeneratorTarget->GetExportMacro()) {
  3234. clOptions.AddDefine(*exportMacro);
  3235. }
  3236. if (this->MSTools) {
  3237. // If we have the VS_WINRT_COMPONENT set then force Compile as WinRT
  3238. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
  3239. clOptions.AddFlag("CompileAsWinRT", "true");
  3240. // For WinRT components, add the _WINRT_DLL define to produce a lib
  3241. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3242. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3243. clOptions.AddDefine("_WINRT_DLL");
  3244. }
  3245. } else if (this->GlobalGenerator->TargetsWindowsStore() ||
  3246. this->GlobalGenerator->TargetsWindowsPhone() ||
  3247. this->Makefile->IsOn("CMAKE_VS_WINRT_BY_DEFAULT")) {
  3248. if (!clOptions.IsWinRt()) {
  3249. clOptions.AddFlag("CompileAsWinRT", "false");
  3250. }
  3251. }
  3252. if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) {
  3253. if (cmIsOn(winRT)) {
  3254. this->TargetCompileAsWinRT = true;
  3255. }
  3256. }
  3257. }
  3258. if (this->ProjectType != VsProjectType::csproj &&
  3259. (clOptions.IsManaged() || clOptions.HasFlag("CLRSupport"))) {
  3260. this->Managed = true;
  3261. std::string managedType = clOptions.HasFlag("CompileAsManaged")
  3262. ? clOptions.GetFlag("CompileAsManaged")
  3263. : "Mixed";
  3264. if (managedType == "Safe"_s || managedType == "Pure"_s) {
  3265. // force empty calling convention if safe clr is used
  3266. clOptions.AddFlag("CallingConvention", "");
  3267. }
  3268. // The default values of these flags are incompatible to
  3269. // managed assemblies. We have to force valid values if
  3270. // the target is a managed C++ target.
  3271. clOptions.AddFlag("ExceptionHandling", "Async");
  3272. clOptions.AddFlag("BasicRuntimeChecks", "Default");
  3273. }
  3274. if (this->ProjectType == VsProjectType::csproj) {
  3275. // /nowin32manifest overrides /win32manifest: parameter
  3276. if (clOptions.HasFlag("NoWin32Manifest")) {
  3277. clOptions.RemoveFlag("ApplicationManifest");
  3278. }
  3279. }
  3280. if (const char* s = clOptions.GetFlag("SpectreMitigation")) {
  3281. this->SpectreMitigation[configName] = s;
  3282. clOptions.RemoveFlag("SpectreMitigation");
  3283. }
  3284. // Remove any target-wide -TC or -TP flag added by the project.
  3285. // Such flags are unnecessary and break our model of language selection.
  3286. if (langForClCompile == "C"_s || langForClCompile == "CXX"_s) {
  3287. clOptions.RemoveFlag("CompileAs");
  3288. }
  3289. if (this->ProjectType == VsProjectType::vcxproj && this->MSTools) {
  3290. // Suppress Microsoft.Cl.Common.props default settings for which the
  3291. // project specifies no flags. Do not let UseDebugLibraries affect them.
  3292. if (!clOptions.HasFlag("BasicRuntimeChecks")) {
  3293. clOptions.AddFlag("BasicRuntimeChecks", "Default");
  3294. }
  3295. if (!clOptions.HasFlag("MinimalRebuild")) {
  3296. clOptions.AddFlag("MinimalRebuild", "");
  3297. }
  3298. if (!clOptions.HasFlag("Optimization")) {
  3299. clOptions.AddFlag("Optimization", "");
  3300. }
  3301. if (!clOptions.HasFlag("RuntimeLibrary")) {
  3302. clOptions.AddFlag("RuntimeLibrary", "");
  3303. }
  3304. if (!clOptions.HasFlag("SupportJustMyCode")) {
  3305. clOptions.AddFlag("SupportJustMyCode", "");
  3306. }
  3307. }
  3308. this->ClOptions[configName] = std::move(pOptions);
  3309. return true;
  3310. }
  3311. void cmVisualStudio10TargetGenerator::WriteClOptions(
  3312. Elem& e1, std::string const& configName)
  3313. {
  3314. Options& clOptions = *(this->ClOptions[configName]);
  3315. if (this->ProjectType == VsProjectType::csproj) {
  3316. return;
  3317. }
  3318. Elem e2(e1, "ClCompile");
  3319. OptionsHelper oh(clOptions, e2);
  3320. oh.PrependInheritedString("AdditionalOptions");
  3321. oh.OutputAdditionalIncludeDirectories(this->LangForClCompile);
  3322. oh.OutputFlagMap();
  3323. oh.OutputPreprocessorDefinitions(this->LangForClCompile);
  3324. if (this->NsightTegra) {
  3325. if (cmValue processMax =
  3326. this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) {
  3327. e2.Element("ProcessMax", *processMax);
  3328. }
  3329. }
  3330. if (this->Android) {
  3331. e2.Element("ObjectFileName", "$(IntDir)%(filename).o");
  3332. } else if (this->MSTools) {
  3333. cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
  3334. const char* toolset = this->GlobalGenerator->GetPlatformToolset();
  3335. cmValue noCompileBatching =
  3336. this->GeneratorTarget->GetProperty("VS_NO_COMPILE_BATCHING");
  3337. if (noCompileBatching.IsOn() || (toolset && clangToolset.find(toolset))) {
  3338. e2.Element("ObjectFileName", "$(IntDir)%(filename).obj");
  3339. } else {
  3340. e2.Element("ObjectFileName", "$(IntDir)");
  3341. }
  3342. // If not in debug mode, write the DebugInformationFormat field
  3343. // without value so PDBs don't get generated uselessly. Each tag
  3344. // goes on its own line because Visual Studio corrects it this
  3345. // way when saving the project after CMake generates it.
  3346. if (!clOptions.UsingDebugInfo()) {
  3347. Elem e3(e2, "DebugInformationFormat");
  3348. e3.SetHasElements();
  3349. }
  3350. // Specify the compiler program database file if configured.
  3351. std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
  3352. if (!pdb.empty()) {
  3353. if (this->GlobalGenerator->IsCudaEnabled()) {
  3354. // CUDA does not quote paths with spaces correctly when forwarding
  3355. // this to the host compiler. Use a relative path to avoid spaces.
  3356. // FIXME: We can likely do this even when CUDA is not involved,
  3357. // but for now we will make a minimal change.
  3358. pdb = this->ConvertPath(pdb, true);
  3359. }
  3360. ConvertToWindowsSlash(pdb);
  3361. e2.Element("ProgramDataBaseFileName", pdb);
  3362. }
  3363. // add AdditionalUsingDirectories
  3364. if (this->AdditionalUsingDirectories.count(configName) > 0) {
  3365. std::string dirs;
  3366. for (auto const& u : this->AdditionalUsingDirectories[configName]) {
  3367. if (!dirs.empty()) {
  3368. dirs.append(";");
  3369. }
  3370. dirs.append(u);
  3371. }
  3372. e2.Element("AdditionalUsingDirectories", dirs);
  3373. }
  3374. }
  3375. e2.Element("ScanSourceForModuleDependencies",
  3376. this->ScanSourceForModuleDependencies[configName] ? "true"
  3377. : "false");
  3378. }
  3379. bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
  3380. {
  3381. return std::all_of(
  3382. this->Configurations.begin(), this->Configurations.end(),
  3383. [this](std::string const& c) { return this->ComputeRcOptions(c); });
  3384. }
  3385. bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
  3386. std::string const& configName)
  3387. {
  3388. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3389. auto pOptions = cm::make_unique<Options>(
  3390. this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
  3391. Options& rcOptions = *pOptions;
  3392. std::string CONFIG = cmSystemTools::UpperCase(configName);
  3393. std::string rcConfigFlagsVar = cmStrCat("CMAKE_RC_FLAGS_", CONFIG);
  3394. std::string flags =
  3395. cmStrCat(this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS"), ' ',
  3396. this->Makefile->GetSafeDefinition(rcConfigFlagsVar));
  3397. rcOptions.Parse(flags);
  3398. // For historical reasons, add the C preprocessor defines to RC.
  3399. Options& clOptions = *(this->ClOptions[configName]);
  3400. rcOptions.AddDefines(clOptions.GetDefines());
  3401. // Get includes for this target
  3402. rcOptions.AddIncludes(this->GetIncludes(configName, "RC"));
  3403. this->RcOptions[configName] = std::move(pOptions);
  3404. return true;
  3405. }
  3406. void cmVisualStudio10TargetGenerator::WriteRCOptions(
  3407. Elem& e1, std::string const& configName)
  3408. {
  3409. if (!this->MSTools) {
  3410. return;
  3411. }
  3412. Elem e2(e1, "ResourceCompile");
  3413. OptionsHelper rcOptions(*(this->RcOptions[configName]), e2);
  3414. rcOptions.OutputPreprocessorDefinitions("RC");
  3415. rcOptions.OutputAdditionalIncludeDirectories("RC");
  3416. rcOptions.PrependInheritedString("AdditionalOptions");
  3417. rcOptions.OutputFlagMap();
  3418. }
  3419. bool cmVisualStudio10TargetGenerator::ComputeCudaOptions()
  3420. {
  3421. if (!this->GlobalGenerator->IsCudaEnabled()) {
  3422. return true;
  3423. }
  3424. return std::all_of(this->Configurations.begin(), this->Configurations.end(),
  3425. [this](std::string const& c) {
  3426. return !this->GeneratorTarget->IsLanguageUsed("CUDA",
  3427. c) ||
  3428. this->ComputeCudaOptions(c);
  3429. });
  3430. }
  3431. bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
  3432. std::string const& configName)
  3433. {
  3434. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3435. auto pOptions = cm::make_unique<Options>(
  3436. this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
  3437. Options& cudaOptions = *pOptions;
  3438. auto cudaVersion = this->GlobalGenerator->GetPlatformToolsetCudaString();
  3439. // Get compile flags for CUDA in this directory.
  3440. std::string flags;
  3441. this->LocalGenerator->AddLanguageFlags(
  3442. flags, this->GeneratorTarget, cmBuildStep::Compile, "CUDA", configName);
  3443. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, "CUDA",
  3444. configName);
  3445. // Get preprocessor definitions for this directory.
  3446. std::string defineFlags = this->Makefile->GetDefineFlags();
  3447. cudaOptions.Parse(flags);
  3448. cudaOptions.Parse(defineFlags);
  3449. cudaOptions.ParseFinish();
  3450. // If we haven't explicitly enabled GPU debug information
  3451. // explicitly disable it
  3452. if (!cudaOptions.HasFlag("GPUDebugInfo")) {
  3453. cudaOptions.AddFlag("GPUDebugInfo", "false");
  3454. }
  3455. // The extension on object libraries the CUDA gives isn't
  3456. // consistent with how MSVC generates object libraries for C+, so set
  3457. // the default to not have any extension
  3458. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).obj");
  3459. if (this->GeneratorTarget->GetPropertyAsBool("CUDA_SEPARABLE_COMPILATION")) {
  3460. cudaOptions.AddFlag("GenerateRelocatableDeviceCode", "true");
  3461. }
  3462. bool notPtxLike = true;
  3463. if (this->GeneratorTarget->GetPropertyAsBool("CUDA_PTX_COMPILATION")) {
  3464. cudaOptions.AddFlag("NvccCompilation", "ptx");
  3465. // We drop the %(Extension) component as CMake expects all PTX files
  3466. // to not have the source file extension at all
  3467. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
  3468. notPtxLike = false;
  3469. if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  3470. cudaVersion, "9.0") &&
  3471. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, cudaVersion,
  3472. "11.5")) {
  3473. // The DriverApi flag before 11.5 ( verified back to 9.0 ) which controls
  3474. // PTX compilation doesn't propagate user defines causing
  3475. // target_compile_definitions to behave differently for VS +
  3476. // PTX compared to other generators so we patch the rules
  3477. // to normalize behavior
  3478. cudaOptions.AddFlag("DriverApiCommandLineTemplate",
  3479. "%(BaseCommandLineTemplate) [CompileOut] [FastMath] "
  3480. "[Defines] \"%(FullPath)\"");
  3481. }
  3482. } else if (this->GeneratorTarget->GetPropertyAsBool(
  3483. "CUDA_CUBIN_COMPILATION")) {
  3484. cudaOptions.AddFlag("NvccCompilation", "cubin");
  3485. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).cubin");
  3486. notPtxLike = false;
  3487. } else if (this->GeneratorTarget->GetPropertyAsBool(
  3488. "CUDA_FATBIN_COMPILATION")) {
  3489. cudaOptions.AddFlag("NvccCompilation", "fatbin");
  3490. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).fatbin");
  3491. notPtxLike = false;
  3492. } else if (this->GeneratorTarget->GetPropertyAsBool(
  3493. "CUDA_OPTIX_COMPILATION")) {
  3494. cudaOptions.AddFlag("NvccCompilation", "optix-ir");
  3495. cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).optixir");
  3496. notPtxLike = false;
  3497. }
  3498. if (notPtxLike &&
  3499. cmSystemTools::VersionCompareGreaterEq(
  3500. "8.0", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
  3501. // Explicitly state that we want this file to be treated as a
  3502. // CUDA file no matter what the file extensions is
  3503. // This is only needed for < CUDA 9
  3504. cudaOptions.AppendFlagString("AdditionalOptions", "-x cu");
  3505. }
  3506. // Specify the compiler program database file if configured.
  3507. std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
  3508. if (!pdb.empty()) {
  3509. // CUDA does not make the directory if it is non-standard.
  3510. std::string const pdbDir = cmSystemTools::GetFilenamePath(pdb);
  3511. cmSystemTools::MakeDirectory(pdbDir);
  3512. if (cmSystemTools::VersionCompareGreaterEq(
  3513. "9.2", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
  3514. // CUDA does not have a field for this and does not honor the
  3515. // ProgramDataBaseFileName field in ClCompile. Work around this
  3516. // limitation by creating the directory and passing the flag ourselves.
  3517. pdb = this->ConvertPath(pdb, true);
  3518. ConvertToWindowsSlash(pdb);
  3519. std::string const clFd = cmStrCat(R"(-Xcompiler="-Fd\")", pdb, R"(\"")");
  3520. cudaOptions.AppendFlagString("AdditionalOptions", clFd);
  3521. }
  3522. }
  3523. // CUDA automatically passes the proper '--machine' flag to nvcc
  3524. // for the current architecture, but does not reflect this default
  3525. // in the user-visible IDE settings. Set it explicitly.
  3526. if (this->Platform == "x64"_s) {
  3527. cudaOptions.AddFlag("TargetMachinePlatform", "64");
  3528. }
  3529. // Convert the host compiler options to the toolset's abstractions
  3530. // using a secondary flag table.
  3531. cudaOptions.ClearTables();
  3532. cudaOptions.AddTable(gg->GetCudaHostFlagTable());
  3533. cudaOptions.Reparse("AdditionalCompilerOptions");
  3534. // `CUDA 8.0.targets` places AdditionalCompilerOptions before nvcc!
  3535. // Pass them through -Xcompiler in AdditionalOptions instead.
  3536. if (const char* acoPtr = cudaOptions.GetFlag("AdditionalCompilerOptions")) {
  3537. std::string aco = acoPtr;
  3538. cudaOptions.RemoveFlag("AdditionalCompilerOptions");
  3539. if (!aco.empty()) {
  3540. aco = this->LocalGenerator->EscapeForShell(aco, false);
  3541. cudaOptions.AppendFlagString("AdditionalOptions",
  3542. cmStrCat("-Xcompiler=", aco));
  3543. }
  3544. }
  3545. cudaOptions.FixCudaCodeGeneration();
  3546. std::vector<std::string> targetDefines;
  3547. this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
  3548. "CUDA");
  3549. cudaOptions.AddDefines(targetDefines);
  3550. // Add a definition for the configuration name.
  3551. std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
  3552. cudaOptions.AddDefine(configDefine);
  3553. if (const std::string* exportMacro =
  3554. this->GeneratorTarget->GetExportMacro()) {
  3555. cudaOptions.AddDefine(*exportMacro);
  3556. }
  3557. // Get includes for this target
  3558. cudaOptions.AddIncludes(this->GetIncludes(configName, "CUDA"));
  3559. cudaOptions.AddFlag("UseHostInclude", "false");
  3560. // Add runtime library selection flag.
  3561. std::string const& cudaRuntime =
  3562. this->GeneratorTarget->GetRuntimeLinkLibrary("CUDA", configName);
  3563. if (cudaRuntime == "STATIC"_s) {
  3564. cudaOptions.AddFlag("CudaRuntime", "Static");
  3565. } else if (cudaRuntime == "SHARED"_s) {
  3566. cudaOptions.AddFlag("CudaRuntime", "Shared");
  3567. } else if (cudaRuntime == "NONE"_s) {
  3568. cudaOptions.AddFlag("CudaRuntime", "None");
  3569. }
  3570. if (this->ProjectType == VsProjectType::vcxproj && this->MSTools) {
  3571. // Suppress inheritance of host compiler optimization flags
  3572. // when the project does not specify any optimization flags for CUDA.
  3573. if (!cudaOptions.HasFlag("Optimization")) {
  3574. cudaOptions.AddFlag("Optimization", "");
  3575. }
  3576. }
  3577. this->CudaOptions[configName] = std::move(pOptions);
  3578. return true;
  3579. }
  3580. void cmVisualStudio10TargetGenerator::WriteCudaOptions(
  3581. Elem& e1, std::string const& configName)
  3582. {
  3583. if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled() ||
  3584. !this->GeneratorTarget->IsLanguageUsed("CUDA", configName)) {
  3585. return;
  3586. }
  3587. Elem e2(e1, "CudaCompile");
  3588. OptionsHelper cudaOptions(*(this->CudaOptions[configName]), e2);
  3589. cudaOptions.OutputAdditionalIncludeDirectories("CUDA");
  3590. cudaOptions.OutputPreprocessorDefinitions("CUDA");
  3591. cudaOptions.PrependInheritedString("AdditionalOptions");
  3592. cudaOptions.OutputFlagMap();
  3593. }
  3594. bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
  3595. {
  3596. if (!this->GlobalGenerator->IsCudaEnabled()) {
  3597. return true;
  3598. }
  3599. return std::all_of(
  3600. this->Configurations.begin(), this->Configurations.end(),
  3601. [this](std::string const& c) { return this->ComputeCudaLinkOptions(c); });
  3602. }
  3603. bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
  3604. std::string const& configName)
  3605. {
  3606. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3607. auto pOptions = cm::make_unique<Options>(
  3608. this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
  3609. Options& cudaLinkOptions = *pOptions;
  3610. cmGeneratorTarget::DeviceLinkSetter setter(*this->GeneratorTarget);
  3611. // Determine if we need to do a device link
  3612. const bool doDeviceLinking = requireDeviceLinking(
  3613. *this->GeneratorTarget, *this->LocalGenerator, configName);
  3614. cudaLinkOptions.AddFlag("PerformDeviceLink",
  3615. doDeviceLinking ? "true" : "false");
  3616. // Add extra flags for device linking
  3617. cudaLinkOptions.AppendFlagString(
  3618. "AdditionalOptions",
  3619. this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_FLAGS"));
  3620. cudaLinkOptions.AppendFlagString(
  3621. "AdditionalOptions",
  3622. this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS"));
  3623. std::vector<std::string> linkOpts;
  3624. std::string linkFlags;
  3625. this->GeneratorTarget->GetLinkOptions(linkOpts, configName, "CUDA");
  3626. // LINK_OPTIONS are escaped.
  3627. this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
  3628. cmComputeLinkInformation* pcli =
  3629. this->GeneratorTarget->GetLinkInformation(configName);
  3630. if (doDeviceLinking && pcli) {
  3631. cmLinkLineDeviceComputer computer(
  3632. this->LocalGenerator,
  3633. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  3634. std::string ignored_;
  3635. this->LocalGenerator->GetDeviceLinkFlags(computer, configName, ignored_,
  3636. linkFlags, ignored_, ignored_,
  3637. this->GeneratorTarget);
  3638. this->LocalGenerator->AddLanguageFlagsForLinking(
  3639. linkFlags, this->GeneratorTarget, "CUDA", configName);
  3640. }
  3641. cudaLinkOptions.AppendFlagString("AdditionalOptions", linkFlags);
  3642. if (doDeviceLinking) {
  3643. std::vector<std::string> libVec;
  3644. auto const& kinded = this->GeneratorTarget->GetKindedSources(configName);
  3645. // CMake conversion uses full paths when possible to allow deeper trees.
  3646. // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
  3647. // we must use relative paths.
  3648. const bool forceRelative = true;
  3649. for (cmGeneratorTarget::SourceAndKind const& si : kinded.Sources) {
  3650. switch (si.Kind) {
  3651. case cmGeneratorTarget::SourceKindExternalObject: {
  3652. std::string path =
  3653. this->ConvertPath(si.Source.Value->GetFullPath(), forceRelative);
  3654. ConvertToWindowsSlash(path);
  3655. libVec.emplace_back(std::move(path));
  3656. } break;
  3657. default:
  3658. break;
  3659. }
  3660. }
  3661. // For static libraries that have device linking enabled compute
  3662. // the libraries
  3663. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3664. cmComputeLinkInformation& cli = *pcli;
  3665. cmLinkLineDeviceComputer computer(
  3666. this->LocalGenerator,
  3667. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  3668. std::vector<BT<std::string>> btLibVec;
  3669. computer.ComputeLinkLibraries(cli, std::string{}, btLibVec);
  3670. for (auto const& item : btLibVec) {
  3671. libVec.emplace_back(item.Value);
  3672. }
  3673. }
  3674. if (!libVec.empty()) {
  3675. cudaLinkOptions.AddFlag("AdditionalDependencies", libVec);
  3676. }
  3677. }
  3678. this->CudaLinkOptions[configName] = std::move(pOptions);
  3679. return true;
  3680. }
  3681. void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
  3682. Elem& e1, std::string const& configName)
  3683. {
  3684. // We need to write link options for OBJECT libraries so that
  3685. // we override the default device link behavior ( enabled ) when
  3686. // building object libraries with ptx/optix-ir/etc
  3687. if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  3688. return;
  3689. }
  3690. if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
  3691. return;
  3692. }
  3693. Elem e2(e1, "CudaLink");
  3694. OptionsHelper cudaLinkOptions(*(this->CudaLinkOptions[configName]), e2);
  3695. cudaLinkOptions.OutputFlagMap();
  3696. }
  3697. bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions()
  3698. {
  3699. if (!this->GlobalGenerator->IsMarmasmEnabled()) {
  3700. return true;
  3701. }
  3702. return std::all_of(
  3703. this->Configurations.begin(), this->Configurations.end(),
  3704. [this](std::string const& c) { return this->ComputeMarmasmOptions(c); });
  3705. }
  3706. bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions(
  3707. std::string const& configName)
  3708. {
  3709. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3710. auto pOptions = cm::make_unique<Options>(
  3711. this->LocalGenerator, Options::MarmasmCompiler, gg->GetMarmasmFlagTable());
  3712. Options& marmasmOptions = *pOptions;
  3713. std::string flags;
  3714. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3715. cmBuildStep::Compile, "ASM_MARMASM",
  3716. configName);
  3717. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3718. "ASM_MARMASM", configName);
  3719. marmasmOptions.Parse(flags);
  3720. // Get includes for this target
  3721. marmasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MARMASM"));
  3722. this->MarmasmOptions[configName] = std::move(pOptions);
  3723. return true;
  3724. }
  3725. void cmVisualStudio10TargetGenerator::WriteMarmasmOptions(
  3726. Elem& e1, std::string const& configName)
  3727. {
  3728. if (!this->MSTools || !this->GlobalGenerator->IsMarmasmEnabled()) {
  3729. return;
  3730. }
  3731. Elem e2(e1, "MARMASM");
  3732. // Preprocessor definitions and includes are shared with clOptions.
  3733. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3734. clOptions.OutputPreprocessorDefinitions("ASM_MARMASM");
  3735. OptionsHelper marmasmOptions(*(this->MarmasmOptions[configName]), e2);
  3736. marmasmOptions.OutputAdditionalIncludeDirectories("ASM_MARMASM");
  3737. marmasmOptions.PrependInheritedString("AdditionalOptions");
  3738. marmasmOptions.OutputFlagMap();
  3739. }
  3740. bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
  3741. {
  3742. if (!this->GlobalGenerator->IsMasmEnabled()) {
  3743. return true;
  3744. }
  3745. return std::all_of(
  3746. this->Configurations.begin(), this->Configurations.end(),
  3747. [this](std::string const& c) { return this->ComputeMasmOptions(c); });
  3748. }
  3749. bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
  3750. std::string const& configName)
  3751. {
  3752. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3753. auto pOptions = cm::make_unique<Options>(
  3754. this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
  3755. Options& masmOptions = *pOptions;
  3756. // MSBuild enables debug information by default.
  3757. // Disable it explicitly unless a flag parsed below re-enables it.
  3758. masmOptions.AddFlag("GenerateDebugInformation", "false");
  3759. std::string flags;
  3760. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3761. cmBuildStep::Compile, "ASM_MASM",
  3762. configName);
  3763. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3764. "ASM_MASM", configName);
  3765. masmOptions.Parse(flags);
  3766. // Get includes for this target
  3767. masmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MASM"));
  3768. this->MasmOptions[configName] = std::move(pOptions);
  3769. return true;
  3770. }
  3771. void cmVisualStudio10TargetGenerator::WriteMasmOptions(
  3772. Elem& e1, std::string const& configName)
  3773. {
  3774. if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
  3775. return;
  3776. }
  3777. Elem e2(e1, "MASM");
  3778. // Preprocessor definitions and includes are shared with clOptions.
  3779. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3780. clOptions.OutputPreprocessorDefinitions("ASM_MASM");
  3781. OptionsHelper masmOptions(*(this->MasmOptions[configName]), e2);
  3782. masmOptions.OutputAdditionalIncludeDirectories("ASM_MASM");
  3783. masmOptions.PrependInheritedString("AdditionalOptions");
  3784. masmOptions.OutputFlagMap();
  3785. }
  3786. bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
  3787. {
  3788. if (!this->GlobalGenerator->IsNasmEnabled()) {
  3789. return true;
  3790. }
  3791. return std::all_of(
  3792. this->Configurations.begin(), this->Configurations.end(),
  3793. [this](std::string const& c) { return this->ComputeNasmOptions(c); });
  3794. }
  3795. bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
  3796. std::string const& configName)
  3797. {
  3798. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3799. auto pOptions = cm::make_unique<Options>(
  3800. this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
  3801. Options& nasmOptions = *pOptions;
  3802. std::string flags;
  3803. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3804. cmBuildStep::Compile, "ASM_NASM",
  3805. configName);
  3806. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3807. "ASM_NASM", configName);
  3808. flags += " -f";
  3809. flags += this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_OBJECT_FORMAT");
  3810. nasmOptions.Parse(flags);
  3811. // Get includes for this target
  3812. nasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_NASM"));
  3813. this->NasmOptions[configName] = std::move(pOptions);
  3814. return true;
  3815. }
  3816. void cmVisualStudio10TargetGenerator::WriteNasmOptions(
  3817. Elem& e1, std::string const& configName)
  3818. {
  3819. if (!this->GlobalGenerator->IsNasmEnabled()) {
  3820. return;
  3821. }
  3822. Elem e2(e1, "NASM");
  3823. OptionsHelper nasmOptions(*(this->NasmOptions[configName]), e2);
  3824. nasmOptions.OutputAdditionalIncludeDirectories("ASM_NASM");
  3825. nasmOptions.OutputFlagMap();
  3826. nasmOptions.PrependInheritedString("AdditionalOptions");
  3827. nasmOptions.OutputPreprocessorDefinitions("ASM_NASM");
  3828. // Preprocessor definitions and includes are shared with clOptions.
  3829. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3830. clOptions.OutputPreprocessorDefinitions("ASM_NASM");
  3831. }
  3832. void cmVisualStudio10TargetGenerator::WriteLibOptions(
  3833. Elem& e1, std::string const& config)
  3834. {
  3835. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3836. this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  3837. return;
  3838. }
  3839. const std::string& linkLanguage =
  3840. this->GeneratorTarget->GetLinkClosure(config)->LinkerLanguage;
  3841. std::string libflags;
  3842. this->LocalGenerator->GetStaticLibraryFlags(libflags, config, linkLanguage,
  3843. this->GeneratorTarget);
  3844. if (!libflags.empty()) {
  3845. Elem e2(e1, "Lib");
  3846. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3847. cmVS10GeneratorOptions libOptions(this->LocalGenerator,
  3848. cmVisualStudioGeneratorOptions::Linker,
  3849. gg->GetLibFlagTable(), this);
  3850. libOptions.Parse(libflags);
  3851. OptionsHelper oh(libOptions, e2);
  3852. oh.PrependInheritedString("AdditionalOptions");
  3853. oh.OutputFlagMap();
  3854. }
  3855. // We cannot generate metadata for static libraries. WindowsPhone
  3856. // and WindowsStore tools look at GenerateWindowsMetadata in the
  3857. // Link tool options even for static libraries.
  3858. if (this->GlobalGenerator->TargetsWindowsPhone() ||
  3859. this->GlobalGenerator->TargetsWindowsStore()) {
  3860. Elem e2(e1, "Link");
  3861. e2.Element("GenerateWindowsMetadata", "false");
  3862. }
  3863. }
  3864. void cmVisualStudio10TargetGenerator::WriteManifestOptions(
  3865. Elem& e1, std::string const& config)
  3866. {
  3867. if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
  3868. this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3869. this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
  3870. return;
  3871. }
  3872. std::vector<cmSourceFile const*> manifest_srcs;
  3873. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  3874. cmValue dpiAware = this->GeneratorTarget->GetProperty("VS_DPI_AWARE");
  3875. if (!manifest_srcs.empty() || dpiAware) {
  3876. Elem e2(e1, "Manifest");
  3877. if (!manifest_srcs.empty()) {
  3878. std::ostringstream oss;
  3879. for (cmSourceFile const* mi : manifest_srcs) {
  3880. std::string m = this->ConvertPath(mi->GetFullPath(), false);
  3881. ConvertToWindowsSlash(m);
  3882. oss << m << ";";
  3883. }
  3884. e2.Element("AdditionalManifestFiles", oss.str());
  3885. }
  3886. if (dpiAware) {
  3887. if (*dpiAware == "PerMonitor"_s) {
  3888. e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware");
  3889. } else if (dpiAware.IsOn()) {
  3890. e2.Element("EnableDpiAwareness", "true");
  3891. } else if (dpiAware.IsOff()) {
  3892. e2.Element("EnableDpiAwareness", "false");
  3893. } else {
  3894. cmSystemTools::Error(
  3895. cmStrCat("Bad parameter for VS_DPI_AWARE: ", *dpiAware));
  3896. }
  3897. }
  3898. }
  3899. }
  3900. void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
  3901. Elem& e1, std::string const& configName)
  3902. {
  3903. // Look through the sources for AndroidManifest.xml and use
  3904. // its location as the root source directory.
  3905. std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
  3906. {
  3907. for (cmGeneratorTarget::AllConfigSource const& source :
  3908. this->GeneratorTarget->GetAllConfigSources()) {
  3909. if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
  3910. "androidmanifest.xml" ==
  3911. cmSystemTools::LowerCase(source.Source->GetLocation().GetName())) {
  3912. rootDir = source.Source->GetLocation().GetDirectory();
  3913. break;
  3914. }
  3915. }
  3916. }
  3917. // Tell MSBuild to launch Ant.
  3918. Elem e2(e1, "AntBuild");
  3919. {
  3920. std::string antBuildPath = rootDir;
  3921. ConvertToWindowsSlash(antBuildPath);
  3922. e2.Element("AntBuildPath", antBuildPath);
  3923. }
  3924. if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
  3925. e2.Element("SkipAntStep", "true");
  3926. }
  3927. if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
  3928. e2.Element("EnableProGuard", "true");
  3929. }
  3930. if (cmValue proGuardConfigLocation =
  3931. this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
  3932. e2.Element("ProGuardConfigLocation", *proGuardConfigLocation);
  3933. }
  3934. if (cmValue securePropertiesLocation =
  3935. this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
  3936. e2.Element("SecurePropertiesLocation", *securePropertiesLocation);
  3937. }
  3938. if (cmValue nativeLibDirectoriesExpression =
  3939. this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
  3940. std::string nativeLibDirs = cmGeneratorExpression::Evaluate(
  3941. *nativeLibDirectoriesExpression, this->LocalGenerator, configName);
  3942. e2.Element("NativeLibDirectories", nativeLibDirs);
  3943. }
  3944. if (cmValue nativeLibDependenciesExpression =
  3945. this->GeneratorTarget->GetProperty(
  3946. "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
  3947. std::string nativeLibDeps = cmGeneratorExpression::Evaluate(
  3948. *nativeLibDependenciesExpression, this->LocalGenerator, configName);
  3949. e2.Element("NativeLibDependencies", nativeLibDeps);
  3950. }
  3951. if (cmValue javaSourceDir =
  3952. this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
  3953. e2.Element("JavaSourceDir", *javaSourceDir);
  3954. }
  3955. if (cmValue jarDirectoriesExpression =
  3956. this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
  3957. std::string jarDirectories = cmGeneratorExpression::Evaluate(
  3958. *jarDirectoriesExpression, this->LocalGenerator, configName);
  3959. e2.Element("JarDirectories", jarDirectories);
  3960. }
  3961. if (cmValue jarDeps =
  3962. this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
  3963. e2.Element("JarDependencies", *jarDeps);
  3964. }
  3965. if (cmValue assetsDirectories =
  3966. this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
  3967. e2.Element("AssetsDirectories", *assetsDirectories);
  3968. }
  3969. {
  3970. std::string manifest_xml = cmStrCat(rootDir, "/AndroidManifest.xml");
  3971. ConvertToWindowsSlash(manifest_xml);
  3972. e2.Element("AndroidManifestLocation", manifest_xml);
  3973. }
  3974. if (cmValue antAdditionalOptions =
  3975. this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
  3976. e2.Element("AdditionalOptions",
  3977. cmStrCat(*antAdditionalOptions, " %(AdditionalOptions)"));
  3978. }
  3979. }
  3980. bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
  3981. {
  3982. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  3983. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3984. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3985. for (std::string const& c : this->Configurations) {
  3986. if (!this->ComputeLinkOptions(c)) {
  3987. return false;
  3988. }
  3989. }
  3990. }
  3991. return true;
  3992. }
  3993. bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
  3994. std::string const& config)
  3995. {
  3996. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3997. auto pOptions = cm::make_unique<Options>(
  3998. this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this);
  3999. Options& linkOptions = *pOptions;
  4000. cmGeneratorTarget::LinkClosure const* linkClosure =
  4001. this->GeneratorTarget->GetLinkClosure(config);
  4002. const std::string& linkLanguage = linkClosure->LinkerLanguage;
  4003. if (linkLanguage.empty()) {
  4004. cmSystemTools::Error(cmStrCat(
  4005. "CMake can not determine linker language for target: ", this->Name));
  4006. return false;
  4007. }
  4008. std::string CONFIG = cmSystemTools::UpperCase(config);
  4009. const char* linkType = "SHARED";
  4010. if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4011. linkType = "MODULE";
  4012. }
  4013. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4014. linkType = "EXE";
  4015. }
  4016. std::string flags;
  4017. std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS");
  4018. flags += ' ';
  4019. flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase);
  4020. std::string linkFlagVar = cmStrCat(linkFlagVarBase, '_', CONFIG);
  4021. flags += ' ';
  4022. flags += this->Makefile->GetRequiredDefinition(linkFlagVar);
  4023. cmValue targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS");
  4024. if (targetLinkFlags) {
  4025. flags += ' ';
  4026. flags += *targetLinkFlags;
  4027. }
  4028. std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG);
  4029. if (cmValue flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) {
  4030. flags += ' ';
  4031. flags += *flagsConfig;
  4032. }
  4033. std::vector<std::string> opts;
  4034. this->GeneratorTarget->GetLinkOptions(opts, config, linkLanguage);
  4035. // LINK_OPTIONS are escaped.
  4036. this->LocalGenerator->AppendCompileOptions(flags, opts);
  4037. cmComputeLinkInformation* pcli =
  4038. this->GeneratorTarget->GetLinkInformation(config);
  4039. if (!pcli) {
  4040. cmSystemTools::Error(
  4041. cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
  4042. this->Name));
  4043. return false;
  4044. }
  4045. cmComputeLinkInformation& cli = *pcli;
  4046. std::vector<std::string> libVec;
  4047. std::vector<std::string> vsTargetVec;
  4048. this->AddLibraries(cli, libVec, vsTargetVec, config);
  4049. std::string standardLibsVar =
  4050. cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
  4051. std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar);
  4052. cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
  4053. linkOptions.AddFlag("AdditionalDependencies", libVec);
  4054. // Populate TargetsFileAndConfigsVec
  4055. for (std::string const& ti : vsTargetVec) {
  4056. this->AddTargetsFileAndConfigPair(ti, config);
  4057. }
  4058. std::vector<std::string> const& ldirs = cli.GetDirectories();
  4059. std::vector<std::string> linkDirs;
  4060. for (std::string const& d : ldirs) {
  4061. // first just full path
  4062. linkDirs.push_back(d);
  4063. // next path with configuration type Debug, Release, etc
  4064. linkDirs.emplace_back(cmStrCat(d, "/$(Configuration)"));
  4065. }
  4066. linkDirs.push_back("%(AdditionalLibraryDirectories)");
  4067. linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
  4068. cmGeneratorTarget::Names targetNames;
  4069. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4070. targetNames = this->GeneratorTarget->GetExecutableNames(config);
  4071. } else {
  4072. targetNames = this->GeneratorTarget->GetLibraryNames(config);
  4073. }
  4074. if (this->MSTools) {
  4075. if (this->GeneratorTarget->IsWin32Executable(config)) {
  4076. if (this->GlobalGenerator->TargetsWindowsCE()) {
  4077. linkOptions.AddFlag("SubSystem", "WindowsCE");
  4078. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4079. if (this->ClOptions[config]->UsingUnicode()) {
  4080. linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
  4081. } else {
  4082. linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
  4083. }
  4084. }
  4085. } else {
  4086. linkOptions.AddFlag("SubSystem", "Windows");
  4087. }
  4088. } else {
  4089. if (this->GlobalGenerator->TargetsWindowsCE()) {
  4090. linkOptions.AddFlag("SubSystem", "WindowsCE");
  4091. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4092. if (this->ClOptions[config]->UsingUnicode()) {
  4093. linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
  4094. } else {
  4095. linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
  4096. }
  4097. }
  4098. } else {
  4099. linkOptions.AddFlag("SubSystem", "Console");
  4100. };
  4101. }
  4102. if (cmValue stackVal = this->Makefile->GetDefinition(
  4103. cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"))) {
  4104. linkOptions.AddFlag("StackReserveSize", *stackVal);
  4105. }
  4106. linkOptions.AddFlag("GenerateDebugInformation", "false");
  4107. std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config),
  4108. '/', targetNames.PDB);
  4109. if (!targetNames.ImportLibrary.empty()) {
  4110. std::string imLib =
  4111. cmStrCat(this->GeneratorTarget->GetDirectory(
  4112. config, cmStateEnums::ImportLibraryArtifact),
  4113. '/', targetNames.ImportLibrary);
  4114. linkOptions.AddFlag("ImportLibrary", imLib);
  4115. }
  4116. linkOptions.AddFlag("ProgramDataBaseFile", pdb);
  4117. // A Windows Runtime component uses internal .NET metadata,
  4118. // so does not have an import library.
  4119. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
  4120. this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
  4121. linkOptions.AddFlag("GenerateWindowsMetadata", "true");
  4122. } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
  4123. this->GlobalGenerator->TargetsWindowsStore()) {
  4124. // WindowsPhone and WindowsStore components are in an app container
  4125. // and produce WindowsMetadata. If we are not producing a WINRT
  4126. // component, then do not generate the metadata here.
  4127. linkOptions.AddFlag("GenerateWindowsMetadata", "false");
  4128. }
  4129. if (this->GlobalGenerator->TargetsWindowsPhone() &&
  4130. this->GlobalGenerator->GetSystemVersion() == "8.0"_s) {
  4131. // WindowsPhone 8.0 does not have ole32.
  4132. linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
  4133. }
  4134. } else if (this->NsightTegra) {
  4135. linkOptions.AddFlag("SoName", targetNames.SharedObject);
  4136. }
  4137. linkOptions.Parse(flags);
  4138. linkOptions.FixManifestUACFlags();
  4139. if (this->MSTools) {
  4140. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  4141. this->GeneratorTarget->GetModuleDefinitionInfo(config);
  4142. if (mdi && !mdi->DefFile.empty()) {
  4143. linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile);
  4144. }
  4145. linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
  4146. "%(IgnoreSpecificDefaultLibraries)");
  4147. }
  4148. // VS 2015 without all updates has a v140 toolset whose
  4149. // GenerateDebugInformation expects No/Debug instead of false/true.
  4150. if (gg->GetPlatformToolsetNeedsDebugEnum()) {
  4151. if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
  4152. if (strcmp(debug, "false") == 0) {
  4153. linkOptions.AddFlag("GenerateDebugInformation", "No");
  4154. } else if (strcmp(debug, "true") == 0) {
  4155. linkOptions.AddFlag("GenerateDebugInformation", "Debug");
  4156. }
  4157. }
  4158. }
  4159. // Managed code cannot be linked with /DEBUG:FASTLINK
  4160. if (this->Managed) {
  4161. if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
  4162. if (strcmp(debug, "DebugFastLink") == 0) {
  4163. linkOptions.AddFlag("GenerateDebugInformation", "Debug");
  4164. }
  4165. }
  4166. }
  4167. this->LinkOptions[config] = std::move(pOptions);
  4168. return true;
  4169. }
  4170. bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
  4171. {
  4172. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4173. for (std::string const& c : this->Configurations) {
  4174. if (!this->ComputeLibOptions(c)) {
  4175. return false;
  4176. }
  4177. }
  4178. }
  4179. return true;
  4180. }
  4181. bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
  4182. std::string const& config)
  4183. {
  4184. cmComputeLinkInformation* pcli =
  4185. this->GeneratorTarget->GetLinkInformation(config);
  4186. if (!pcli) {
  4187. cmSystemTools::Error(
  4188. cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
  4189. this->Name));
  4190. return false;
  4191. }
  4192. cmComputeLinkInformation& cli = *pcli;
  4193. using ItemVector = cmComputeLinkInformation::ItemVector;
  4194. const ItemVector& libs = cli.GetItems();
  4195. for (cmComputeLinkInformation::Item const& l : libs) {
  4196. if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  4197. cmVS10IsTargetsFile(l.Value.Value)) {
  4198. std::string path =
  4199. this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
  4200. ConvertToWindowsSlash(path);
  4201. this->AddTargetsFileAndConfigPair(path, config);
  4202. }
  4203. }
  4204. return true;
  4205. }
  4206. void cmVisualStudio10TargetGenerator::WriteLinkOptions(
  4207. Elem& e1, std::string const& config)
  4208. {
  4209. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4210. this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
  4211. return;
  4212. }
  4213. if (this->ProjectType == VsProjectType::csproj) {
  4214. return;
  4215. }
  4216. {
  4217. Elem e2(e1, "Link");
  4218. OptionsHelper linkOptions(*(this->LinkOptions[config]), e2);
  4219. linkOptions.PrependInheritedString("AdditionalOptions");
  4220. linkOptions.OutputFlagMap();
  4221. }
  4222. if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
  4223. this->GeneratorTarget)) {
  4224. Elem e2(e1, "ProjectReference");
  4225. e2.Element("LinkLibraryDependencies", "false");
  4226. }
  4227. }
  4228. void cmVisualStudio10TargetGenerator::AddLibraries(
  4229. const cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
  4230. std::vector<std::string>& vsTargetVec, const std::string& config)
  4231. {
  4232. using ItemVector = cmComputeLinkInformation::ItemVector;
  4233. ItemVector const& libs = cli.GetItems();
  4234. for (cmComputeLinkInformation::Item const& l : libs) {
  4235. if (l.Target) {
  4236. auto managedType = l.Target->GetManagedType(config);
  4237. if (managedType != cmGeneratorTarget::ManagedType::Native &&
  4238. this->GeneratorTarget->GetManagedType(config) !=
  4239. cmGeneratorTarget::ManagedType::Native &&
  4240. l.Target->IsImported() &&
  4241. l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  4242. auto location = l.Target->GetFullPath(config);
  4243. if (!location.empty()) {
  4244. ConvertToWindowsSlash(location);
  4245. switch (this->ProjectType) {
  4246. case VsProjectType::csproj:
  4247. // If the target we want to "link" to is an imported managed
  4248. // target and this is a C# project, we add a hint reference. This
  4249. // reference is written to project file in
  4250. // WriteDotNetReferences().
  4251. this->DotNetHintReferences[config].push_back(
  4252. DotNetHintReference(l.Target->GetName(), location));
  4253. break;
  4254. case VsProjectType::vcxproj:
  4255. // Add path of assembly to list of using-directories, so the
  4256. // managed assembly can be used by '#using <assembly.dll>' in
  4257. // code.
  4258. this->AdditionalUsingDirectories[config].insert(
  4259. cmSystemTools::GetFilenamePath(location));
  4260. break;
  4261. default:
  4262. // In .proj files, we wouldn't be referencing libraries.
  4263. break;
  4264. }
  4265. }
  4266. }
  4267. // Do not allow C# targets to be added to the LIB listing. LIB files are
  4268. // used for linking C++ dependencies. C# libraries do not have lib files.
  4269. // Instead, they compile down to C# reference libraries (DLL files). The
  4270. // `<ProjectReference>` elements added to the vcxproj are enough for the
  4271. // IDE to deduce the DLL file required by other C# projects that need its
  4272. // reference library.
  4273. if (managedType == cmGeneratorTarget::ManagedType::Managed) {
  4274. continue;
  4275. }
  4276. }
  4277. if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  4278. std::string path =
  4279. this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
  4280. ConvertToWindowsSlash(path);
  4281. if (cmVS10IsTargetsFile(l.Value.Value)) {
  4282. vsTargetVec.push_back(path);
  4283. } else {
  4284. libVec.push_back(l.HasFeature() ? l.GetFormattedItem(path).Value
  4285. : path);
  4286. }
  4287. } else if (!l.Target ||
  4288. (l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4289. l.Target->GetType() != cmStateEnums::OBJECT_LIBRARY)) {
  4290. libVec.push_back(l.Value.Value);
  4291. }
  4292. }
  4293. }
  4294. void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
  4295. std::string const& targetsFile, std::string const& config)
  4296. {
  4297. for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) {
  4298. if (cmSystemTools::ComparePath(targetsFile, i.File)) {
  4299. if (!cm::contains(i.Configs, config)) {
  4300. i.Configs.push_back(config);
  4301. }
  4302. return;
  4303. }
  4304. }
  4305. TargetsFileAndConfigs entry;
  4306. entry.File = targetsFile;
  4307. entry.Configs.push_back(config);
  4308. this->TargetsFileAndConfigsVec.push_back(entry);
  4309. }
  4310. void cmVisualStudio10TargetGenerator::WriteMidlOptions(
  4311. Elem& e1, std::string const& configName)
  4312. {
  4313. if (!this->MSTools) {
  4314. return;
  4315. }
  4316. if (this->ProjectType == VsProjectType::csproj) {
  4317. return;
  4318. }
  4319. if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
  4320. return;
  4321. }
  4322. // This processes *any* of the .idl files specified in the project's file
  4323. // list (and passed as the item metadata %(Filename) expressing the rule
  4324. // input filename) into output files at the per-config *build* dir
  4325. // ($(IntDir)) each.
  4326. //
  4327. // IOW, this MIDL section is intended to provide a fully generic syntax
  4328. // content suitable for most cases (read: if you get errors, then it's quite
  4329. // probable that the error is on your side of the .idl setup).
  4330. //
  4331. // Also, note that the marked-as-generated _i.c file in the Visual Studio
  4332. // generator case needs to be referred to as $(IntDir)\foo_i.c at the
  4333. // project's file list, otherwise the compiler-side processing won't pick it
  4334. // up (for non-directory form, it ends up looking in project binary dir
  4335. // only). Perhaps there's something to be done to make this more automatic
  4336. // on the CMake side?
  4337. std::vector<std::string> const includes =
  4338. this->GetIncludes(configName, "MIDL");
  4339. std::ostringstream oss;
  4340. for (std::string const& i : includes) {
  4341. oss << i << ";";
  4342. }
  4343. oss << "%(AdditionalIncludeDirectories)";
  4344. Elem e2(e1, "Midl");
  4345. e2.Element("AdditionalIncludeDirectories", oss.str());
  4346. e2.Element("OutputDirectory", "$(ProjectDir)/$(IntDir)");
  4347. e2.Element("HeaderFileName", "%(Filename).h");
  4348. e2.Element("TypeLibraryName", "%(Filename).tlb");
  4349. e2.Element("InterfaceIdentifierFileName", "%(Filename)_i.c");
  4350. e2.Element("ProxyFileName", "%(Filename)_p.c");
  4351. }
  4352. void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups(Elem& e0)
  4353. {
  4354. if (this->ProjectType == VsProjectType::csproj) {
  4355. return;
  4356. }
  4357. for (const std::string& c : this->Configurations) {
  4358. Elem e1(e0, "ItemDefinitionGroup");
  4359. e1.Attribute("Condition", this->CalcCondition(c));
  4360. // output cl compile flags <ClCompile></ClCompile>
  4361. if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  4362. this->WriteClOptions(e1, c);
  4363. // output rc compile flags <ResourceCompile></ResourceCompile>
  4364. this->WriteRCOptions(e1, c);
  4365. this->WriteCudaOptions(e1, c);
  4366. this->WriteMarmasmOptions(e1, c);
  4367. this->WriteMasmOptions(e1, c);
  4368. this->WriteNasmOptions(e1, c);
  4369. }
  4370. // output midl flags <Midl></Midl>
  4371. this->WriteMidlOptions(e1, c);
  4372. // write events
  4373. if (this->ProjectType != VsProjectType::csproj) {
  4374. this->WriteEvents(e1, c);
  4375. }
  4376. // output link flags <Link></Link>
  4377. this->WriteLinkOptions(e1, c);
  4378. this->WriteCudaLinkOptions(e1, c);
  4379. // output lib flags <Lib></Lib>
  4380. this->WriteLibOptions(e1, c);
  4381. // output manifest flags <Manifest></Manifest>
  4382. this->WriteManifestOptions(e1, c);
  4383. if (this->NsightTegra &&
  4384. this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
  4385. this->WriteAntBuildOptions(e1, c);
  4386. }
  4387. }
  4388. }
  4389. void cmVisualStudio10TargetGenerator::WriteEvents(
  4390. Elem& e1, std::string const& configName)
  4391. {
  4392. bool addedPrelink = false;
  4393. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  4394. this->GeneratorTarget->GetModuleDefinitionInfo(configName);
  4395. if (mdi && mdi->DefFileGenerated) {
  4396. addedPrelink = true;
  4397. std::vector<cmCustomCommand> commands =
  4398. this->GeneratorTarget->GetPreLinkCommands();
  4399. this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
  4400. commands, configName);
  4401. this->WriteEvent(e1, "PreLinkEvent", commands, configName);
  4402. }
  4403. if (!addedPrelink) {
  4404. this->WriteEvent(e1, "PreLinkEvent",
  4405. this->GeneratorTarget->GetPreLinkCommands(), configName);
  4406. }
  4407. this->WriteEvent(e1, "PreBuildEvent",
  4408. this->GeneratorTarget->GetPreBuildCommands(), configName);
  4409. this->WriteEvent(e1, "PostBuildEvent",
  4410. this->GeneratorTarget->GetPostBuildCommands(), configName);
  4411. }
  4412. void cmVisualStudio10TargetGenerator::WriteEvent(
  4413. Elem& e1, const std::string& name,
  4414. std::vector<cmCustomCommand> const& commands, std::string const& configName)
  4415. {
  4416. if (commands.empty()) {
  4417. return;
  4418. }
  4419. cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
  4420. std::string script;
  4421. const char* pre = "";
  4422. std::string comment;
  4423. bool stdPipesUTF8 = false;
  4424. for (cmCustomCommand const& cc : commands) {
  4425. cmCustomCommandGenerator ccg(cc, configName, lg);
  4426. if (!ccg.HasOnlyEmptyCommandLines()) {
  4427. comment += pre;
  4428. comment += lg->ConstructComment(ccg);
  4429. script += pre;
  4430. pre = "\n";
  4431. script += lg->ConstructScript(ccg);
  4432. stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
  4433. }
  4434. }
  4435. if (!script.empty()) {
  4436. script += lg->FinishConstructScript(this->ProjectType);
  4437. }
  4438. comment = cmVS10EscapeComment(comment);
  4439. if (this->ProjectType != VsProjectType::csproj) {
  4440. Elem e2(e1, name);
  4441. if (stdPipesUTF8) {
  4442. this->WriteStdOutEncodingUtf8(e2);
  4443. }
  4444. e2.Element("Message", comment);
  4445. e2.Element("Command", script);
  4446. } else {
  4447. std::string strippedComment = comment;
  4448. strippedComment.erase(
  4449. std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
  4450. strippedComment.end());
  4451. std::ostringstream oss;
  4452. if (!comment.empty() && !strippedComment.empty()) {
  4453. oss << "echo " << comment << "\n";
  4454. }
  4455. oss << script << "\n";
  4456. e1.Element(name, oss.str());
  4457. }
  4458. }
  4459. void cmVisualStudio10TargetGenerator::WriteSdkStyleEvents(
  4460. Elem& e0, std::string const& configName)
  4461. {
  4462. this->WriteSdkStyleEvent(e0, "PreLink", "BeforeTargets", "Link",
  4463. this->GeneratorTarget->GetPreLinkCommands(),
  4464. configName);
  4465. this->WriteSdkStyleEvent(e0, "PreBuild", "BeforeTargets", "PreBuildEvent",
  4466. this->GeneratorTarget->GetPreBuildCommands(),
  4467. configName);
  4468. this->WriteSdkStyleEvent(e0, "PostBuild", "AfterTargets", "PostBuildEvent",
  4469. this->GeneratorTarget->GetPostBuildCommands(),
  4470. configName);
  4471. }
  4472. void cmVisualStudio10TargetGenerator::WriteSdkStyleEvent(
  4473. Elem& e0, const std::string& name, const std::string& when,
  4474. const std::string& target, std::vector<cmCustomCommand> const& commands,
  4475. std::string const& configName)
  4476. {
  4477. if (commands.empty()) {
  4478. return;
  4479. }
  4480. Elem e1(e0, "Target");
  4481. e1.Attribute("Condition",
  4482. cmStrCat("'$(Configuration)' == '", configName, '\''));
  4483. e1.Attribute("Name", name + configName);
  4484. e1.Attribute(when.c_str(), target);
  4485. e1.SetHasElements();
  4486. cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
  4487. std::string script;
  4488. const char* pre = "";
  4489. std::string comment;
  4490. bool stdPipesUTF8 = false;
  4491. for (cmCustomCommand const& cc : commands) {
  4492. cmCustomCommandGenerator ccg(cc, configName, lg);
  4493. if (!ccg.HasOnlyEmptyCommandLines()) {
  4494. comment += pre;
  4495. comment += lg->ConstructComment(ccg);
  4496. script += pre;
  4497. pre = "\n";
  4498. script += lg->ConstructScript(ccg);
  4499. stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
  4500. }
  4501. }
  4502. if (!script.empty()) {
  4503. script += lg->FinishConstructScript(this->ProjectType);
  4504. }
  4505. comment = cmVS10EscapeComment(comment);
  4506. std::string strippedComment = comment;
  4507. strippedComment.erase(
  4508. std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
  4509. strippedComment.end());
  4510. std::ostringstream oss;
  4511. if (!comment.empty() && !strippedComment.empty()) {
  4512. oss << "echo " << comment << "\n";
  4513. }
  4514. oss << script << "\n";
  4515. Elem e2(e1, "Exec");
  4516. e2.Attribute("Command", oss.str());
  4517. }
  4518. void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0)
  4519. {
  4520. cmGlobalGenerator::TargetDependSet const& unordered =
  4521. this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
  4522. using OrderedTargetDependSet =
  4523. cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
  4524. OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  4525. Elem e1(e0, "ItemGroup");
  4526. e1.SetHasElements();
  4527. for (cmGeneratorTarget const* dt : depends) {
  4528. if (!dt->IsInBuildSystem()) {
  4529. continue;
  4530. }
  4531. // skip fortran targets as they can not be processed by MSBuild
  4532. // the only reference will be in the .sln file
  4533. if (this->GlobalGenerator->TargetIsFortranOnly(dt)) {
  4534. continue;
  4535. }
  4536. cmLocalGenerator* lg = dt->GetLocalGenerator();
  4537. std::string name = dt->GetName();
  4538. std::string path;
  4539. if (cmValue p = dt->GetProperty("EXTERNAL_MSPROJECT")) {
  4540. path = *p;
  4541. } else {
  4542. path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(),
  4543. computeProjectFileExtension(dt));
  4544. }
  4545. ConvertToWindowsSlash(path);
  4546. Elem e2(e1, "ProjectReference");
  4547. e2.Attribute("Include", path);
  4548. e2.Element("Project",
  4549. cmStrCat('{', this->GlobalGenerator->GetGUID(name), '}'));
  4550. e2.Element("Name", name);
  4551. this->WriteDotNetReferenceCustomTags(e2, name);
  4552. if (dt->IsCSharpOnly() || cmHasLiteralSuffix(path, "csproj")) {
  4553. e2.Element("SkipGetTargetFrameworkProperties", "true");
  4554. }
  4555. // Don't reference targets that don't produce any output.
  4556. else if (this->Configurations.empty() ||
  4557. dt->GetManagedType(this->Configurations[0]) ==
  4558. cmGeneratorTarget::ManagedType::Undefined) {
  4559. e2.Element("ReferenceOutputAssembly", "false");
  4560. e2.Element("CopyToOutputDirectory", "Never");
  4561. }
  4562. }
  4563. }
  4564. void cmVisualStudio10TargetGenerator::WritePlatformExtensions(Elem& e1)
  4565. {
  4566. // This only applies to Windows 10 apps
  4567. if (this->GlobalGenerator->TargetsWindowsStore() &&
  4568. cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
  4569. cmValue desktopExtensionsVersion =
  4570. this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
  4571. if (desktopExtensionsVersion) {
  4572. this->WriteSinglePlatformExtension(e1, "WindowsDesktop",
  4573. *desktopExtensionsVersion);
  4574. }
  4575. cmValue mobileExtensionsVersion =
  4576. this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
  4577. if (mobileExtensionsVersion) {
  4578. this->WriteSinglePlatformExtension(e1, "WindowsMobile",
  4579. *mobileExtensionsVersion);
  4580. }
  4581. }
  4582. }
  4583. void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
  4584. Elem& e1, std::string const& extension, std::string const& version)
  4585. {
  4586. const std::string s =
  4587. cmStrCat("$([Microsoft.Build.Utilities.ToolLocationHelper]"
  4588. "::GetPlatformExtensionSDKLocation(`",
  4589. extension, ", Version=", version,
  4590. "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
  4591. "$(ExtensionSDKDirectoryRoot), null))"
  4592. "\\DesignTime\\CommonConfiguration\\Neutral\\",
  4593. extension, ".props");
  4594. Elem e2(e1, "Import");
  4595. e2.Attribute("Project", s);
  4596. e2.Attribute("Condition", cmStrCat("exists('", s, "')"));
  4597. }
  4598. void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0)
  4599. {
  4600. cmList sdkReferences;
  4601. std::unique_ptr<Elem> spe1;
  4602. if (cmValue vsSDKReferences =
  4603. this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
  4604. sdkReferences.assign(*vsSDKReferences);
  4605. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  4606. for (auto const& ri : sdkReferences) {
  4607. Elem(*spe1, "SDKReference").Attribute("Include", ri);
  4608. }
  4609. }
  4610. // This only applies to Windows 10 apps
  4611. if (this->GlobalGenerator->TargetsWindowsStore() &&
  4612. cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
  4613. cmValue desktopExtensionsVersion =
  4614. this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
  4615. cmValue mobileExtensionsVersion =
  4616. this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
  4617. cmValue iotExtensionsVersion =
  4618. this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
  4619. if (desktopExtensionsVersion || mobileExtensionsVersion ||
  4620. iotExtensionsVersion) {
  4621. if (!spe1) {
  4622. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  4623. }
  4624. if (desktopExtensionsVersion) {
  4625. this->WriteSingleSDKReference(*spe1, "WindowsDesktop",
  4626. *desktopExtensionsVersion);
  4627. }
  4628. if (mobileExtensionsVersion) {
  4629. this->WriteSingleSDKReference(*spe1, "WindowsMobile",
  4630. *mobileExtensionsVersion);
  4631. }
  4632. if (iotExtensionsVersion) {
  4633. this->WriteSingleSDKReference(*spe1, "WindowsIoT",
  4634. *iotExtensionsVersion);
  4635. }
  4636. }
  4637. }
  4638. }
  4639. void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
  4640. Elem& e1, std::string const& extension, std::string const& version)
  4641. {
  4642. Elem(e1, "SDKReference")
  4643. .Attribute("Include", cmStrCat(extension, ", Version=", version));
  4644. }
  4645. namespace {
  4646. std::string ComputeCertificateThumbprint(const std::string& source)
  4647. {
  4648. std::string thumbprint;
  4649. CRYPT_INTEGER_BLOB cryptBlob;
  4650. HCERTSTORE certStore = nullptr;
  4651. PCCERT_CONTEXT certContext = nullptr;
  4652. HANDLE certFile = CreateFileW(
  4653. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  4654. FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  4655. if (certFile != INVALID_HANDLE_VALUE && certFile) {
  4656. DWORD fileSize = GetFileSize(certFile, nullptr);
  4657. if (fileSize != INVALID_FILE_SIZE) {
  4658. auto certData = cm::make_unique<BYTE[]>(fileSize);
  4659. if (certData) {
  4660. DWORD dwRead = 0;
  4661. if (ReadFile(certFile, certData.get(), fileSize, &dwRead, nullptr)) {
  4662. cryptBlob.cbData = fileSize;
  4663. cryptBlob.pbData = certData.get();
  4664. // Verify that this is a valid cert
  4665. if (PFXIsPFXBlob(&cryptBlob)) {
  4666. // Open the certificate as a store
  4667. certStore =
  4668. PFXImportCertStore(&cryptBlob, nullptr, CRYPT_EXPORTABLE);
  4669. if (certStore) {
  4670. // There should only be 1 cert.
  4671. certContext =
  4672. CertEnumCertificatesInStore(certStore, certContext);
  4673. if (certContext) {
  4674. // The hash is 20 bytes
  4675. BYTE hashData[20];
  4676. DWORD hashLength = 20;
  4677. // Buffer to print the hash. Each byte takes 2 chars +
  4678. // terminating character
  4679. char hashPrint[41];
  4680. char* pHashPrint = hashPrint;
  4681. // Get the hash property from the certificate
  4682. if (CertGetCertificateContextProperty(
  4683. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  4684. for (DWORD i = 0; i < hashLength; i++) {
  4685. // Convert each byte to hexadecimal
  4686. snprintf(pHashPrint, 3, "%02X", hashData[i]);
  4687. pHashPrint += 2;
  4688. }
  4689. *pHashPrint = '\0';
  4690. thumbprint = hashPrint;
  4691. }
  4692. CertFreeCertificateContext(certContext);
  4693. }
  4694. CertCloseStore(certStore, 0);
  4695. }
  4696. }
  4697. }
  4698. }
  4699. }
  4700. CloseHandle(certFile);
  4701. }
  4702. return thumbprint;
  4703. }
  4704. }
  4705. void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile(
  4706. Elem& e0)
  4707. {
  4708. if ((this->GlobalGenerator->TargetsWindowsStore() ||
  4709. this->GlobalGenerator->TargetsWindowsPhone()) &&
  4710. (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
  4711. std::string pfxFile;
  4712. for (cmGeneratorTarget::AllConfigSource const& source :
  4713. this->GeneratorTarget->GetAllConfigSources()) {
  4714. if (source.Kind == cmGeneratorTarget::SourceKindCertificate) {
  4715. pfxFile = this->ConvertPath(source.Source->GetFullPath(), false);
  4716. ConvertToWindowsSlash(pfxFile);
  4717. break;
  4718. }
  4719. }
  4720. if (this->IsMissingFiles &&
  4721. !(this->GlobalGenerator->TargetsWindowsPhone() &&
  4722. this->GlobalGenerator->GetSystemVersion() == "8.0"_s)) {
  4723. // Move the manifest to a project directory to avoid clashes
  4724. std::string artifactDir =
  4725. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4726. ConvertToWindowsSlash(artifactDir);
  4727. Elem e1(e0, "PropertyGroup");
  4728. e1.Element("AppxPackageArtifactsDir", cmStrCat(artifactDir, '\\'));
  4729. std::string resourcePriFile =
  4730. cmStrCat(this->DefaultArtifactDir, "/resources.pri");
  4731. ConvertToWindowsSlash(resourcePriFile);
  4732. e1.Element("ProjectPriFullPath", resourcePriFile);
  4733. // If we are missing files and we don't have a certificate and
  4734. // aren't targeting WP8.0, add a default certificate
  4735. if (pfxFile.empty()) {
  4736. std::string templateFolder =
  4737. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  4738. pfxFile =
  4739. cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
  4740. cmSystemTools::CopyAFile(
  4741. cmStrCat(templateFolder, "/Windows_TemporaryKey.pfx"), pfxFile,
  4742. false);
  4743. ConvertToWindowsSlash(pfxFile);
  4744. this->AddedFiles.push_back(pfxFile);
  4745. this->AddedDefaultCertificate = true;
  4746. }
  4747. e1.Element("PackageCertificateKeyFile", pfxFile);
  4748. std::string thumb = ComputeCertificateThumbprint(pfxFile);
  4749. if (!thumb.empty()) {
  4750. e1.Element("PackageCertificateThumbprint", thumb);
  4751. }
  4752. } else if (!pfxFile.empty()) {
  4753. Elem e1(e0, "PropertyGroup");
  4754. e1.Element("PackageCertificateKeyFile", pfxFile);
  4755. std::string thumb = ComputeCertificateThumbprint(pfxFile);
  4756. if (!thumb.empty()) {
  4757. e1.Element("PackageCertificateThumbprint", thumb);
  4758. }
  4759. }
  4760. }
  4761. }
  4762. void cmVisualStudio10TargetGenerator::ClassifyAllConfigSources()
  4763. {
  4764. for (cmGeneratorTarget::AllConfigSource const& source :
  4765. this->GeneratorTarget->GetAllConfigSources()) {
  4766. this->ClassifyAllConfigSource(source);
  4767. }
  4768. }
  4769. void cmVisualStudio10TargetGenerator::ClassifyAllConfigSource(
  4770. cmGeneratorTarget::AllConfigSource const& acs)
  4771. {
  4772. switch (acs.Kind) {
  4773. case cmGeneratorTarget::SourceKindResx: {
  4774. // Build and save the name of the corresponding .h file
  4775. // This relationship will be used later when building the project files.
  4776. // Both names would have been auto generated from Visual Studio
  4777. // where the user supplied the file name and Visual Studio
  4778. // appended the suffix.
  4779. std::string resx = acs.Source->ResolveFullPath();
  4780. std::string hFileName =
  4781. cmStrCat(resx.substr(0, resx.find_last_of('.')), ".h");
  4782. this->ExpectedResxHeaders.insert(hFileName);
  4783. } break;
  4784. case cmGeneratorTarget::SourceKindXaml: {
  4785. // Build and save the name of the corresponding .h and .cpp file
  4786. // This relationship will be used later when building the project files.
  4787. // Both names would have been auto generated from Visual Studio
  4788. // where the user supplied the file name and Visual Studio
  4789. // appended the suffix.
  4790. std::string xaml = acs.Source->ResolveFullPath();
  4791. std::string hFileName = cmStrCat(xaml, ".h");
  4792. std::string cppFileName = cmStrCat(xaml, ".cpp");
  4793. this->ExpectedXamlHeaders.insert(hFileName);
  4794. this->ExpectedXamlSources.insert(cppFileName);
  4795. } break;
  4796. default:
  4797. break;
  4798. }
  4799. }
  4800. bool cmVisualStudio10TargetGenerator::IsResxHeader(
  4801. const std::string& headerFile)
  4802. {
  4803. return this->ExpectedResxHeaders.count(headerFile) > 0;
  4804. }
  4805. bool cmVisualStudio10TargetGenerator::IsXamlHeader(
  4806. const std::string& headerFile)
  4807. {
  4808. return this->ExpectedXamlHeaders.count(headerFile) > 0;
  4809. }
  4810. bool cmVisualStudio10TargetGenerator::IsXamlSource(
  4811. const std::string& sourceFile)
  4812. {
  4813. return this->ExpectedXamlSources.count(sourceFile) > 0;
  4814. }
  4815. void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1)
  4816. {
  4817. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  4818. bool isAppContainer = false;
  4819. bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
  4820. bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
  4821. bool const isAndroid = this->GlobalGenerator->TargetsAndroid();
  4822. std::string const& rev = this->GlobalGenerator->GetApplicationTypeRevision();
  4823. if (isWindowsPhone || isWindowsStore) {
  4824. e1.Element("ApplicationType",
  4825. (isWindowsPhone ? "Windows Phone" : "Windows Store"));
  4826. e1.Element("DefaultLanguage", "en-US");
  4827. if (rev == "10.0"_s) {
  4828. e1.Element("ApplicationTypeRevision", rev);
  4829. // Visual Studio 14.0 is necessary for building 10.0 apps
  4830. e1.Element("MinimumVisualStudioVersion", "14.0");
  4831. if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4832. isAppContainer = true;
  4833. }
  4834. } else if (rev == "8.1"_s) {
  4835. e1.Element("ApplicationTypeRevision", rev);
  4836. // Visual Studio 12.0 is necessary for building 8.1 apps
  4837. e1.Element("MinimumVisualStudioVersion", "12.0");
  4838. if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4839. isAppContainer = true;
  4840. }
  4841. } else if (rev == "8.0"_s) {
  4842. e1.Element("ApplicationTypeRevision", rev);
  4843. // Visual Studio 11.0 is necessary for building 8.0 apps
  4844. e1.Element("MinimumVisualStudioVersion", "11.0");
  4845. if (isWindowsStore &&
  4846. this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4847. isAppContainer = true;
  4848. } else if (isWindowsPhone &&
  4849. this->GeneratorTarget->GetType() ==
  4850. cmStateEnums::EXECUTABLE) {
  4851. e1.Element("XapOutputs", "true");
  4852. e1.Element("XapFilename",
  4853. cmStrCat(this->Name, "_$(Configuration)_$(Platform).xap"));
  4854. }
  4855. }
  4856. } else if (isAndroid) {
  4857. e1.Element("ApplicationType", "Android");
  4858. e1.Element("ApplicationTypeRevision",
  4859. gg->GetAndroidApplicationTypeRevision());
  4860. }
  4861. if (isAppContainer) {
  4862. e1.Element("AppContainerApplication", "true");
  4863. } else if (!isAndroid) {
  4864. if (this->Platform == "ARM64"_s) {
  4865. e1.Element("WindowsSDKDesktopARM64Support", "true");
  4866. } else if (this->Platform == "ARM"_s) {
  4867. e1.Element("WindowsSDKDesktopARMSupport", "true");
  4868. }
  4869. }
  4870. std::string const& targetPlatformVersion =
  4871. gg->GetWindowsTargetPlatformVersion();
  4872. if (!targetPlatformVersion.empty()) {
  4873. e1.Element("WindowsTargetPlatformVersion", targetPlatformVersion);
  4874. }
  4875. cmValue targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
  4876. "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
  4877. if (targetPlatformMinVersion) {
  4878. e1.Element("WindowsTargetPlatformMinVersion", *targetPlatformMinVersion);
  4879. } else if (isWindowsStore && rev == "10.0"_s) {
  4880. // If the min version is not set, then use the TargetPlatformVersion
  4881. if (!targetPlatformVersion.empty()) {
  4882. e1.Element("WindowsTargetPlatformMinVersion", targetPlatformVersion);
  4883. }
  4884. }
  4885. // Added IoT Startup Task support
  4886. if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
  4887. e1.Element("ContainsStartupTask", "true");
  4888. }
  4889. }
  4890. void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
  4891. {
  4892. // For Windows and Windows Phone executables, we will assume that if a
  4893. // manifest is not present that we need to add all the necessary files
  4894. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4895. std::vector<cmGeneratorTarget::AllConfigSource> manifestSources =
  4896. this->GeneratorTarget->GetAllConfigSources(
  4897. cmGeneratorTarget::SourceKindAppManifest);
  4898. std::string const& v = this->GlobalGenerator->GetSystemVersion();
  4899. if (this->GlobalGenerator->TargetsWindowsPhone()) {
  4900. if (v == "8.0"_s) {
  4901. // Look through the sources for WMAppManifest.xml
  4902. bool foundManifest = false;
  4903. for (cmGeneratorTarget::AllConfigSource const& source :
  4904. this->GeneratorTarget->GetAllConfigSources()) {
  4905. if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
  4906. "wmappmanifest.xml" ==
  4907. cmSystemTools::LowerCase(
  4908. source.Source->GetLocation().GetName())) {
  4909. foundManifest = true;
  4910. break;
  4911. }
  4912. }
  4913. if (!foundManifest) {
  4914. this->IsMissingFiles = true;
  4915. }
  4916. } else if (v == "8.1"_s) {
  4917. if (manifestSources.empty()) {
  4918. this->IsMissingFiles = true;
  4919. }
  4920. }
  4921. } else if (this->GlobalGenerator->TargetsWindowsStore()) {
  4922. if (manifestSources.empty()) {
  4923. if (v == "8.0"_s) {
  4924. this->IsMissingFiles = true;
  4925. } else if (v == "8.1"_s || cmHasLiteralPrefix(v, "10.0")) {
  4926. this->IsMissingFiles = true;
  4927. }
  4928. }
  4929. }
  4930. }
  4931. }
  4932. void cmVisualStudio10TargetGenerator::WriteMissingFiles(Elem& e1)
  4933. {
  4934. std::string const& v = this->GlobalGenerator->GetSystemVersion();
  4935. if (this->GlobalGenerator->TargetsWindowsPhone()) {
  4936. if (v == "8.0"_s) {
  4937. this->WriteMissingFilesWP80(e1);
  4938. } else if (v == "8.1"_s) {
  4939. this->WriteMissingFilesWP81(e1);
  4940. }
  4941. } else if (this->GlobalGenerator->TargetsWindowsStore()) {
  4942. if (v == "8.0"_s) {
  4943. this->WriteMissingFilesWS80(e1);
  4944. } else if (v == "8.1"_s) {
  4945. this->WriteMissingFilesWS81(e1);
  4946. } else if (cmHasLiteralPrefix(v, "10.0")) {
  4947. this->WriteMissingFilesWS10_0(e1);
  4948. }
  4949. }
  4950. }
  4951. void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80(Elem& e1)
  4952. {
  4953. std::string templateFolder =
  4954. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  4955. // For WP80, the manifest needs to be in the same folder as the project
  4956. // this can cause an overwrite problem if projects aren't organized in
  4957. // folders
  4958. std::string manifestFile = cmStrCat(
  4959. this->LocalGenerator->GetCurrentBinaryDirectory(), "/WMAppManifest.xml");
  4960. std::string artifactDir =
  4961. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4962. ConvertToWindowsSlash(artifactDir);
  4963. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  4964. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  4965. cmGeneratedFileStream fout(manifestFile);
  4966. fout.SetCopyIfDifferent(true);
  4967. /* clang-format off */
  4968. fout <<
  4969. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  4970. "<Deployment"
  4971. " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
  4972. " AppPlatformVersion=\"8.0\">\n"
  4973. "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
  4974. "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
  4975. " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
  4976. " Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"CMake\""
  4977. " Description=\"Default CMake App\" Publisher=\"CMake\""
  4978. " PublisherID=\"{" << this->GUID << "}\">\n"
  4979. "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
  4980. << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
  4981. "\t\t<Capabilities/>\n"
  4982. "\t\t<Tasks>\n"
  4983. "\t\t\t<DefaultTask Name=\"_default\""
  4984. " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
  4985. "\t\t</Tasks>\n"
  4986. "\t\t<Tokens>\n"
  4987. "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
  4988. " TaskName=\"_default\">\n"
  4989. "\t\t\t\t<TemplateFlip>\n"
  4990. "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
  4991. << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
  4992. "\t\t\t\t\t<Count>0</Count>\n"
  4993. "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
  4994. << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
  4995. "\t\t\t\t</TemplateFlip>\n"
  4996. "\t\t\t</PrimaryToken>\n"
  4997. "\t\t</Tokens>\n"
  4998. "\t\t<ScreenResolutions>\n"
  4999. "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
  5000. "\t\t</ScreenResolutions>\n"
  5001. "\t</App>\n"
  5002. "</Deployment>\n";
  5003. /* clang-format on */
  5004. std::string sourceFile = this->ConvertPath(manifestFile, false);
  5005. ConvertToWindowsSlash(sourceFile);
  5006. {
  5007. Elem e2(e1, "Xml");
  5008. e2.Attribute("Include", sourceFile);
  5009. e2.Element("SubType", "Designer");
  5010. }
  5011. this->AddedFiles.push_back(sourceFile);
  5012. std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
  5013. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
  5014. smallLogo, false);
  5015. ConvertToWindowsSlash(smallLogo);
  5016. Elem(e1, "Image").Attribute("Include", smallLogo);
  5017. this->AddedFiles.push_back(smallLogo);
  5018. std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
  5019. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
  5020. ConvertToWindowsSlash(logo);
  5021. Elem(e1, "Image").Attribute("Include", logo);
  5022. this->AddedFiles.push_back(logo);
  5023. std::string applicationIcon =
  5024. cmStrCat(this->DefaultArtifactDir, "/ApplicationIcon.png");
  5025. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/ApplicationIcon.png"),
  5026. applicationIcon, false);
  5027. ConvertToWindowsSlash(applicationIcon);
  5028. Elem(e1, "Image").Attribute("Include", applicationIcon);
  5029. this->AddedFiles.push_back(applicationIcon);
  5030. }
  5031. void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81(Elem& e1)
  5032. {
  5033. std::string manifestFile =
  5034. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5035. std::string artifactDir =
  5036. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5037. ConvertToWindowsSlash(artifactDir);
  5038. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5039. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5040. cmGeneratedFileStream fout(manifestFile);
  5041. fout.SetCopyIfDifferent(true);
  5042. /* clang-format off */
  5043. fout <<
  5044. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5045. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
  5046. " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
  5047. " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
  5048. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5049. " Version=\"1.0.0.0\" />\n"
  5050. "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
  5051. " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
  5052. "\t<Properties>\n"
  5053. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5054. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5055. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5056. "\t</Properties>\n"
  5057. "\t<Prerequisites>\n"
  5058. "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
  5059. "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
  5060. "\t</Prerequisites>\n"
  5061. "\t<Resources>\n"
  5062. "\t\t<Resource Language=\"x-generate\" />\n"
  5063. "\t</Resources>\n"
  5064. "\t<Applications>\n"
  5065. "\t\t<Application Id=\"App\""
  5066. " Executable=\"" << targetNameXML << ".exe\""
  5067. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5068. "\t\t\t<m2:VisualElements\n"
  5069. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5070. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5071. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5072. "\t\t\t\tForegroundText=\"light\"\n"
  5073. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5074. "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5075. "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
  5076. "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
  5077. "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
  5078. "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
  5079. "\t\t\t\t</m2:DefaultTile>\n"
  5080. "\t\t\t\t<m2:SplashScreen"
  5081. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5082. "\t\t\t</m2:VisualElements>\n"
  5083. "\t\t</Application>\n"
  5084. "\t</Applications>\n"
  5085. "</Package>\n";
  5086. /* clang-format on */
  5087. this->WriteCommonMissingFiles(e1, manifestFile);
  5088. }
  5089. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80(Elem& e1)
  5090. {
  5091. std::string manifestFile =
  5092. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5093. std::string artifactDir =
  5094. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5095. ConvertToWindowsSlash(artifactDir);
  5096. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5097. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5098. cmGeneratedFileStream fout(manifestFile);
  5099. fout.SetCopyIfDifferent(true);
  5100. /* clang-format off */
  5101. fout <<
  5102. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5103. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
  5104. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5105. " Version=\"1.0.0.0\" />\n"
  5106. "\t<Properties>\n"
  5107. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5108. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5109. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5110. "\t</Properties>\n"
  5111. "\t<Prerequisites>\n"
  5112. "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
  5113. "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
  5114. "\t</Prerequisites>\n"
  5115. "\t<Resources>\n"
  5116. "\t\t<Resource Language=\"x-generate\" />\n"
  5117. "\t</Resources>\n"
  5118. "\t<Applications>\n"
  5119. "\t\t<Application Id=\"App\""
  5120. " Executable=\"" << targetNameXML << ".exe\""
  5121. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5122. "\t\t\t<VisualElements"
  5123. " DisplayName=\"" << targetNameXML << "\""
  5124. " Description=\"" << targetNameXML << "\""
  5125. " BackgroundColor=\"#336699\" ForegroundText=\"light\""
  5126. " Logo=\"" << artifactDirXML << "\\Logo.png\""
  5127. " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5128. "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
  5129. " ShortName=\"" << targetNameXML << "\" />\n"
  5130. "\t\t\t\t<SplashScreen"
  5131. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5132. "\t\t\t</VisualElements>\n"
  5133. "\t\t</Application>\n"
  5134. "\t</Applications>\n"
  5135. "</Package>\n";
  5136. /* clang-format on */
  5137. this->WriteCommonMissingFiles(e1, manifestFile);
  5138. }
  5139. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81(Elem& e1)
  5140. {
  5141. std::string manifestFile =
  5142. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5143. std::string artifactDir =
  5144. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5145. ConvertToWindowsSlash(artifactDir);
  5146. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5147. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5148. cmGeneratedFileStream fout(manifestFile);
  5149. fout.SetCopyIfDifferent(true);
  5150. /* clang-format off */
  5151. fout <<
  5152. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5153. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
  5154. " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
  5155. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5156. " Version=\"1.0.0.0\" />\n"
  5157. "\t<Properties>\n"
  5158. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5159. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5160. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5161. "\t</Properties>\n"
  5162. "\t<Prerequisites>\n"
  5163. "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
  5164. "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
  5165. "\t</Prerequisites>\n"
  5166. "\t<Resources>\n"
  5167. "\t\t<Resource Language=\"x-generate\" />\n"
  5168. "\t</Resources>\n"
  5169. "\t<Applications>\n"
  5170. "\t\t<Application Id=\"App\""
  5171. " Executable=\"" << targetNameXML << ".exe\""
  5172. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5173. "\t\t\t<m2:VisualElements\n"
  5174. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5175. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5176. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5177. "\t\t\t\tForegroundText=\"light\"\n"
  5178. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5179. "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5180. "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
  5181. "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
  5182. "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
  5183. "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
  5184. "\t\t\t\t</m2:DefaultTile>\n"
  5185. "\t\t\t\t<m2:SplashScreen"
  5186. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5187. "\t\t\t</m2:VisualElements>\n"
  5188. "\t\t</Application>\n"
  5189. "\t</Applications>\n"
  5190. "</Package>\n";
  5191. /* clang-format on */
  5192. this->WriteCommonMissingFiles(e1, manifestFile);
  5193. }
  5194. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0(Elem& e1)
  5195. {
  5196. std::string manifestFile =
  5197. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5198. std::string artifactDir =
  5199. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5200. ConvertToWindowsSlash(artifactDir);
  5201. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5202. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5203. cmGeneratedFileStream fout(manifestFile);
  5204. fout.SetCopyIfDifferent(true);
  5205. /* clang-format off */
  5206. fout <<
  5207. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5208. "<Package\n\t"
  5209. "xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
  5210. "\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
  5211. "\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
  5212. "\n\tIgnorableNamespaces=\"uap mp\">\n\n"
  5213. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5214. " Version=\"1.0.0.0\" />\n"
  5215. "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
  5216. "\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
  5217. "\t<Properties>\n"
  5218. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5219. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5220. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5221. "\t</Properties>\n"
  5222. "\t<Dependencies>\n"
  5223. "\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
  5224. "MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
  5225. "\t</Dependencies>\n"
  5226. "\t<Resources>\n"
  5227. "\t\t<Resource Language=\"x-generate\" />\n"
  5228. "\t</Resources>\n"
  5229. "\t<Applications>\n"
  5230. "\t\t<Application Id=\"App\""
  5231. " Executable=\"" << targetNameXML << ".exe\""
  5232. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5233. "\t\t\t<uap:VisualElements\n"
  5234. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5235. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5236. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5237. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5238. "\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
  5239. "\\SmallLogo44x44.png\">\n"
  5240. "\t\t\t\t<uap:SplashScreen"
  5241. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5242. "\t\t\t</uap:VisualElements>\n"
  5243. "\t\t</Application>\n"
  5244. "\t</Applications>\n"
  5245. "</Package>\n";
  5246. /* clang-format on */
  5247. this->WriteCommonMissingFiles(e1, manifestFile);
  5248. }
  5249. void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
  5250. Elem& e1, const std::string& manifestFile)
  5251. {
  5252. std::string templateFolder =
  5253. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  5254. std::string sourceFile = this->ConvertPath(manifestFile, false);
  5255. ConvertToWindowsSlash(sourceFile);
  5256. {
  5257. Elem e2(e1, "AppxManifest");
  5258. e2.Attribute("Include", sourceFile);
  5259. e2.Element("SubType", "Designer");
  5260. }
  5261. this->AddedFiles.push_back(sourceFile);
  5262. std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
  5263. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
  5264. smallLogo, false);
  5265. ConvertToWindowsSlash(smallLogo);
  5266. Elem(e1, "Image").Attribute("Include", smallLogo);
  5267. this->AddedFiles.push_back(smallLogo);
  5268. std::string smallLogo44 =
  5269. cmStrCat(this->DefaultArtifactDir, "/SmallLogo44x44.png");
  5270. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo44x44.png"),
  5271. smallLogo44, false);
  5272. ConvertToWindowsSlash(smallLogo44);
  5273. Elem(e1, "Image").Attribute("Include", smallLogo44);
  5274. this->AddedFiles.push_back(smallLogo44);
  5275. std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
  5276. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
  5277. ConvertToWindowsSlash(logo);
  5278. Elem(e1, "Image").Attribute("Include", logo);
  5279. this->AddedFiles.push_back(logo);
  5280. std::string storeLogo = cmStrCat(this->DefaultArtifactDir, "/StoreLogo.png");
  5281. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/StoreLogo.png"),
  5282. storeLogo, false);
  5283. ConvertToWindowsSlash(storeLogo);
  5284. Elem(e1, "Image").Attribute("Include", storeLogo);
  5285. this->AddedFiles.push_back(storeLogo);
  5286. std::string splashScreen =
  5287. cmStrCat(this->DefaultArtifactDir, "/SplashScreen.png");
  5288. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SplashScreen.png"),
  5289. splashScreen, false);
  5290. ConvertToWindowsSlash(splashScreen);
  5291. Elem(e1, "Image").Attribute("Include", splashScreen);
  5292. this->AddedFiles.push_back(splashScreen);
  5293. if (this->AddedDefaultCertificate) {
  5294. // This file has already been added to the build so don't copy it
  5295. std::string keyFile =
  5296. cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
  5297. ConvertToWindowsSlash(keyFile);
  5298. Elem(e1, "None").Attribute("Include", keyFile);
  5299. }
  5300. }
  5301. bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
  5302. {
  5303. HANDLE h =
  5304. CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
  5305. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
  5306. FILE_FLAG_BACKUP_SEMANTICS, 0);
  5307. if (!h) {
  5308. return false;
  5309. }
  5310. FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
  5311. if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
  5312. CloseHandle(h);
  5313. return false;
  5314. }
  5315. CloseHandle(h);
  5316. return true;
  5317. }
  5318. void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
  5319. cmSourceFile const* sf, std::map<std::string, std::string>& tags)
  5320. {
  5321. if (this->ProjectType == VsProjectType::csproj) {
  5322. const cmPropertyMap& props = sf->GetProperties();
  5323. for (const std::string& p : props.GetKeys()) {
  5324. static const cm::string_view propNamePrefix = "VS_CSHARP_";
  5325. if (cmHasPrefix(p, propNamePrefix)) {
  5326. std::string tagName = p.substr(propNamePrefix.length());
  5327. if (!tagName.empty()) {
  5328. cmValue val = props.GetPropertyValue(p);
  5329. if (cmNonempty(val)) {
  5330. tags[tagName] = *val;
  5331. } else {
  5332. tags.erase(tagName);
  5333. }
  5334. }
  5335. }
  5336. }
  5337. }
  5338. }
  5339. void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
  5340. Elem& e2, const std::map<std::string, std::string>& tags)
  5341. {
  5342. for (const auto& i : tags) {
  5343. e2.Element(i.first, i.second);
  5344. }
  5345. }
  5346. std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
  5347. cmSourceFile const* source)
  5348. {
  5349. // For out of source files, we first check if a matching source group
  5350. // for this file exists, otherwise we check if the path relative to current
  5351. // source- or binary-dir is used within the link and return that.
  5352. // In case of .cs files we can't do that automatically for files in the
  5353. // binary directory, because this leads to compilation errors.
  5354. std::string link;
  5355. std::string sourceGroupedFile;
  5356. std::string const& fullFileName = source->GetFullPath();
  5357. std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory();
  5358. std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory();
  5359. // unfortunately we have to copy the source groups, because
  5360. // FindSourceGroup uses a regex which is modifying the group
  5361. std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
  5362. cmSourceGroup* sourceGroup =
  5363. this->Makefile->FindSourceGroup(fullFileName, sourceGroups);
  5364. if (sourceGroup && !sourceGroup->GetFullName().empty()) {
  5365. sourceGroupedFile =
  5366. cmStrCat(sourceGroup->GetFullName(), '/',
  5367. cmsys::SystemTools::GetFilenameName(fullFileName));
  5368. cmsys::SystemTools::ConvertToUnixSlashes(sourceGroupedFile);
  5369. }
  5370. if (!sourceGroupedFile.empty() &&
  5371. cmHasSuffix(fullFileName, sourceGroupedFile)) {
  5372. link = sourceGroupedFile;
  5373. } else if (cmHasPrefix(fullFileName, srcDir)) {
  5374. link = fullFileName.substr(srcDir.length() + 1);
  5375. } else if (!cmHasSuffix(fullFileName, ".cs") &&
  5376. cmHasPrefix(fullFileName, binDir)) {
  5377. link = fullFileName.substr(binDir.length() + 1);
  5378. } else if (cmValue l = source->GetProperty("VS_CSHARP_Link")) {
  5379. link = *l;
  5380. }
  5381. ConvertToWindowsSlash(link);
  5382. return link;
  5383. }
  5384. std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
  5385. const char* relativeFilePath) const
  5386. {
  5387. // Always search in the standard modules location.
  5388. std::string path =
  5389. cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath);
  5390. ConvertToWindowsSlash(path);
  5391. return path;
  5392. }
  5393. void cmVisualStudio10TargetGenerator::WriteStdOutEncodingUtf8(Elem& e1)
  5394. {
  5395. if (this->GlobalGenerator->IsUtf8EncodingSupported()) {
  5396. e1.Element("UseUtf8Encoding", "Always");
  5397. } else if (this->GlobalGenerator->IsStdOutEncodingSupported()) {
  5398. e1.Element("StdOutEncoding", "UTF-8");
  5399. }
  5400. }
  5401. void cmVisualStudio10TargetGenerator::UpdateCache()
  5402. {
  5403. std::vector<std::string> packageReferences;
  5404. if (this->GeneratorTarget->HasPackageReferences()) {
  5405. // Store a cache entry that later determines, if a package restore is
  5406. // required.
  5407. this->GeneratorTarget->Makefile->AddCacheDefinition(
  5408. cmStrCat(this->GeneratorTarget->GetName(),
  5409. "_REQUIRES_VS_PACKAGE_RESTORE"),
  5410. "ON", "Value Computed by CMake", cmStateEnums::STATIC);
  5411. } else {
  5412. // If there are any dependencies that require package restore, inherit the
  5413. // cache variable.
  5414. cmGlobalGenerator::TargetDependSet const& unordered =
  5415. this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
  5416. using OrderedTargetDependSet =
  5417. cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
  5418. OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  5419. for (cmGeneratorTarget const* dt : depends) {
  5420. if (dt->HasPackageReferences()) {
  5421. this->GeneratorTarget->Makefile->AddCacheDefinition(
  5422. cmStrCat(this->GeneratorTarget->GetName(),
  5423. "_REQUIRES_VS_PACKAGE_RESTORE"),
  5424. "ON", "Value Computed by CMake", cmStateEnums::STATIC);
  5425. }
  5426. }
  5427. }
  5428. }