cmVisualStudio10TargetGenerator.cxx 211 KB

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