cmVisualStudio10TargetGenerator.cxx 214 KB

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