cmVisualStudio10TargetGenerator.cxx 210 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861
  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. this->CudaOptions[configName] = std::move(pOptions);
  3554. return true;
  3555. }
  3556. void cmVisualStudio10TargetGenerator::WriteCudaOptions(
  3557. Elem& e1, std::string const& configName)
  3558. {
  3559. if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled() ||
  3560. !this->GeneratorTarget->IsLanguageUsed("CUDA", configName)) {
  3561. return;
  3562. }
  3563. Elem e2(e1, "CudaCompile");
  3564. OptionsHelper cudaOptions(*(this->CudaOptions[configName]), e2);
  3565. cudaOptions.OutputAdditionalIncludeDirectories("CUDA");
  3566. cudaOptions.OutputPreprocessorDefinitions("CUDA");
  3567. cudaOptions.PrependInheritedString("AdditionalOptions");
  3568. cudaOptions.OutputFlagMap();
  3569. }
  3570. bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
  3571. {
  3572. if (!this->GlobalGenerator->IsCudaEnabled()) {
  3573. return true;
  3574. }
  3575. return std::all_of(
  3576. this->Configurations.begin(), this->Configurations.end(),
  3577. [this](std::string const& c) { return this->ComputeCudaLinkOptions(c); });
  3578. }
  3579. bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
  3580. std::string const& configName)
  3581. {
  3582. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3583. auto pOptions = cm::make_unique<Options>(
  3584. this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
  3585. Options& cudaLinkOptions = *pOptions;
  3586. cmGeneratorTarget::DeviceLinkSetter setter(*this->GeneratorTarget);
  3587. // Determine if we need to do a device link
  3588. const bool doDeviceLinking = requireDeviceLinking(
  3589. *this->GeneratorTarget, *this->LocalGenerator, configName);
  3590. cudaLinkOptions.AddFlag("PerformDeviceLink",
  3591. doDeviceLinking ? "true" : "false");
  3592. // Add extra flags for device linking
  3593. cudaLinkOptions.AppendFlagString(
  3594. "AdditionalOptions",
  3595. this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_FLAGS"));
  3596. cudaLinkOptions.AppendFlagString(
  3597. "AdditionalOptions",
  3598. this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS"));
  3599. std::vector<std::string> linkOpts;
  3600. std::string linkFlags;
  3601. this->GeneratorTarget->GetLinkOptions(linkOpts, configName, "CUDA");
  3602. // LINK_OPTIONS are escaped.
  3603. this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
  3604. cmComputeLinkInformation* pcli =
  3605. this->GeneratorTarget->GetLinkInformation(configName);
  3606. if (doDeviceLinking && pcli) {
  3607. cmLinkLineDeviceComputer computer(
  3608. this->LocalGenerator,
  3609. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  3610. std::string ignored_;
  3611. this->LocalGenerator->GetDeviceLinkFlags(computer, configName, ignored_,
  3612. linkFlags, ignored_, ignored_,
  3613. this->GeneratorTarget);
  3614. this->LocalGenerator->AddLanguageFlagsForLinking(
  3615. linkFlags, this->GeneratorTarget, "CUDA", configName);
  3616. }
  3617. cudaLinkOptions.AppendFlagString("AdditionalOptions", linkFlags);
  3618. if (doDeviceLinking) {
  3619. std::vector<std::string> libVec;
  3620. auto const& kinded = this->GeneratorTarget->GetKindedSources(configName);
  3621. // CMake conversion uses full paths when possible to allow deeper trees.
  3622. // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
  3623. // we must use relative paths.
  3624. const bool forceRelative = true;
  3625. for (cmGeneratorTarget::SourceAndKind const& si : kinded.Sources) {
  3626. switch (si.Kind) {
  3627. case cmGeneratorTarget::SourceKindExternalObject: {
  3628. std::string path =
  3629. this->ConvertPath(si.Source.Value->GetFullPath(), forceRelative);
  3630. ConvertToWindowsSlash(path);
  3631. libVec.emplace_back(std::move(path));
  3632. } break;
  3633. default:
  3634. break;
  3635. }
  3636. }
  3637. // For static libraries that have device linking enabled compute
  3638. // the libraries
  3639. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3640. cmComputeLinkInformation& cli = *pcli;
  3641. cmLinkLineDeviceComputer computer(
  3642. this->LocalGenerator,
  3643. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  3644. std::vector<BT<std::string>> btLibVec;
  3645. computer.ComputeLinkLibraries(cli, std::string{}, btLibVec);
  3646. for (auto const& item : btLibVec) {
  3647. libVec.emplace_back(item.Value);
  3648. }
  3649. }
  3650. if (!libVec.empty()) {
  3651. cudaLinkOptions.AddFlag("AdditionalDependencies", libVec);
  3652. }
  3653. }
  3654. this->CudaLinkOptions[configName] = std::move(pOptions);
  3655. return true;
  3656. }
  3657. void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
  3658. Elem& e1, std::string const& configName)
  3659. {
  3660. // We need to write link options for OBJECT libraries so that
  3661. // we override the default device link behavior ( enabled ) when
  3662. // building object libraries with ptx/optix-ir/etc
  3663. if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  3664. return;
  3665. }
  3666. if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
  3667. return;
  3668. }
  3669. Elem e2(e1, "CudaLink");
  3670. OptionsHelper cudaLinkOptions(*(this->CudaLinkOptions[configName]), e2);
  3671. cudaLinkOptions.OutputFlagMap();
  3672. }
  3673. bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions()
  3674. {
  3675. if (!this->GlobalGenerator->IsMarmasmEnabled()) {
  3676. return true;
  3677. }
  3678. return std::all_of(
  3679. this->Configurations.begin(), this->Configurations.end(),
  3680. [this](std::string const& c) { return this->ComputeMarmasmOptions(c); });
  3681. }
  3682. bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions(
  3683. std::string const& configName)
  3684. {
  3685. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3686. auto pOptions = cm::make_unique<Options>(
  3687. this->LocalGenerator, Options::MarmasmCompiler, gg->GetMarmasmFlagTable());
  3688. Options& marmasmOptions = *pOptions;
  3689. std::string flags;
  3690. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3691. cmBuildStep::Compile, "ASM_MARMASM",
  3692. configName);
  3693. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3694. "ASM_MARMASM", configName);
  3695. marmasmOptions.Parse(flags);
  3696. // Get includes for this target
  3697. marmasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MARMASM"));
  3698. this->MarmasmOptions[configName] = std::move(pOptions);
  3699. return true;
  3700. }
  3701. void cmVisualStudio10TargetGenerator::WriteMarmasmOptions(
  3702. Elem& e1, std::string const& configName)
  3703. {
  3704. if (!this->MSTools || !this->GlobalGenerator->IsMarmasmEnabled()) {
  3705. return;
  3706. }
  3707. Elem e2(e1, "MARMASM");
  3708. // Preprocessor definitions and includes are shared with clOptions.
  3709. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3710. clOptions.OutputPreprocessorDefinitions("ASM_MARMASM");
  3711. OptionsHelper marmasmOptions(*(this->MarmasmOptions[configName]), e2);
  3712. marmasmOptions.OutputAdditionalIncludeDirectories("ASM_MARMASM");
  3713. marmasmOptions.PrependInheritedString("AdditionalOptions");
  3714. marmasmOptions.OutputFlagMap();
  3715. }
  3716. bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
  3717. {
  3718. if (!this->GlobalGenerator->IsMasmEnabled()) {
  3719. return true;
  3720. }
  3721. return std::all_of(
  3722. this->Configurations.begin(), this->Configurations.end(),
  3723. [this](std::string const& c) { return this->ComputeMasmOptions(c); });
  3724. }
  3725. bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
  3726. std::string const& configName)
  3727. {
  3728. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3729. auto pOptions = cm::make_unique<Options>(
  3730. this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
  3731. Options& masmOptions = *pOptions;
  3732. // MSBuild enables debug information by default.
  3733. // Disable it explicitly unless a flag parsed below re-enables it.
  3734. masmOptions.AddFlag("GenerateDebugInformation", "false");
  3735. std::string flags;
  3736. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3737. cmBuildStep::Compile, "ASM_MASM",
  3738. configName);
  3739. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3740. "ASM_MASM", configName);
  3741. masmOptions.Parse(flags);
  3742. // Get includes for this target
  3743. masmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MASM"));
  3744. this->MasmOptions[configName] = std::move(pOptions);
  3745. return true;
  3746. }
  3747. void cmVisualStudio10TargetGenerator::WriteMasmOptions(
  3748. Elem& e1, std::string const& configName)
  3749. {
  3750. if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
  3751. return;
  3752. }
  3753. Elem e2(e1, "MASM");
  3754. // Preprocessor definitions and includes are shared with clOptions.
  3755. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3756. clOptions.OutputPreprocessorDefinitions("ASM_MASM");
  3757. OptionsHelper masmOptions(*(this->MasmOptions[configName]), e2);
  3758. masmOptions.OutputAdditionalIncludeDirectories("ASM_MASM");
  3759. masmOptions.PrependInheritedString("AdditionalOptions");
  3760. masmOptions.OutputFlagMap();
  3761. }
  3762. bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
  3763. {
  3764. if (!this->GlobalGenerator->IsNasmEnabled()) {
  3765. return true;
  3766. }
  3767. return std::all_of(
  3768. this->Configurations.begin(), this->Configurations.end(),
  3769. [this](std::string const& c) { return this->ComputeNasmOptions(c); });
  3770. }
  3771. bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
  3772. std::string const& configName)
  3773. {
  3774. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3775. auto pOptions = cm::make_unique<Options>(
  3776. this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
  3777. Options& nasmOptions = *pOptions;
  3778. std::string flags;
  3779. this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
  3780. cmBuildStep::Compile, "ASM_NASM",
  3781. configName);
  3782. this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
  3783. "ASM_NASM", configName);
  3784. flags += " -f";
  3785. flags += this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_OBJECT_FORMAT");
  3786. nasmOptions.Parse(flags);
  3787. // Get includes for this target
  3788. nasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_NASM"));
  3789. this->NasmOptions[configName] = std::move(pOptions);
  3790. return true;
  3791. }
  3792. void cmVisualStudio10TargetGenerator::WriteNasmOptions(
  3793. Elem& e1, std::string const& configName)
  3794. {
  3795. if (!this->GlobalGenerator->IsNasmEnabled()) {
  3796. return;
  3797. }
  3798. Elem e2(e1, "NASM");
  3799. OptionsHelper nasmOptions(*(this->NasmOptions[configName]), e2);
  3800. nasmOptions.OutputAdditionalIncludeDirectories("ASM_NASM");
  3801. nasmOptions.OutputFlagMap();
  3802. nasmOptions.PrependInheritedString("AdditionalOptions");
  3803. nasmOptions.OutputPreprocessorDefinitions("ASM_NASM");
  3804. // Preprocessor definitions and includes are shared with clOptions.
  3805. OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
  3806. clOptions.OutputPreprocessorDefinitions("ASM_NASM");
  3807. }
  3808. void cmVisualStudio10TargetGenerator::WriteLibOptions(
  3809. Elem& e1, std::string const& config)
  3810. {
  3811. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3812. this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  3813. return;
  3814. }
  3815. const std::string& linkLanguage =
  3816. this->GeneratorTarget->GetLinkClosure(config)->LinkerLanguage;
  3817. std::string libflags;
  3818. this->LocalGenerator->GetStaticLibraryFlags(libflags, config, linkLanguage,
  3819. this->GeneratorTarget);
  3820. if (!libflags.empty()) {
  3821. Elem e2(e1, "Lib");
  3822. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3823. cmVS10GeneratorOptions libOptions(this->LocalGenerator,
  3824. cmVisualStudioGeneratorOptions::Linker,
  3825. gg->GetLibFlagTable(), this);
  3826. libOptions.Parse(libflags);
  3827. OptionsHelper oh(libOptions, e2);
  3828. oh.PrependInheritedString("AdditionalOptions");
  3829. oh.OutputFlagMap();
  3830. }
  3831. // We cannot generate metadata for static libraries. WindowsPhone
  3832. // and WindowsStore tools look at GenerateWindowsMetadata in the
  3833. // Link tool options even for static libraries.
  3834. if (this->GlobalGenerator->TargetsWindowsPhone() ||
  3835. this->GlobalGenerator->TargetsWindowsStore()) {
  3836. Elem e2(e1, "Link");
  3837. e2.Element("GenerateWindowsMetadata", "false");
  3838. }
  3839. }
  3840. void cmVisualStudio10TargetGenerator::WriteManifestOptions(
  3841. Elem& e1, std::string const& config)
  3842. {
  3843. if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
  3844. this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3845. this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
  3846. return;
  3847. }
  3848. std::vector<cmSourceFile const*> manifest_srcs;
  3849. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  3850. cmValue dpiAware = this->GeneratorTarget->GetProperty("VS_DPI_AWARE");
  3851. if (!manifest_srcs.empty() || dpiAware) {
  3852. Elem e2(e1, "Manifest");
  3853. if (!manifest_srcs.empty()) {
  3854. std::ostringstream oss;
  3855. for (cmSourceFile const* mi : manifest_srcs) {
  3856. std::string m = this->ConvertPath(mi->GetFullPath(), false);
  3857. ConvertToWindowsSlash(m);
  3858. oss << m << ";";
  3859. }
  3860. e2.Element("AdditionalManifestFiles", oss.str());
  3861. }
  3862. if (dpiAware) {
  3863. if (*dpiAware == "PerMonitor"_s) {
  3864. e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware");
  3865. } else if (dpiAware.IsOn()) {
  3866. e2.Element("EnableDpiAwareness", "true");
  3867. } else if (dpiAware.IsOff()) {
  3868. e2.Element("EnableDpiAwareness", "false");
  3869. } else {
  3870. cmSystemTools::Error(
  3871. cmStrCat("Bad parameter for VS_DPI_AWARE: ", *dpiAware));
  3872. }
  3873. }
  3874. }
  3875. }
  3876. void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
  3877. Elem& e1, std::string const& configName)
  3878. {
  3879. // Look through the sources for AndroidManifest.xml and use
  3880. // its location as the root source directory.
  3881. std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
  3882. {
  3883. for (cmGeneratorTarget::AllConfigSource const& source :
  3884. this->GeneratorTarget->GetAllConfigSources()) {
  3885. if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
  3886. "androidmanifest.xml" ==
  3887. cmSystemTools::LowerCase(source.Source->GetLocation().GetName())) {
  3888. rootDir = source.Source->GetLocation().GetDirectory();
  3889. break;
  3890. }
  3891. }
  3892. }
  3893. // Tell MSBuild to launch Ant.
  3894. Elem e2(e1, "AntBuild");
  3895. {
  3896. std::string antBuildPath = rootDir;
  3897. ConvertToWindowsSlash(antBuildPath);
  3898. e2.Element("AntBuildPath", antBuildPath);
  3899. }
  3900. if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
  3901. e2.Element("SkipAntStep", "true");
  3902. }
  3903. if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
  3904. e2.Element("EnableProGuard", "true");
  3905. }
  3906. if (cmValue proGuardConfigLocation =
  3907. this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
  3908. e2.Element("ProGuardConfigLocation", *proGuardConfigLocation);
  3909. }
  3910. if (cmValue securePropertiesLocation =
  3911. this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
  3912. e2.Element("SecurePropertiesLocation", *securePropertiesLocation);
  3913. }
  3914. if (cmValue nativeLibDirectoriesExpression =
  3915. this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
  3916. std::string nativeLibDirs = cmGeneratorExpression::Evaluate(
  3917. *nativeLibDirectoriesExpression, this->LocalGenerator, configName);
  3918. e2.Element("NativeLibDirectories", nativeLibDirs);
  3919. }
  3920. if (cmValue nativeLibDependenciesExpression =
  3921. this->GeneratorTarget->GetProperty(
  3922. "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
  3923. std::string nativeLibDeps = cmGeneratorExpression::Evaluate(
  3924. *nativeLibDependenciesExpression, this->LocalGenerator, configName);
  3925. e2.Element("NativeLibDependencies", nativeLibDeps);
  3926. }
  3927. if (cmValue javaSourceDir =
  3928. this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
  3929. e2.Element("JavaSourceDir", *javaSourceDir);
  3930. }
  3931. if (cmValue jarDirectoriesExpression =
  3932. this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
  3933. std::string jarDirectories = cmGeneratorExpression::Evaluate(
  3934. *jarDirectoriesExpression, this->LocalGenerator, configName);
  3935. e2.Element("JarDirectories", jarDirectories);
  3936. }
  3937. if (cmValue jarDeps =
  3938. this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
  3939. e2.Element("JarDependencies", *jarDeps);
  3940. }
  3941. if (cmValue assetsDirectories =
  3942. this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
  3943. e2.Element("AssetsDirectories", *assetsDirectories);
  3944. }
  3945. {
  3946. std::string manifest_xml = cmStrCat(rootDir, "/AndroidManifest.xml");
  3947. ConvertToWindowsSlash(manifest_xml);
  3948. e2.Element("AndroidManifestLocation", manifest_xml);
  3949. }
  3950. if (cmValue antAdditionalOptions =
  3951. this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
  3952. e2.Element("AdditionalOptions",
  3953. cmStrCat(*antAdditionalOptions, " %(AdditionalOptions)"));
  3954. }
  3955. }
  3956. bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
  3957. {
  3958. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  3959. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3960. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3961. for (std::string const& c : this->Configurations) {
  3962. if (!this->ComputeLinkOptions(c)) {
  3963. return false;
  3964. }
  3965. }
  3966. }
  3967. return true;
  3968. }
  3969. bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
  3970. std::string const& config)
  3971. {
  3972. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  3973. auto pOptions = cm::make_unique<Options>(
  3974. this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this);
  3975. Options& linkOptions = *pOptions;
  3976. cmGeneratorTarget::LinkClosure const* linkClosure =
  3977. this->GeneratorTarget->GetLinkClosure(config);
  3978. const std::string& linkLanguage = linkClosure->LinkerLanguage;
  3979. if (linkLanguage.empty()) {
  3980. cmSystemTools::Error(cmStrCat(
  3981. "CMake can not determine linker language for target: ", this->Name));
  3982. return false;
  3983. }
  3984. std::string CONFIG = cmSystemTools::UpperCase(config);
  3985. const char* linkType = "SHARED";
  3986. if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3987. linkType = "MODULE";
  3988. }
  3989. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  3990. linkType = "EXE";
  3991. }
  3992. std::string flags;
  3993. std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS");
  3994. flags += ' ';
  3995. flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase);
  3996. std::string linkFlagVar = cmStrCat(linkFlagVarBase, '_', CONFIG);
  3997. flags += ' ';
  3998. flags += this->Makefile->GetRequiredDefinition(linkFlagVar);
  3999. cmValue targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS");
  4000. if (targetLinkFlags) {
  4001. flags += ' ';
  4002. flags += *targetLinkFlags;
  4003. }
  4004. std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG);
  4005. if (cmValue flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) {
  4006. flags += ' ';
  4007. flags += *flagsConfig;
  4008. }
  4009. std::vector<std::string> opts;
  4010. this->GeneratorTarget->GetLinkOptions(opts, config, linkLanguage);
  4011. // LINK_OPTIONS are escaped.
  4012. this->LocalGenerator->AppendCompileOptions(flags, opts);
  4013. cmComputeLinkInformation* pcli =
  4014. this->GeneratorTarget->GetLinkInformation(config);
  4015. if (!pcli) {
  4016. cmSystemTools::Error(
  4017. cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
  4018. this->Name));
  4019. return false;
  4020. }
  4021. cmComputeLinkInformation& cli = *pcli;
  4022. std::vector<std::string> libVec;
  4023. std::vector<std::string> vsTargetVec;
  4024. this->AddLibraries(cli, libVec, vsTargetVec, config);
  4025. std::string standardLibsVar =
  4026. cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
  4027. std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar);
  4028. cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
  4029. linkOptions.AddFlag("AdditionalDependencies", libVec);
  4030. // Populate TargetsFileAndConfigsVec
  4031. for (std::string const& ti : vsTargetVec) {
  4032. this->AddTargetsFileAndConfigPair(ti, config);
  4033. }
  4034. std::vector<std::string> const& ldirs = cli.GetDirectories();
  4035. std::vector<std::string> linkDirs;
  4036. for (std::string const& d : ldirs) {
  4037. // first just full path
  4038. linkDirs.push_back(d);
  4039. // next path with configuration type Debug, Release, etc
  4040. linkDirs.emplace_back(cmStrCat(d, "/$(Configuration)"));
  4041. }
  4042. linkDirs.push_back("%(AdditionalLibraryDirectories)");
  4043. linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
  4044. cmGeneratorTarget::Names targetNames;
  4045. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4046. targetNames = this->GeneratorTarget->GetExecutableNames(config);
  4047. } else {
  4048. targetNames = this->GeneratorTarget->GetLibraryNames(config);
  4049. }
  4050. if (this->MSTools) {
  4051. if (this->GeneratorTarget->IsWin32Executable(config)) {
  4052. if (this->GlobalGenerator->TargetsWindowsCE()) {
  4053. linkOptions.AddFlag("SubSystem", "WindowsCE");
  4054. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4055. if (this->ClOptions[config]->UsingUnicode()) {
  4056. linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
  4057. } else {
  4058. linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
  4059. }
  4060. }
  4061. } else {
  4062. linkOptions.AddFlag("SubSystem", "Windows");
  4063. }
  4064. } else {
  4065. if (this->GlobalGenerator->TargetsWindowsCE()) {
  4066. linkOptions.AddFlag("SubSystem", "WindowsCE");
  4067. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4068. if (this->ClOptions[config]->UsingUnicode()) {
  4069. linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
  4070. } else {
  4071. linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
  4072. }
  4073. }
  4074. } else {
  4075. linkOptions.AddFlag("SubSystem", "Console");
  4076. };
  4077. }
  4078. if (cmValue stackVal = this->Makefile->GetDefinition(
  4079. cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"))) {
  4080. linkOptions.AddFlag("StackReserveSize", *stackVal);
  4081. }
  4082. linkOptions.AddFlag("GenerateDebugInformation", "false");
  4083. std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config),
  4084. '/', targetNames.PDB);
  4085. if (!targetNames.ImportLibrary.empty()) {
  4086. std::string imLib =
  4087. cmStrCat(this->GeneratorTarget->GetDirectory(
  4088. config, cmStateEnums::ImportLibraryArtifact),
  4089. '/', targetNames.ImportLibrary);
  4090. linkOptions.AddFlag("ImportLibrary", imLib);
  4091. }
  4092. linkOptions.AddFlag("ProgramDataBaseFile", pdb);
  4093. // A Windows Runtime component uses internal .NET metadata,
  4094. // so does not have an import library.
  4095. if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
  4096. this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
  4097. linkOptions.AddFlag("GenerateWindowsMetadata", "true");
  4098. } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
  4099. this->GlobalGenerator->TargetsWindowsStore()) {
  4100. // WindowsPhone and WindowsStore components are in an app container
  4101. // and produce WindowsMetadata. If we are not producing a WINRT
  4102. // component, then do not generate the metadata here.
  4103. linkOptions.AddFlag("GenerateWindowsMetadata", "false");
  4104. }
  4105. if (this->GlobalGenerator->TargetsWindowsPhone() &&
  4106. this->GlobalGenerator->GetSystemVersion() == "8.0"_s) {
  4107. // WindowsPhone 8.0 does not have ole32.
  4108. linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
  4109. }
  4110. } else if (this->NsightTegra) {
  4111. linkOptions.AddFlag("SoName", targetNames.SharedObject);
  4112. }
  4113. linkOptions.Parse(flags);
  4114. linkOptions.FixManifestUACFlags();
  4115. if (this->MSTools) {
  4116. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  4117. this->GeneratorTarget->GetModuleDefinitionInfo(config);
  4118. if (mdi && !mdi->DefFile.empty()) {
  4119. linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile);
  4120. }
  4121. linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
  4122. "%(IgnoreSpecificDefaultLibraries)");
  4123. }
  4124. // VS 2015 without all updates has a v140 toolset whose
  4125. // GenerateDebugInformation expects No/Debug instead of false/true.
  4126. if (gg->GetPlatformToolsetNeedsDebugEnum()) {
  4127. if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
  4128. if (strcmp(debug, "false") == 0) {
  4129. linkOptions.AddFlag("GenerateDebugInformation", "No");
  4130. } else if (strcmp(debug, "true") == 0) {
  4131. linkOptions.AddFlag("GenerateDebugInformation", "Debug");
  4132. }
  4133. }
  4134. }
  4135. // Managed code cannot be linked with /DEBUG:FASTLINK
  4136. if (this->Managed) {
  4137. if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
  4138. if (strcmp(debug, "DebugFastLink") == 0) {
  4139. linkOptions.AddFlag("GenerateDebugInformation", "Debug");
  4140. }
  4141. }
  4142. }
  4143. this->LinkOptions[config] = std::move(pOptions);
  4144. return true;
  4145. }
  4146. bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
  4147. {
  4148. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4149. for (std::string const& c : this->Configurations) {
  4150. if (!this->ComputeLibOptions(c)) {
  4151. return false;
  4152. }
  4153. }
  4154. }
  4155. return true;
  4156. }
  4157. bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
  4158. std::string const& config)
  4159. {
  4160. cmComputeLinkInformation* pcli =
  4161. this->GeneratorTarget->GetLinkInformation(config);
  4162. if (!pcli) {
  4163. cmSystemTools::Error(
  4164. cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
  4165. this->Name));
  4166. return false;
  4167. }
  4168. cmComputeLinkInformation& cli = *pcli;
  4169. using ItemVector = cmComputeLinkInformation::ItemVector;
  4170. const ItemVector& libs = cli.GetItems();
  4171. for (cmComputeLinkInformation::Item const& l : libs) {
  4172. if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  4173. cmVS10IsTargetsFile(l.Value.Value)) {
  4174. std::string path =
  4175. this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
  4176. ConvertToWindowsSlash(path);
  4177. this->AddTargetsFileAndConfigPair(path, config);
  4178. }
  4179. }
  4180. return true;
  4181. }
  4182. void cmVisualStudio10TargetGenerator::WriteLinkOptions(
  4183. Elem& e1, std::string const& config)
  4184. {
  4185. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4186. this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
  4187. return;
  4188. }
  4189. if (this->ProjectType == VsProjectType::csproj) {
  4190. return;
  4191. }
  4192. {
  4193. Elem e2(e1, "Link");
  4194. OptionsHelper linkOptions(*(this->LinkOptions[config]), e2);
  4195. linkOptions.PrependInheritedString("AdditionalOptions");
  4196. linkOptions.OutputFlagMap();
  4197. }
  4198. if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
  4199. this->GeneratorTarget)) {
  4200. Elem e2(e1, "ProjectReference");
  4201. e2.Element("LinkLibraryDependencies", "false");
  4202. }
  4203. }
  4204. void cmVisualStudio10TargetGenerator::AddLibraries(
  4205. const cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
  4206. std::vector<std::string>& vsTargetVec, const std::string& config)
  4207. {
  4208. using ItemVector = cmComputeLinkInformation::ItemVector;
  4209. ItemVector const& libs = cli.GetItems();
  4210. for (cmComputeLinkInformation::Item const& l : libs) {
  4211. if (l.Target) {
  4212. auto managedType = l.Target->GetManagedType(config);
  4213. if (managedType != cmGeneratorTarget::ManagedType::Native &&
  4214. this->GeneratorTarget->GetManagedType(config) !=
  4215. cmGeneratorTarget::ManagedType::Native &&
  4216. l.Target->IsImported() &&
  4217. l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  4218. auto location = l.Target->GetFullPath(config);
  4219. if (!location.empty()) {
  4220. ConvertToWindowsSlash(location);
  4221. switch (this->ProjectType) {
  4222. case VsProjectType::csproj:
  4223. // If the target we want to "link" to is an imported managed
  4224. // target and this is a C# project, we add a hint reference. This
  4225. // reference is written to project file in
  4226. // WriteDotNetReferences().
  4227. this->DotNetHintReferences[config].push_back(
  4228. DotNetHintReference(l.Target->GetName(), location));
  4229. break;
  4230. case VsProjectType::vcxproj:
  4231. // Add path of assembly to list of using-directories, so the
  4232. // managed assembly can be used by '#using <assembly.dll>' in
  4233. // code.
  4234. this->AdditionalUsingDirectories[config].insert(
  4235. cmSystemTools::GetFilenamePath(location));
  4236. break;
  4237. default:
  4238. // In .proj files, we wouldn't be referencing libraries.
  4239. break;
  4240. }
  4241. }
  4242. }
  4243. // Do not allow C# targets to be added to the LIB listing. LIB files are
  4244. // used for linking C++ dependencies. C# libraries do not have lib files.
  4245. // Instead, they compile down to C# reference libraries (DLL files). The
  4246. // `<ProjectReference>` elements added to the vcxproj are enough for the
  4247. // IDE to deduce the DLL file required by other C# projects that need its
  4248. // reference library.
  4249. if (managedType == cmGeneratorTarget::ManagedType::Managed) {
  4250. continue;
  4251. }
  4252. }
  4253. if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  4254. std::string path =
  4255. this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
  4256. ConvertToWindowsSlash(path);
  4257. if (cmVS10IsTargetsFile(l.Value.Value)) {
  4258. vsTargetVec.push_back(path);
  4259. } else {
  4260. libVec.push_back(l.HasFeature() ? l.GetFormattedItem(path).Value
  4261. : path);
  4262. }
  4263. } else if (!l.Target ||
  4264. (l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4265. l.Target->GetType() != cmStateEnums::OBJECT_LIBRARY)) {
  4266. libVec.push_back(l.Value.Value);
  4267. }
  4268. }
  4269. }
  4270. void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
  4271. std::string const& targetsFile, std::string const& config)
  4272. {
  4273. for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) {
  4274. if (cmSystemTools::ComparePath(targetsFile, i.File)) {
  4275. if (!cm::contains(i.Configs, config)) {
  4276. i.Configs.push_back(config);
  4277. }
  4278. return;
  4279. }
  4280. }
  4281. TargetsFileAndConfigs entry;
  4282. entry.File = targetsFile;
  4283. entry.Configs.push_back(config);
  4284. this->TargetsFileAndConfigsVec.push_back(entry);
  4285. }
  4286. void cmVisualStudio10TargetGenerator::WriteMidlOptions(
  4287. Elem& e1, std::string const& configName)
  4288. {
  4289. if (!this->MSTools) {
  4290. return;
  4291. }
  4292. if (this->ProjectType == VsProjectType::csproj) {
  4293. return;
  4294. }
  4295. if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
  4296. return;
  4297. }
  4298. // This processes *any* of the .idl files specified in the project's file
  4299. // list (and passed as the item metadata %(Filename) expressing the rule
  4300. // input filename) into output files at the per-config *build* dir
  4301. // ($(IntDir)) each.
  4302. //
  4303. // IOW, this MIDL section is intended to provide a fully generic syntax
  4304. // content suitable for most cases (read: if you get errors, then it's quite
  4305. // probable that the error is on your side of the .idl setup).
  4306. //
  4307. // Also, note that the marked-as-generated _i.c file in the Visual Studio
  4308. // generator case needs to be referred to as $(IntDir)\foo_i.c at the
  4309. // project's file list, otherwise the compiler-side processing won't pick it
  4310. // up (for non-directory form, it ends up looking in project binary dir
  4311. // only). Perhaps there's something to be done to make this more automatic
  4312. // on the CMake side?
  4313. std::vector<std::string> const includes =
  4314. this->GetIncludes(configName, "MIDL");
  4315. std::ostringstream oss;
  4316. for (std::string const& i : includes) {
  4317. oss << i << ";";
  4318. }
  4319. oss << "%(AdditionalIncludeDirectories)";
  4320. Elem e2(e1, "Midl");
  4321. e2.Element("AdditionalIncludeDirectories", oss.str());
  4322. e2.Element("OutputDirectory", "$(ProjectDir)/$(IntDir)");
  4323. e2.Element("HeaderFileName", "%(Filename).h");
  4324. e2.Element("TypeLibraryName", "%(Filename).tlb");
  4325. e2.Element("InterfaceIdentifierFileName", "%(Filename)_i.c");
  4326. e2.Element("ProxyFileName", "%(Filename)_p.c");
  4327. }
  4328. void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups(Elem& e0)
  4329. {
  4330. if (this->ProjectType == VsProjectType::csproj) {
  4331. return;
  4332. }
  4333. for (const std::string& c : this->Configurations) {
  4334. Elem e1(e0, "ItemDefinitionGroup");
  4335. e1.Attribute("Condition", this->CalcCondition(c));
  4336. // output cl compile flags <ClCompile></ClCompile>
  4337. if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  4338. this->WriteClOptions(e1, c);
  4339. // output rc compile flags <ResourceCompile></ResourceCompile>
  4340. this->WriteRCOptions(e1, c);
  4341. this->WriteCudaOptions(e1, c);
  4342. this->WriteMarmasmOptions(e1, c);
  4343. this->WriteMasmOptions(e1, c);
  4344. this->WriteNasmOptions(e1, c);
  4345. }
  4346. // output midl flags <Midl></Midl>
  4347. this->WriteMidlOptions(e1, c);
  4348. // write events
  4349. if (this->ProjectType != VsProjectType::csproj) {
  4350. this->WriteEvents(e1, c);
  4351. }
  4352. // output link flags <Link></Link>
  4353. this->WriteLinkOptions(e1, c);
  4354. this->WriteCudaLinkOptions(e1, c);
  4355. // output lib flags <Lib></Lib>
  4356. this->WriteLibOptions(e1, c);
  4357. // output manifest flags <Manifest></Manifest>
  4358. this->WriteManifestOptions(e1, c);
  4359. if (this->NsightTegra &&
  4360. this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
  4361. this->WriteAntBuildOptions(e1, c);
  4362. }
  4363. }
  4364. }
  4365. void cmVisualStudio10TargetGenerator::WriteEvents(
  4366. Elem& e1, std::string const& configName)
  4367. {
  4368. bool addedPrelink = false;
  4369. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  4370. this->GeneratorTarget->GetModuleDefinitionInfo(configName);
  4371. if (mdi && mdi->DefFileGenerated) {
  4372. addedPrelink = true;
  4373. std::vector<cmCustomCommand> commands =
  4374. this->GeneratorTarget->GetPreLinkCommands();
  4375. this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
  4376. commands, configName);
  4377. this->WriteEvent(e1, "PreLinkEvent", commands, configName);
  4378. }
  4379. if (!addedPrelink) {
  4380. this->WriteEvent(e1, "PreLinkEvent",
  4381. this->GeneratorTarget->GetPreLinkCommands(), configName);
  4382. }
  4383. this->WriteEvent(e1, "PreBuildEvent",
  4384. this->GeneratorTarget->GetPreBuildCommands(), configName);
  4385. this->WriteEvent(e1, "PostBuildEvent",
  4386. this->GeneratorTarget->GetPostBuildCommands(), configName);
  4387. }
  4388. void cmVisualStudio10TargetGenerator::WriteEvent(
  4389. Elem& e1, const std::string& name,
  4390. std::vector<cmCustomCommand> const& commands, std::string const& configName)
  4391. {
  4392. if (commands.empty()) {
  4393. return;
  4394. }
  4395. cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
  4396. std::string script;
  4397. const char* pre = "";
  4398. std::string comment;
  4399. bool stdPipesUTF8 = false;
  4400. for (cmCustomCommand const& cc : commands) {
  4401. cmCustomCommandGenerator ccg(cc, configName, lg);
  4402. if (!ccg.HasOnlyEmptyCommandLines()) {
  4403. comment += pre;
  4404. comment += lg->ConstructComment(ccg);
  4405. script += pre;
  4406. pre = "\n";
  4407. script += lg->ConstructScript(ccg);
  4408. stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
  4409. }
  4410. }
  4411. if (!script.empty()) {
  4412. script += lg->FinishConstructScript(this->ProjectType);
  4413. }
  4414. comment = cmVS10EscapeComment(comment);
  4415. if (this->ProjectType != VsProjectType::csproj) {
  4416. Elem e2(e1, name);
  4417. if (stdPipesUTF8) {
  4418. this->WriteStdOutEncodingUtf8(e2);
  4419. }
  4420. e2.Element("Message", comment);
  4421. e2.Element("Command", script);
  4422. } else {
  4423. std::string strippedComment = comment;
  4424. strippedComment.erase(
  4425. std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
  4426. strippedComment.end());
  4427. std::ostringstream oss;
  4428. if (!comment.empty() && !strippedComment.empty()) {
  4429. oss << "echo " << comment << "\n";
  4430. }
  4431. oss << script << "\n";
  4432. e1.Element(name, oss.str());
  4433. }
  4434. }
  4435. void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0)
  4436. {
  4437. cmGlobalGenerator::TargetDependSet const& unordered =
  4438. this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
  4439. using OrderedTargetDependSet =
  4440. cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
  4441. OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  4442. Elem e1(e0, "ItemGroup");
  4443. e1.SetHasElements();
  4444. for (cmGeneratorTarget const* dt : depends) {
  4445. if (!dt->IsInBuildSystem()) {
  4446. continue;
  4447. }
  4448. // skip fortran targets as they can not be processed by MSBuild
  4449. // the only reference will be in the .sln file
  4450. if (this->GlobalGenerator->TargetIsFortranOnly(dt)) {
  4451. continue;
  4452. }
  4453. cmLocalGenerator* lg = dt->GetLocalGenerator();
  4454. std::string name = dt->GetName();
  4455. std::string path;
  4456. if (cmValue p = dt->GetProperty("EXTERNAL_MSPROJECT")) {
  4457. path = *p;
  4458. } else {
  4459. path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(),
  4460. computeProjectFileExtension(dt));
  4461. }
  4462. ConvertToWindowsSlash(path);
  4463. Elem e2(e1, "ProjectReference");
  4464. e2.Attribute("Include", path);
  4465. e2.Element("Project",
  4466. cmStrCat('{', this->GlobalGenerator->GetGUID(name), '}'));
  4467. e2.Element("Name", name);
  4468. this->WriteDotNetReferenceCustomTags(e2, name);
  4469. if (dt->IsCSharpOnly() || cmHasLiteralSuffix(path, "csproj")) {
  4470. e2.Element("SkipGetTargetFrameworkProperties", "true");
  4471. }
  4472. // Don't reference targets that don't produce any output.
  4473. else if (this->Configurations.empty() ||
  4474. dt->GetManagedType(this->Configurations[0]) ==
  4475. cmGeneratorTarget::ManagedType::Undefined) {
  4476. e2.Element("ReferenceOutputAssembly", "false");
  4477. e2.Element("CopyToOutputDirectory", "Never");
  4478. }
  4479. }
  4480. }
  4481. void cmVisualStudio10TargetGenerator::WritePlatformExtensions(Elem& e1)
  4482. {
  4483. // This only applies to Windows 10 apps
  4484. if (this->GlobalGenerator->TargetsWindowsStore() &&
  4485. cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
  4486. cmValue desktopExtensionsVersion =
  4487. this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
  4488. if (desktopExtensionsVersion) {
  4489. this->WriteSinglePlatformExtension(e1, "WindowsDesktop",
  4490. *desktopExtensionsVersion);
  4491. }
  4492. cmValue mobileExtensionsVersion =
  4493. this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
  4494. if (mobileExtensionsVersion) {
  4495. this->WriteSinglePlatformExtension(e1, "WindowsMobile",
  4496. *mobileExtensionsVersion);
  4497. }
  4498. }
  4499. }
  4500. void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
  4501. Elem& e1, std::string const& extension, std::string const& version)
  4502. {
  4503. const std::string s =
  4504. cmStrCat("$([Microsoft.Build.Utilities.ToolLocationHelper]"
  4505. "::GetPlatformExtensionSDKLocation(`",
  4506. extension, ", Version=", version,
  4507. "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
  4508. "$(ExtensionSDKDirectoryRoot), null))"
  4509. "\\DesignTime\\CommonConfiguration\\Neutral\\",
  4510. extension, ".props");
  4511. Elem e2(e1, "Import");
  4512. e2.Attribute("Project", s);
  4513. e2.Attribute("Condition", cmStrCat("exists('", s, "')"));
  4514. }
  4515. void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0)
  4516. {
  4517. cmList sdkReferences;
  4518. std::unique_ptr<Elem> spe1;
  4519. if (cmValue vsSDKReferences =
  4520. this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
  4521. sdkReferences.assign(*vsSDKReferences);
  4522. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  4523. for (auto const& ri : sdkReferences) {
  4524. Elem(*spe1, "SDKReference").Attribute("Include", ri);
  4525. }
  4526. }
  4527. // This only applies to Windows 10 apps
  4528. if (this->GlobalGenerator->TargetsWindowsStore() &&
  4529. cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
  4530. cmValue desktopExtensionsVersion =
  4531. this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
  4532. cmValue mobileExtensionsVersion =
  4533. this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
  4534. cmValue iotExtensionsVersion =
  4535. this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
  4536. if (desktopExtensionsVersion || mobileExtensionsVersion ||
  4537. iotExtensionsVersion) {
  4538. if (!spe1) {
  4539. spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
  4540. }
  4541. if (desktopExtensionsVersion) {
  4542. this->WriteSingleSDKReference(*spe1, "WindowsDesktop",
  4543. *desktopExtensionsVersion);
  4544. }
  4545. if (mobileExtensionsVersion) {
  4546. this->WriteSingleSDKReference(*spe1, "WindowsMobile",
  4547. *mobileExtensionsVersion);
  4548. }
  4549. if (iotExtensionsVersion) {
  4550. this->WriteSingleSDKReference(*spe1, "WindowsIoT",
  4551. *iotExtensionsVersion);
  4552. }
  4553. }
  4554. }
  4555. }
  4556. void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
  4557. Elem& e1, std::string const& extension, std::string const& version)
  4558. {
  4559. Elem(e1, "SDKReference")
  4560. .Attribute("Include", cmStrCat(extension, ", Version=", version));
  4561. }
  4562. namespace {
  4563. std::string ComputeCertificateThumbprint(const std::string& source)
  4564. {
  4565. std::string thumbprint;
  4566. CRYPT_INTEGER_BLOB cryptBlob;
  4567. HCERTSTORE certStore = nullptr;
  4568. PCCERT_CONTEXT certContext = nullptr;
  4569. HANDLE certFile = CreateFileW(
  4570. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  4571. FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  4572. if (certFile != INVALID_HANDLE_VALUE && certFile != nullptr) {
  4573. DWORD fileSize = GetFileSize(certFile, nullptr);
  4574. if (fileSize != INVALID_FILE_SIZE) {
  4575. auto certData = cm::make_unique<BYTE[]>(fileSize);
  4576. if (certData != nullptr) {
  4577. DWORD dwRead = 0;
  4578. if (ReadFile(certFile, certData.get(), fileSize, &dwRead, nullptr)) {
  4579. cryptBlob.cbData = fileSize;
  4580. cryptBlob.pbData = certData.get();
  4581. // Verify that this is a valid cert
  4582. if (PFXIsPFXBlob(&cryptBlob)) {
  4583. // Open the certificate as a store
  4584. certStore =
  4585. PFXImportCertStore(&cryptBlob, nullptr, CRYPT_EXPORTABLE);
  4586. if (certStore != nullptr) {
  4587. // There should only be 1 cert.
  4588. certContext =
  4589. CertEnumCertificatesInStore(certStore, certContext);
  4590. if (certContext != nullptr) {
  4591. // The hash is 20 bytes
  4592. BYTE hashData[20];
  4593. DWORD hashLength = 20;
  4594. // Buffer to print the hash. Each byte takes 2 chars +
  4595. // terminating character
  4596. char hashPrint[41];
  4597. char* pHashPrint = hashPrint;
  4598. // Get the hash property from the certificate
  4599. if (CertGetCertificateContextProperty(
  4600. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  4601. for (DWORD i = 0; i < hashLength; i++) {
  4602. // Convert each byte to hexadecimal
  4603. snprintf(pHashPrint, 3, "%02X", hashData[i]);
  4604. pHashPrint += 2;
  4605. }
  4606. *pHashPrint = '\0';
  4607. thumbprint = hashPrint;
  4608. }
  4609. CertFreeCertificateContext(certContext);
  4610. }
  4611. CertCloseStore(certStore, 0);
  4612. }
  4613. }
  4614. }
  4615. }
  4616. }
  4617. CloseHandle(certFile);
  4618. }
  4619. return thumbprint;
  4620. }
  4621. }
  4622. void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile(
  4623. Elem& e0)
  4624. {
  4625. if ((this->GlobalGenerator->TargetsWindowsStore() ||
  4626. this->GlobalGenerator->TargetsWindowsPhone()) &&
  4627. (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
  4628. std::string pfxFile;
  4629. for (cmGeneratorTarget::AllConfigSource const& source :
  4630. this->GeneratorTarget->GetAllConfigSources()) {
  4631. if (source.Kind == cmGeneratorTarget::SourceKindCertificate) {
  4632. pfxFile = this->ConvertPath(source.Source->GetFullPath(), false);
  4633. ConvertToWindowsSlash(pfxFile);
  4634. break;
  4635. }
  4636. }
  4637. if (this->IsMissingFiles &&
  4638. !(this->GlobalGenerator->TargetsWindowsPhone() &&
  4639. this->GlobalGenerator->GetSystemVersion() == "8.0"_s)) {
  4640. // Move the manifest to a project directory to avoid clashes
  4641. std::string artifactDir =
  4642. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4643. ConvertToWindowsSlash(artifactDir);
  4644. Elem e1(e0, "PropertyGroup");
  4645. e1.Element("AppxPackageArtifactsDir", cmStrCat(artifactDir, '\\'));
  4646. std::string resourcePriFile =
  4647. cmStrCat(this->DefaultArtifactDir, "/resources.pri");
  4648. ConvertToWindowsSlash(resourcePriFile);
  4649. e1.Element("ProjectPriFullPath", resourcePriFile);
  4650. // If we are missing files and we don't have a certificate and
  4651. // aren't targeting WP8.0, add a default certificate
  4652. if (pfxFile.empty()) {
  4653. std::string templateFolder =
  4654. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  4655. pfxFile =
  4656. cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
  4657. cmSystemTools::CopyAFile(
  4658. cmStrCat(templateFolder, "/Windows_TemporaryKey.pfx"), pfxFile,
  4659. false);
  4660. ConvertToWindowsSlash(pfxFile);
  4661. this->AddedFiles.push_back(pfxFile);
  4662. this->AddedDefaultCertificate = true;
  4663. }
  4664. e1.Element("PackageCertificateKeyFile", pfxFile);
  4665. std::string thumb = ComputeCertificateThumbprint(pfxFile);
  4666. if (!thumb.empty()) {
  4667. e1.Element("PackageCertificateThumbprint", thumb);
  4668. }
  4669. } else if (!pfxFile.empty()) {
  4670. Elem e1(e0, "PropertyGroup");
  4671. e1.Element("PackageCertificateKeyFile", pfxFile);
  4672. std::string thumb = ComputeCertificateThumbprint(pfxFile);
  4673. if (!thumb.empty()) {
  4674. e1.Element("PackageCertificateThumbprint", thumb);
  4675. }
  4676. }
  4677. }
  4678. }
  4679. void cmVisualStudio10TargetGenerator::ClassifyAllConfigSources()
  4680. {
  4681. for (cmGeneratorTarget::AllConfigSource const& source :
  4682. this->GeneratorTarget->GetAllConfigSources()) {
  4683. this->ClassifyAllConfigSource(source);
  4684. }
  4685. }
  4686. void cmVisualStudio10TargetGenerator::ClassifyAllConfigSource(
  4687. cmGeneratorTarget::AllConfigSource const& acs)
  4688. {
  4689. switch (acs.Kind) {
  4690. case cmGeneratorTarget::SourceKindResx: {
  4691. // Build and save the name of the corresponding .h file
  4692. // This relationship will be used later when building the project files.
  4693. // Both names would have been auto generated from Visual Studio
  4694. // where the user supplied the file name and Visual Studio
  4695. // appended the suffix.
  4696. std::string resx = acs.Source->ResolveFullPath();
  4697. std::string hFileName =
  4698. cmStrCat(resx.substr(0, resx.find_last_of('.')), ".h");
  4699. this->ExpectedResxHeaders.insert(hFileName);
  4700. } break;
  4701. case cmGeneratorTarget::SourceKindXaml: {
  4702. // Build and save the name of the corresponding .h and .cpp file
  4703. // This relationship will be used later when building the project files.
  4704. // Both names would have been auto generated from Visual Studio
  4705. // where the user supplied the file name and Visual Studio
  4706. // appended the suffix.
  4707. std::string xaml = acs.Source->ResolveFullPath();
  4708. std::string hFileName = cmStrCat(xaml, ".h");
  4709. std::string cppFileName = cmStrCat(xaml, ".cpp");
  4710. this->ExpectedXamlHeaders.insert(hFileName);
  4711. this->ExpectedXamlSources.insert(cppFileName);
  4712. } break;
  4713. default:
  4714. break;
  4715. }
  4716. }
  4717. bool cmVisualStudio10TargetGenerator::IsResxHeader(
  4718. const std::string& headerFile)
  4719. {
  4720. return this->ExpectedResxHeaders.count(headerFile) > 0;
  4721. }
  4722. bool cmVisualStudio10TargetGenerator::IsXamlHeader(
  4723. const std::string& headerFile)
  4724. {
  4725. return this->ExpectedXamlHeaders.count(headerFile) > 0;
  4726. }
  4727. bool cmVisualStudio10TargetGenerator::IsXamlSource(
  4728. const std::string& sourceFile)
  4729. {
  4730. return this->ExpectedXamlSources.count(sourceFile) > 0;
  4731. }
  4732. void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1)
  4733. {
  4734. cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
  4735. bool isAppContainer = false;
  4736. bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
  4737. bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
  4738. bool const isAndroid = this->GlobalGenerator->TargetsAndroid();
  4739. std::string const& rev = this->GlobalGenerator->GetApplicationTypeRevision();
  4740. if (isWindowsPhone || isWindowsStore) {
  4741. e1.Element("ApplicationType",
  4742. (isWindowsPhone ? "Windows Phone" : "Windows Store"));
  4743. e1.Element("DefaultLanguage", "en-US");
  4744. if (rev == "10.0"_s) {
  4745. e1.Element("ApplicationTypeRevision", rev);
  4746. // Visual Studio 14.0 is necessary for building 10.0 apps
  4747. e1.Element("MinimumVisualStudioVersion", "14.0");
  4748. if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4749. isAppContainer = true;
  4750. }
  4751. } else if (rev == "8.1"_s) {
  4752. e1.Element("ApplicationTypeRevision", rev);
  4753. // Visual Studio 12.0 is necessary for building 8.1 apps
  4754. e1.Element("MinimumVisualStudioVersion", "12.0");
  4755. if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4756. isAppContainer = true;
  4757. }
  4758. } else if (rev == "8.0"_s) {
  4759. e1.Element("ApplicationTypeRevision", rev);
  4760. // Visual Studio 11.0 is necessary for building 8.0 apps
  4761. e1.Element("MinimumVisualStudioVersion", "11.0");
  4762. if (isWindowsStore &&
  4763. this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
  4764. isAppContainer = true;
  4765. } else if (isWindowsPhone &&
  4766. this->GeneratorTarget->GetType() ==
  4767. cmStateEnums::EXECUTABLE) {
  4768. e1.Element("XapOutputs", "true");
  4769. e1.Element("XapFilename",
  4770. cmStrCat(this->Name, "_$(Configuration)_$(Platform).xap"));
  4771. }
  4772. }
  4773. } else if (isAndroid) {
  4774. e1.Element("ApplicationType", "Android");
  4775. e1.Element("ApplicationTypeRevision",
  4776. gg->GetAndroidApplicationTypeRevision());
  4777. }
  4778. if (isAppContainer) {
  4779. e1.Element("AppContainerApplication", "true");
  4780. } else if (!isAndroid) {
  4781. if (this->Platform == "ARM64"_s) {
  4782. e1.Element("WindowsSDKDesktopARM64Support", "true");
  4783. } else if (this->Platform == "ARM"_s) {
  4784. e1.Element("WindowsSDKDesktopARMSupport", "true");
  4785. }
  4786. }
  4787. std::string const& targetPlatformVersion =
  4788. gg->GetWindowsTargetPlatformVersion();
  4789. if (!targetPlatformVersion.empty()) {
  4790. e1.Element("WindowsTargetPlatformVersion", targetPlatformVersion);
  4791. }
  4792. cmValue targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
  4793. "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
  4794. if (targetPlatformMinVersion) {
  4795. e1.Element("WindowsTargetPlatformMinVersion", *targetPlatformMinVersion);
  4796. } else if (isWindowsStore && rev == "10.0"_s) {
  4797. // If the min version is not set, then use the TargetPlatformVersion
  4798. if (!targetPlatformVersion.empty()) {
  4799. e1.Element("WindowsTargetPlatformMinVersion", targetPlatformVersion);
  4800. }
  4801. }
  4802. // Added IoT Startup Task support
  4803. if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
  4804. e1.Element("ContainsStartupTask", "true");
  4805. }
  4806. }
  4807. void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
  4808. {
  4809. // For Windows and Windows Phone executables, we will assume that if a
  4810. // manifest is not present that we need to add all the necessary files
  4811. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  4812. std::vector<cmGeneratorTarget::AllConfigSource> manifestSources =
  4813. this->GeneratorTarget->GetAllConfigSources(
  4814. cmGeneratorTarget::SourceKindAppManifest);
  4815. std::string const& v = this->GlobalGenerator->GetSystemVersion();
  4816. if (this->GlobalGenerator->TargetsWindowsPhone()) {
  4817. if (v == "8.0"_s) {
  4818. // Look through the sources for WMAppManifest.xml
  4819. bool foundManifest = false;
  4820. for (cmGeneratorTarget::AllConfigSource const& source :
  4821. this->GeneratorTarget->GetAllConfigSources()) {
  4822. if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
  4823. "wmappmanifest.xml" ==
  4824. cmSystemTools::LowerCase(
  4825. source.Source->GetLocation().GetName())) {
  4826. foundManifest = true;
  4827. break;
  4828. }
  4829. }
  4830. if (!foundManifest) {
  4831. this->IsMissingFiles = true;
  4832. }
  4833. } else if (v == "8.1"_s) {
  4834. if (manifestSources.empty()) {
  4835. this->IsMissingFiles = true;
  4836. }
  4837. }
  4838. } else if (this->GlobalGenerator->TargetsWindowsStore()) {
  4839. if (manifestSources.empty()) {
  4840. if (v == "8.0"_s) {
  4841. this->IsMissingFiles = true;
  4842. } else if (v == "8.1"_s || cmHasLiteralPrefix(v, "10.0")) {
  4843. this->IsMissingFiles = true;
  4844. }
  4845. }
  4846. }
  4847. }
  4848. }
  4849. void cmVisualStudio10TargetGenerator::WriteMissingFiles(Elem& e1)
  4850. {
  4851. std::string const& v = this->GlobalGenerator->GetSystemVersion();
  4852. if (this->GlobalGenerator->TargetsWindowsPhone()) {
  4853. if (v == "8.0"_s) {
  4854. this->WriteMissingFilesWP80(e1);
  4855. } else if (v == "8.1"_s) {
  4856. this->WriteMissingFilesWP81(e1);
  4857. }
  4858. } else if (this->GlobalGenerator->TargetsWindowsStore()) {
  4859. if (v == "8.0"_s) {
  4860. this->WriteMissingFilesWS80(e1);
  4861. } else if (v == "8.1"_s) {
  4862. this->WriteMissingFilesWS81(e1);
  4863. } else if (cmHasLiteralPrefix(v, "10.0")) {
  4864. this->WriteMissingFilesWS10_0(e1);
  4865. }
  4866. }
  4867. }
  4868. void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80(Elem& e1)
  4869. {
  4870. std::string templateFolder =
  4871. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  4872. // For WP80, the manifest needs to be in the same folder as the project
  4873. // this can cause an overwrite problem if projects aren't organized in
  4874. // folders
  4875. std::string manifestFile = cmStrCat(
  4876. this->LocalGenerator->GetCurrentBinaryDirectory(), "/WMAppManifest.xml");
  4877. std::string artifactDir =
  4878. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4879. ConvertToWindowsSlash(artifactDir);
  4880. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  4881. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  4882. cmGeneratedFileStream fout(manifestFile);
  4883. fout.SetCopyIfDifferent(true);
  4884. /* clang-format off */
  4885. fout <<
  4886. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  4887. "<Deployment"
  4888. " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
  4889. " AppPlatformVersion=\"8.0\">\n"
  4890. "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
  4891. "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
  4892. " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
  4893. " Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"CMake\""
  4894. " Description=\"Default CMake App\" Publisher=\"CMake\""
  4895. " PublisherID=\"{" << this->GUID << "}\">\n"
  4896. "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
  4897. << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
  4898. "\t\t<Capabilities/>\n"
  4899. "\t\t<Tasks>\n"
  4900. "\t\t\t<DefaultTask Name=\"_default\""
  4901. " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
  4902. "\t\t</Tasks>\n"
  4903. "\t\t<Tokens>\n"
  4904. "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
  4905. " TaskName=\"_default\">\n"
  4906. "\t\t\t\t<TemplateFlip>\n"
  4907. "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
  4908. << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
  4909. "\t\t\t\t\t<Count>0</Count>\n"
  4910. "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
  4911. << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
  4912. "\t\t\t\t</TemplateFlip>\n"
  4913. "\t\t\t</PrimaryToken>\n"
  4914. "\t\t</Tokens>\n"
  4915. "\t\t<ScreenResolutions>\n"
  4916. "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
  4917. "\t\t</ScreenResolutions>\n"
  4918. "\t</App>\n"
  4919. "</Deployment>\n";
  4920. /* clang-format on */
  4921. std::string sourceFile = this->ConvertPath(manifestFile, false);
  4922. ConvertToWindowsSlash(sourceFile);
  4923. {
  4924. Elem e2(e1, "Xml");
  4925. e2.Attribute("Include", sourceFile);
  4926. e2.Element("SubType", "Designer");
  4927. }
  4928. this->AddedFiles.push_back(sourceFile);
  4929. std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
  4930. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
  4931. smallLogo, false);
  4932. ConvertToWindowsSlash(smallLogo);
  4933. Elem(e1, "Image").Attribute("Include", smallLogo);
  4934. this->AddedFiles.push_back(smallLogo);
  4935. std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
  4936. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
  4937. ConvertToWindowsSlash(logo);
  4938. Elem(e1, "Image").Attribute("Include", logo);
  4939. this->AddedFiles.push_back(logo);
  4940. std::string applicationIcon =
  4941. cmStrCat(this->DefaultArtifactDir, "/ApplicationIcon.png");
  4942. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/ApplicationIcon.png"),
  4943. applicationIcon, false);
  4944. ConvertToWindowsSlash(applicationIcon);
  4945. Elem(e1, "Image").Attribute("Include", applicationIcon);
  4946. this->AddedFiles.push_back(applicationIcon);
  4947. }
  4948. void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81(Elem& e1)
  4949. {
  4950. std::string manifestFile =
  4951. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  4952. std::string artifactDir =
  4953. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  4954. ConvertToWindowsSlash(artifactDir);
  4955. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  4956. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  4957. cmGeneratedFileStream fout(manifestFile);
  4958. fout.SetCopyIfDifferent(true);
  4959. /* clang-format off */
  4960. fout <<
  4961. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  4962. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
  4963. " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
  4964. " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
  4965. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  4966. " Version=\"1.0.0.0\" />\n"
  4967. "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
  4968. " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
  4969. "\t<Properties>\n"
  4970. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  4971. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  4972. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  4973. "\t</Properties>\n"
  4974. "\t<Prerequisites>\n"
  4975. "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
  4976. "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
  4977. "\t</Prerequisites>\n"
  4978. "\t<Resources>\n"
  4979. "\t\t<Resource Language=\"x-generate\" />\n"
  4980. "\t</Resources>\n"
  4981. "\t<Applications>\n"
  4982. "\t\t<Application Id=\"App\""
  4983. " Executable=\"" << targetNameXML << ".exe\""
  4984. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  4985. "\t\t\t<m2:VisualElements\n"
  4986. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  4987. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  4988. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  4989. "\t\t\t\tForegroundText=\"light\"\n"
  4990. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  4991. "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  4992. "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
  4993. "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
  4994. "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
  4995. "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
  4996. "\t\t\t\t</m2:DefaultTile>\n"
  4997. "\t\t\t\t<m2:SplashScreen"
  4998. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  4999. "\t\t\t</m2:VisualElements>\n"
  5000. "\t\t</Application>\n"
  5001. "\t</Applications>\n"
  5002. "</Package>\n";
  5003. /* clang-format on */
  5004. this->WriteCommonMissingFiles(e1, manifestFile);
  5005. }
  5006. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80(Elem& e1)
  5007. {
  5008. std::string manifestFile =
  5009. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5010. std::string artifactDir =
  5011. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5012. ConvertToWindowsSlash(artifactDir);
  5013. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5014. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5015. cmGeneratedFileStream fout(manifestFile);
  5016. fout.SetCopyIfDifferent(true);
  5017. /* clang-format off */
  5018. fout <<
  5019. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5020. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
  5021. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5022. " Version=\"1.0.0.0\" />\n"
  5023. "\t<Properties>\n"
  5024. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5025. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5026. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5027. "\t</Properties>\n"
  5028. "\t<Prerequisites>\n"
  5029. "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
  5030. "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
  5031. "\t</Prerequisites>\n"
  5032. "\t<Resources>\n"
  5033. "\t\t<Resource Language=\"x-generate\" />\n"
  5034. "\t</Resources>\n"
  5035. "\t<Applications>\n"
  5036. "\t\t<Application Id=\"App\""
  5037. " Executable=\"" << targetNameXML << ".exe\""
  5038. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5039. "\t\t\t<VisualElements"
  5040. " DisplayName=\"" << targetNameXML << "\""
  5041. " Description=\"" << targetNameXML << "\""
  5042. " BackgroundColor=\"#336699\" ForegroundText=\"light\""
  5043. " Logo=\"" << artifactDirXML << "\\Logo.png\""
  5044. " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5045. "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
  5046. " ShortName=\"" << targetNameXML << "\" />\n"
  5047. "\t\t\t\t<SplashScreen"
  5048. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5049. "\t\t\t</VisualElements>\n"
  5050. "\t\t</Application>\n"
  5051. "\t</Applications>\n"
  5052. "</Package>\n";
  5053. /* clang-format on */
  5054. this->WriteCommonMissingFiles(e1, manifestFile);
  5055. }
  5056. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81(Elem& e1)
  5057. {
  5058. std::string manifestFile =
  5059. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5060. std::string artifactDir =
  5061. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5062. ConvertToWindowsSlash(artifactDir);
  5063. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5064. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5065. cmGeneratedFileStream fout(manifestFile);
  5066. fout.SetCopyIfDifferent(true);
  5067. /* clang-format off */
  5068. fout <<
  5069. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5070. "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
  5071. " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
  5072. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5073. " Version=\"1.0.0.0\" />\n"
  5074. "\t<Properties>\n"
  5075. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5076. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5077. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5078. "\t</Properties>\n"
  5079. "\t<Prerequisites>\n"
  5080. "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
  5081. "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
  5082. "\t</Prerequisites>\n"
  5083. "\t<Resources>\n"
  5084. "\t\t<Resource Language=\"x-generate\" />\n"
  5085. "\t</Resources>\n"
  5086. "\t<Applications>\n"
  5087. "\t\t<Application Id=\"App\""
  5088. " Executable=\"" << targetNameXML << ".exe\""
  5089. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5090. "\t\t\t<m2:VisualElements\n"
  5091. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5092. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5093. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5094. "\t\t\t\tForegroundText=\"light\"\n"
  5095. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5096. "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
  5097. "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
  5098. "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
  5099. "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
  5100. "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
  5101. "\t\t\t\t</m2:DefaultTile>\n"
  5102. "\t\t\t\t<m2:SplashScreen"
  5103. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5104. "\t\t\t</m2:VisualElements>\n"
  5105. "\t\t</Application>\n"
  5106. "\t</Applications>\n"
  5107. "</Package>\n";
  5108. /* clang-format on */
  5109. this->WriteCommonMissingFiles(e1, manifestFile);
  5110. }
  5111. void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0(Elem& e1)
  5112. {
  5113. std::string manifestFile =
  5114. cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
  5115. std::string artifactDir =
  5116. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  5117. ConvertToWindowsSlash(artifactDir);
  5118. std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
  5119. const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
  5120. cmGeneratedFileStream fout(manifestFile);
  5121. fout.SetCopyIfDifferent(true);
  5122. /* clang-format off */
  5123. fout <<
  5124. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  5125. "<Package\n\t"
  5126. "xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
  5127. "\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
  5128. "\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
  5129. "\n\tIgnorableNamespaces=\"uap mp\">\n\n"
  5130. "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
  5131. " Version=\"1.0.0.0\" />\n"
  5132. "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
  5133. "\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
  5134. "\t<Properties>\n"
  5135. "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
  5136. "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
  5137. "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
  5138. "\t</Properties>\n"
  5139. "\t<Dependencies>\n"
  5140. "\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
  5141. "MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
  5142. "\t</Dependencies>\n"
  5143. "\t<Resources>\n"
  5144. "\t\t<Resource Language=\"x-generate\" />\n"
  5145. "\t</Resources>\n"
  5146. "\t<Applications>\n"
  5147. "\t\t<Application Id=\"App\""
  5148. " Executable=\"" << targetNameXML << ".exe\""
  5149. " EntryPoint=\"" << targetNameXML << ".App\">\n"
  5150. "\t\t\t<uap:VisualElements\n"
  5151. "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
  5152. "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
  5153. "\t\t\t\tBackgroundColor=\"#336699\"\n"
  5154. "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
  5155. "\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
  5156. "\\SmallLogo44x44.png\">\n"
  5157. "\t\t\t\t<uap:SplashScreen"
  5158. " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
  5159. "\t\t\t</uap:VisualElements>\n"
  5160. "\t\t</Application>\n"
  5161. "\t</Applications>\n"
  5162. "</Package>\n";
  5163. /* clang-format on */
  5164. this->WriteCommonMissingFiles(e1, manifestFile);
  5165. }
  5166. void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
  5167. Elem& e1, const std::string& manifestFile)
  5168. {
  5169. std::string templateFolder =
  5170. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
  5171. std::string sourceFile = this->ConvertPath(manifestFile, false);
  5172. ConvertToWindowsSlash(sourceFile);
  5173. {
  5174. Elem e2(e1, "AppxManifest");
  5175. e2.Attribute("Include", sourceFile);
  5176. e2.Element("SubType", "Designer");
  5177. }
  5178. this->AddedFiles.push_back(sourceFile);
  5179. std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
  5180. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
  5181. smallLogo, false);
  5182. ConvertToWindowsSlash(smallLogo);
  5183. Elem(e1, "Image").Attribute("Include", smallLogo);
  5184. this->AddedFiles.push_back(smallLogo);
  5185. std::string smallLogo44 =
  5186. cmStrCat(this->DefaultArtifactDir, "/SmallLogo44x44.png");
  5187. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo44x44.png"),
  5188. smallLogo44, false);
  5189. ConvertToWindowsSlash(smallLogo44);
  5190. Elem(e1, "Image").Attribute("Include", smallLogo44);
  5191. this->AddedFiles.push_back(smallLogo44);
  5192. std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
  5193. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
  5194. ConvertToWindowsSlash(logo);
  5195. Elem(e1, "Image").Attribute("Include", logo);
  5196. this->AddedFiles.push_back(logo);
  5197. std::string storeLogo = cmStrCat(this->DefaultArtifactDir, "/StoreLogo.png");
  5198. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/StoreLogo.png"),
  5199. storeLogo, false);
  5200. ConvertToWindowsSlash(storeLogo);
  5201. Elem(e1, "Image").Attribute("Include", storeLogo);
  5202. this->AddedFiles.push_back(storeLogo);
  5203. std::string splashScreen =
  5204. cmStrCat(this->DefaultArtifactDir, "/SplashScreen.png");
  5205. cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SplashScreen.png"),
  5206. splashScreen, false);
  5207. ConvertToWindowsSlash(splashScreen);
  5208. Elem(e1, "Image").Attribute("Include", splashScreen);
  5209. this->AddedFiles.push_back(splashScreen);
  5210. if (this->AddedDefaultCertificate) {
  5211. // This file has already been added to the build so don't copy it
  5212. std::string keyFile =
  5213. cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
  5214. ConvertToWindowsSlash(keyFile);
  5215. Elem(e1, "None").Attribute("Include", keyFile);
  5216. }
  5217. }
  5218. bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
  5219. {
  5220. HANDLE h =
  5221. CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
  5222. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
  5223. FILE_FLAG_BACKUP_SEMANTICS, 0);
  5224. if (!h) {
  5225. return false;
  5226. }
  5227. FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
  5228. if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
  5229. CloseHandle(h);
  5230. return false;
  5231. }
  5232. CloseHandle(h);
  5233. return true;
  5234. }
  5235. void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
  5236. cmSourceFile const* sf, std::map<std::string, std::string>& tags)
  5237. {
  5238. if (this->ProjectType == VsProjectType::csproj) {
  5239. const cmPropertyMap& props = sf->GetProperties();
  5240. for (const std::string& p : props.GetKeys()) {
  5241. static const cm::string_view propNamePrefix = "VS_CSHARP_";
  5242. if (cmHasPrefix(p, propNamePrefix)) {
  5243. std::string tagName = p.substr(propNamePrefix.length());
  5244. if (!tagName.empty()) {
  5245. cmValue val = props.GetPropertyValue(p);
  5246. if (cmNonempty(val)) {
  5247. tags[tagName] = *val;
  5248. } else {
  5249. tags.erase(tagName);
  5250. }
  5251. }
  5252. }
  5253. }
  5254. }
  5255. }
  5256. void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
  5257. Elem& e2, const std::map<std::string, std::string>& tags)
  5258. {
  5259. for (const auto& i : tags) {
  5260. e2.Element(i.first, i.second);
  5261. }
  5262. }
  5263. std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
  5264. cmSourceFile const* source)
  5265. {
  5266. // For out of source files, we first check if a matching source group
  5267. // for this file exists, otherwise we check if the path relative to current
  5268. // source- or binary-dir is used within the link and return that.
  5269. // In case of .cs files we can't do that automatically for files in the
  5270. // binary directory, because this leads to compilation errors.
  5271. std::string link;
  5272. std::string sourceGroupedFile;
  5273. std::string const& fullFileName = source->GetFullPath();
  5274. std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory();
  5275. std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory();
  5276. // unfortunately we have to copy the source groups, because
  5277. // FindSourceGroup uses a regex which is modifying the group
  5278. std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
  5279. cmSourceGroup* sourceGroup =
  5280. this->Makefile->FindSourceGroup(fullFileName, sourceGroups);
  5281. if (sourceGroup && !sourceGroup->GetFullName().empty()) {
  5282. sourceGroupedFile =
  5283. cmStrCat(sourceGroup->GetFullName(), '/',
  5284. cmsys::SystemTools::GetFilenameName(fullFileName));
  5285. cmsys::SystemTools::ConvertToUnixSlashes(sourceGroupedFile);
  5286. }
  5287. if (!sourceGroupedFile.empty() &&
  5288. cmHasSuffix(fullFileName, sourceGroupedFile)) {
  5289. link = sourceGroupedFile;
  5290. } else if (cmHasPrefix(fullFileName, srcDir)) {
  5291. link = fullFileName.substr(srcDir.length() + 1);
  5292. } else if (!cmHasSuffix(fullFileName, ".cs") &&
  5293. cmHasPrefix(fullFileName, binDir)) {
  5294. link = fullFileName.substr(binDir.length() + 1);
  5295. } else if (cmValue l = source->GetProperty("VS_CSHARP_Link")) {
  5296. link = *l;
  5297. }
  5298. ConvertToWindowsSlash(link);
  5299. return link;
  5300. }
  5301. std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
  5302. const char* relativeFilePath) const
  5303. {
  5304. // Always search in the standard modules location.
  5305. std::string path =
  5306. cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath);
  5307. ConvertToWindowsSlash(path);
  5308. return path;
  5309. }
  5310. void cmVisualStudio10TargetGenerator::WriteStdOutEncodingUtf8(Elem& e1)
  5311. {
  5312. if (this->GlobalGenerator->IsUtf8EncodingSupported()) {
  5313. e1.Element("UseUtf8Encoding", "Always");
  5314. } else if (this->GlobalGenerator->IsStdOutEncodingSupported()) {
  5315. e1.Element("StdOutEncoding", "UTF-8");
  5316. }
  5317. }
  5318. void cmVisualStudio10TargetGenerator::UpdateCache()
  5319. {
  5320. std::vector<std::string> packageReferences;
  5321. if (this->GeneratorTarget->HasPackageReferences()) {
  5322. // Store a cache entry that later determines, if a package restore is
  5323. // required.
  5324. this->GeneratorTarget->Makefile->AddCacheDefinition(
  5325. cmStrCat(this->GeneratorTarget->GetName(),
  5326. "_REQUIRES_VS_PACKAGE_RESTORE"),
  5327. "ON", "Value Computed by CMake", cmStateEnums::STATIC);
  5328. } else {
  5329. // If there are any dependencies that require package restore, inherit the
  5330. // cache variable.
  5331. cmGlobalGenerator::TargetDependSet const& unordered =
  5332. this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
  5333. using OrderedTargetDependSet =
  5334. cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
  5335. OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  5336. for (cmGeneratorTarget const* dt : depends) {
  5337. if (dt->HasPackageReferences()) {
  5338. this->GeneratorTarget->Makefile->AddCacheDefinition(
  5339. cmStrCat(this->GeneratorTarget->GetName(),
  5340. "_REQUIRES_VS_PACKAGE_RESTORE"),
  5341. "ON", "Value Computed by CMake", cmStateEnums::STATIC);
  5342. }
  5343. }
  5344. }
  5345. }