cmGeneratorTarget.cxx 325 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725
  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 "cmGeneratorTarget.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cerrno>
  9. #include <cstddef>
  10. #include <cstdio>
  11. #include <cstdlib>
  12. #include <cstring>
  13. #include <iterator>
  14. #include <queue>
  15. #include <sstream>
  16. #include <type_traits>
  17. #include <unordered_set>
  18. #include <utility>
  19. #include <cm/memory>
  20. #include <cm/optional>
  21. #include <cm/string_view>
  22. #include <cmext/algorithm>
  23. #include <cmext/string_view>
  24. #include "cmsys/RegularExpression.hxx"
  25. #include "cmAlgorithms.h"
  26. #include "cmComputeLinkInformation.h"
  27. #include "cmCryptoHash.h"
  28. #include "cmCustomCommandGenerator.h"
  29. #include "cmCxxModuleUsageEffects.h"
  30. #include "cmEvaluatedTargetProperty.h"
  31. #include "cmExperimental.h"
  32. #include "cmFileSet.h"
  33. #include "cmFileTimes.h"
  34. #include "cmGeneratedFileStream.h"
  35. #include "cmGeneratorExpression.h"
  36. #include "cmGeneratorExpressionContext.h"
  37. #include "cmGeneratorExpressionDAGChecker.h"
  38. #include "cmGeneratorExpressionNode.h"
  39. #include "cmGlobalGenerator.h"
  40. #include "cmList.h"
  41. #include "cmLocalGenerator.h"
  42. #include "cmMakefile.h"
  43. #include "cmMessageType.h"
  44. #include "cmOutputConverter.h"
  45. #include "cmPropertyMap.h"
  46. #include "cmRange.h"
  47. #include "cmSourceFile.h"
  48. #include "cmSourceFileLocation.h"
  49. #include "cmSourceFileLocationKind.h"
  50. #include "cmSourceGroup.h"
  51. #include "cmStandardLevel.h"
  52. #include "cmStandardLevelResolver.h"
  53. #include "cmState.h"
  54. #include "cmStringAlgorithms.h"
  55. #include "cmSyntheticTargetCache.h"
  56. #include "cmSystemTools.h"
  57. #include "cmTarget.h"
  58. #include "cmTargetLinkLibraryType.h"
  59. #include "cmTargetPropertyComputer.h"
  60. #include "cmake.h"
  61. namespace {
  62. using LinkInterfaceFor = cmGeneratorTarget::LinkInterfaceFor;
  63. const std::string kINTERFACE_LINK_LIBRARIES = "INTERFACE_LINK_LIBRARIES";
  64. const std::string kINTERFACE_LINK_LIBRARIES_DIRECT =
  65. "INTERFACE_LINK_LIBRARIES_DIRECT";
  66. const std::string kINTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE =
  67. "INTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE";
  68. }
  69. template <>
  70. cmValue cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
  71. cmGeneratorTarget const* tgt, cmMakefile const& /* mf */)
  72. {
  73. return tgt->GetSourcesProperty();
  74. }
  75. template <>
  76. const std::string&
  77. cmTargetPropertyComputer::ComputeLocationForBuild<cmGeneratorTarget>(
  78. cmGeneratorTarget const* tgt)
  79. {
  80. return tgt->GetLocation("");
  81. }
  82. template <>
  83. const std::string&
  84. cmTargetPropertyComputer::ComputeLocation<cmGeneratorTarget>(
  85. cmGeneratorTarget const* tgt, const std::string& config)
  86. {
  87. return tgt->GetLocation(config);
  88. }
  89. cmLinkImplItem cmGeneratorTarget::TargetPropertyEntry::NoLinkImplItem;
  90. class TargetPropertyEntryString : public cmGeneratorTarget::TargetPropertyEntry
  91. {
  92. public:
  93. TargetPropertyEntryString(BT<std::string> propertyValue,
  94. cmLinkImplItem const& item = NoLinkImplItem)
  95. : cmGeneratorTarget::TargetPropertyEntry(item)
  96. , PropertyValue(std::move(propertyValue))
  97. {
  98. }
  99. const std::string& Evaluate(cmLocalGenerator*, const std::string&,
  100. cmGeneratorTarget const*,
  101. cmGeneratorExpressionDAGChecker*,
  102. std::string const&) const override
  103. {
  104. return this->PropertyValue.Value;
  105. }
  106. cmListFileBacktrace GetBacktrace() const override
  107. {
  108. return this->PropertyValue.Backtrace;
  109. }
  110. std::string const& GetInput() const override
  111. {
  112. return this->PropertyValue.Value;
  113. }
  114. private:
  115. BT<std::string> PropertyValue;
  116. };
  117. class TargetPropertyEntryGenex : public cmGeneratorTarget::TargetPropertyEntry
  118. {
  119. public:
  120. TargetPropertyEntryGenex(std::unique_ptr<cmCompiledGeneratorExpression> cge,
  121. cmLinkImplItem const& item = NoLinkImplItem)
  122. : cmGeneratorTarget::TargetPropertyEntry(item)
  123. , ge(std::move(cge))
  124. {
  125. }
  126. const std::string& Evaluate(cmLocalGenerator* lg, const std::string& config,
  127. cmGeneratorTarget const* headTarget,
  128. cmGeneratorExpressionDAGChecker* dagChecker,
  129. std::string const& language) const override
  130. {
  131. return this->ge->Evaluate(lg, config, headTarget, dagChecker, nullptr,
  132. language);
  133. }
  134. cmListFileBacktrace GetBacktrace() const override
  135. {
  136. return this->ge->GetBacktrace();
  137. }
  138. std::string const& GetInput() const override { return this->ge->GetInput(); }
  139. bool GetHadContextSensitiveCondition() const override
  140. {
  141. return this->ge->GetHadContextSensitiveCondition();
  142. }
  143. private:
  144. const std::unique_ptr<cmCompiledGeneratorExpression> ge;
  145. };
  146. class TargetPropertyEntryFileSet
  147. : public cmGeneratorTarget::TargetPropertyEntry
  148. {
  149. public:
  150. TargetPropertyEntryFileSet(
  151. std::vector<std::string> dirs, bool contextSensitiveDirs,
  152. std::unique_ptr<cmCompiledGeneratorExpression> entryCge,
  153. const cmFileSet* fileSet, cmLinkImplItem const& item = NoLinkImplItem)
  154. : cmGeneratorTarget::TargetPropertyEntry(item)
  155. , BaseDirs(std::move(dirs))
  156. , ContextSensitiveDirs(contextSensitiveDirs)
  157. , EntryCge(std::move(entryCge))
  158. , FileSet(fileSet)
  159. {
  160. }
  161. const std::string& Evaluate(cmLocalGenerator* lg, const std::string& config,
  162. cmGeneratorTarget const* headTarget,
  163. cmGeneratorExpressionDAGChecker* dagChecker,
  164. std::string const& /*lang*/) const override
  165. {
  166. std::map<std::string, std::vector<std::string>> filesPerDir;
  167. this->FileSet->EvaluateFileEntry(this->BaseDirs, filesPerDir,
  168. this->EntryCge, lg, config, headTarget,
  169. dagChecker);
  170. std::vector<std::string> files;
  171. for (auto const& it : filesPerDir) {
  172. files.insert(files.end(), it.second.begin(), it.second.end());
  173. }
  174. static std::string filesStr;
  175. filesStr = cmList::to_string(files);
  176. return filesStr;
  177. }
  178. cmListFileBacktrace GetBacktrace() const override
  179. {
  180. return this->EntryCge->GetBacktrace();
  181. }
  182. std::string const& GetInput() const override
  183. {
  184. return this->EntryCge->GetInput();
  185. }
  186. bool GetHadContextSensitiveCondition() const override
  187. {
  188. return this->ContextSensitiveDirs ||
  189. this->EntryCge->GetHadContextSensitiveCondition();
  190. }
  191. private:
  192. const std::vector<std::string> BaseDirs;
  193. const bool ContextSensitiveDirs;
  194. const std::unique_ptr<cmCompiledGeneratorExpression> EntryCge;
  195. const cmFileSet* FileSet;
  196. };
  197. std::unique_ptr<
  198. cmGeneratorTarget::
  199. TargetPropertyEntry> static CreateTargetPropertyEntry(cmake& cmakeInstance,
  200. const BT<
  201. std::string>&
  202. propertyValue,
  203. bool
  204. evaluateForBuildsystem =
  205. false)
  206. {
  207. if (cmGeneratorExpression::Find(propertyValue.Value) != std::string::npos) {
  208. cmGeneratorExpression ge(cmakeInstance, propertyValue.Backtrace);
  209. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  210. ge.Parse(propertyValue.Value);
  211. cge->SetEvaluateForBuildsystem(evaluateForBuildsystem);
  212. return std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>(
  213. cm::make_unique<TargetPropertyEntryGenex>(std::move(cge)));
  214. }
  215. return std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>(
  216. cm::make_unique<TargetPropertyEntryString>(propertyValue));
  217. }
  218. cmGeneratorTarget::TargetPropertyEntry::TargetPropertyEntry(
  219. cmLinkImplItem const& item)
  220. : LinkImplItem(item)
  221. {
  222. }
  223. bool cmGeneratorTarget::TargetPropertyEntry::GetHadContextSensitiveCondition()
  224. const
  225. {
  226. return false;
  227. }
  228. static void CreatePropertyGeneratorExpressions(
  229. cmake& cmakeInstance, cmBTStringRange entries,
  230. std::vector<std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>>& items,
  231. bool evaluateForBuildsystem = false)
  232. {
  233. for (auto const& entry : entries) {
  234. items.push_back(
  235. CreateTargetPropertyEntry(cmakeInstance, entry, evaluateForBuildsystem));
  236. }
  237. }
  238. cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
  239. : Target(t)
  240. {
  241. this->Makefile = this->Target->GetMakefile();
  242. this->LocalGenerator = lg;
  243. this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
  244. this->GlobalGenerator->ComputeTargetObjectDirectory(this);
  245. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  246. t->GetIncludeDirectoriesEntries(),
  247. this->IncludeDirectoriesEntries);
  248. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  249. t->GetCompileOptionsEntries(),
  250. this->CompileOptionsEntries);
  251. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  252. t->GetCompileFeaturesEntries(),
  253. this->CompileFeaturesEntries);
  254. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  255. t->GetCompileDefinitionsEntries(),
  256. this->CompileDefinitionsEntries);
  257. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  258. t->GetLinkOptionsEntries(),
  259. this->LinkOptionsEntries);
  260. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  261. t->GetLinkDirectoriesEntries(),
  262. this->LinkDirectoriesEntries);
  263. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  264. t->GetPrecompileHeadersEntries(),
  265. this->PrecompileHeadersEntries);
  266. CreatePropertyGeneratorExpressions(
  267. *lg->GetCMakeInstance(), t->GetSourceEntries(), this->SourceEntries, true);
  268. this->PolicyMap = t->GetPolicyMap();
  269. // Get hard-coded linker language
  270. if (this->Target->GetProperty("HAS_CXX")) {
  271. this->LinkerLanguage = "CXX";
  272. } else {
  273. this->LinkerLanguage = this->Target->GetSafeProperty("LINKER_LANGUAGE");
  274. }
  275. }
  276. cmGeneratorTarget::~cmGeneratorTarget() = default;
  277. cmValue cmGeneratorTarget::GetSourcesProperty() const
  278. {
  279. std::vector<std::string> values;
  280. for (auto const& se : this->SourceEntries) {
  281. values.push_back(se->GetInput());
  282. }
  283. static std::string value;
  284. value = cmList::to_string(values);
  285. return cmValue(value);
  286. }
  287. cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
  288. {
  289. return this->GetLocalGenerator()->GetGlobalGenerator();
  290. }
  291. cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
  292. {
  293. return this->LocalGenerator;
  294. }
  295. cmStateEnums::TargetType cmGeneratorTarget::GetType() const
  296. {
  297. return this->Target->GetType();
  298. }
  299. const std::string& cmGeneratorTarget::GetName() const
  300. {
  301. return this->Target->GetName();
  302. }
  303. std::string cmGeneratorTarget::GetExportName() const
  304. {
  305. cmValue exportName = this->GetProperty("EXPORT_NAME");
  306. if (cmNonempty(exportName)) {
  307. if (!cmGeneratorExpression::IsValidTargetName(*exportName)) {
  308. std::ostringstream e;
  309. e << "EXPORT_NAME property \"" << *exportName << "\" for \""
  310. << this->GetName() << "\": is not valid.";
  311. cmSystemTools::Error(e.str());
  312. return "";
  313. }
  314. return *exportName;
  315. }
  316. return this->GetName();
  317. }
  318. std::string cmGeneratorTarget::GetFilesystemExportName() const
  319. {
  320. auto fs_safe = this->GetExportName();
  321. // First escape any `_` characters to avoid collisions.
  322. cmSystemTools::ReplaceString(fs_safe, "_", "__");
  323. // Escape other characters that are not generally filesystem-safe.
  324. cmSystemTools::ReplaceString(fs_safe, ":", "_c");
  325. return fs_safe;
  326. }
  327. cmValue cmGeneratorTarget::GetProperty(const std::string& prop) const
  328. {
  329. if (cmValue result =
  330. cmTargetPropertyComputer::GetProperty(this, prop, *this->Makefile)) {
  331. return result;
  332. }
  333. if (cmSystemTools::GetFatalErrorOccurred()) {
  334. return nullptr;
  335. }
  336. return this->Target->GetProperty(prop);
  337. }
  338. std::string const& cmGeneratorTarget::GetSafeProperty(
  339. std::string const& prop) const
  340. {
  341. return this->GetProperty(prop);
  342. }
  343. const char* cmGeneratorTarget::GetOutputTargetType(
  344. cmStateEnums::ArtifactType artifact) const
  345. {
  346. if (this->IsFrameworkOnApple() || this->GetGlobalGenerator()->IsXcode()) {
  347. // import file (i.e. .tbd file) is always in same location as library
  348. artifact = cmStateEnums::RuntimeBinaryArtifact;
  349. }
  350. switch (this->GetType()) {
  351. case cmStateEnums::SHARED_LIBRARY:
  352. if (this->IsDLLPlatform()) {
  353. switch (artifact) {
  354. case cmStateEnums::RuntimeBinaryArtifact:
  355. // A DLL shared library is treated as a runtime target.
  356. return "RUNTIME";
  357. case cmStateEnums::ImportLibraryArtifact:
  358. // A DLL import library is treated as an archive target.
  359. return "ARCHIVE";
  360. }
  361. } else {
  362. switch (artifact) {
  363. case cmStateEnums::RuntimeBinaryArtifact:
  364. // For non-DLL platforms shared libraries are treated as
  365. // library targets.
  366. return "LIBRARY";
  367. case cmStateEnums::ImportLibraryArtifact:
  368. // Library import libraries are treated as archive targets.
  369. return "ARCHIVE";
  370. }
  371. }
  372. break;
  373. case cmStateEnums::STATIC_LIBRARY:
  374. // Static libraries are always treated as archive targets.
  375. return "ARCHIVE";
  376. case cmStateEnums::MODULE_LIBRARY:
  377. switch (artifact) {
  378. case cmStateEnums::RuntimeBinaryArtifact:
  379. // Module libraries are always treated as library targets.
  380. return "LIBRARY";
  381. case cmStateEnums::ImportLibraryArtifact:
  382. // Module import libraries are treated as archive targets.
  383. return "ARCHIVE";
  384. }
  385. break;
  386. case cmStateEnums::OBJECT_LIBRARY:
  387. // Object libraries are always treated as object targets.
  388. return "OBJECT";
  389. case cmStateEnums::EXECUTABLE:
  390. switch (artifact) {
  391. case cmStateEnums::RuntimeBinaryArtifact:
  392. // Executables are always treated as runtime targets.
  393. return "RUNTIME";
  394. case cmStateEnums::ImportLibraryArtifact:
  395. // Executable import libraries are treated as archive targets.
  396. return "ARCHIVE";
  397. }
  398. break;
  399. default:
  400. break;
  401. }
  402. return "";
  403. }
  404. std::string cmGeneratorTarget::GetOutputName(
  405. const std::string& config, cmStateEnums::ArtifactType artifact) const
  406. {
  407. // Lookup/compute/cache the output name for this configuration.
  408. OutputNameKey key(config, artifact);
  409. auto i = this->OutputNameMap.find(key);
  410. if (i == this->OutputNameMap.end()) {
  411. // Add empty name in map to detect potential recursion.
  412. OutputNameMapType::value_type entry(key, "");
  413. i = this->OutputNameMap.insert(entry).first;
  414. // Compute output name.
  415. std::vector<std::string> props;
  416. std::string type = this->GetOutputTargetType(artifact);
  417. std::string configUpper = cmSystemTools::UpperCase(config);
  418. if (!type.empty() && !configUpper.empty()) {
  419. // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME_<CONFIG>
  420. props.push_back(type + "_OUTPUT_NAME_" + configUpper);
  421. }
  422. if (!type.empty()) {
  423. // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME
  424. props.push_back(type + "_OUTPUT_NAME");
  425. }
  426. if (!configUpper.empty()) {
  427. // OUTPUT_NAME_<CONFIG>
  428. props.push_back("OUTPUT_NAME_" + configUpper);
  429. // <CONFIG>_OUTPUT_NAME
  430. props.push_back(configUpper + "_OUTPUT_NAME");
  431. }
  432. // OUTPUT_NAME
  433. props.emplace_back("OUTPUT_NAME");
  434. std::string outName;
  435. for (std::string const& p : props) {
  436. if (cmValue outNameProp = this->GetProperty(p)) {
  437. outName = *outNameProp;
  438. break;
  439. }
  440. }
  441. if (outName.empty()) {
  442. outName = this->GetName();
  443. }
  444. // Now evaluate genex and update the previously-prepared map entry.
  445. i->second =
  446. cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
  447. } else if (i->second.empty()) {
  448. // An empty map entry indicates we have been called recursively
  449. // from the above block.
  450. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  451. MessageType::FATAL_ERROR,
  452. "Target '" + this->GetName() + "' OUTPUT_NAME depends on itself.",
  453. this->GetBacktrace());
  454. }
  455. return i->second;
  456. }
  457. std::string cmGeneratorTarget::GetFilePrefix(
  458. const std::string& config, cmStateEnums::ArtifactType artifact) const
  459. {
  460. if (this->IsImported()) {
  461. cmValue prefix = this->GetFilePrefixInternal(config, artifact);
  462. return prefix ? *prefix : std::string();
  463. }
  464. return this->GetFullNameInternalComponents(config, artifact).prefix;
  465. }
  466. std::string cmGeneratorTarget::GetFileSuffix(
  467. const std::string& config, cmStateEnums::ArtifactType artifact) const
  468. {
  469. if (this->IsImported()) {
  470. cmValue suffix = this->GetFileSuffixInternal(config, artifact);
  471. return suffix ? *suffix : std::string();
  472. }
  473. return this->GetFullNameInternalComponents(config, artifact).suffix;
  474. }
  475. std::string cmGeneratorTarget::GetFilePostfix(const std::string& config) const
  476. {
  477. cmValue postfix = nullptr;
  478. std::string frameworkPostfix;
  479. if (!config.empty()) {
  480. std::string configProp =
  481. cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
  482. postfix = this->GetProperty(configProp);
  483. // Mac application bundles and frameworks have no regular postfix like
  484. // libraries do.
  485. if (!this->IsImported() && postfix &&
  486. (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
  487. postfix = nullptr;
  488. }
  489. // Frameworks created by multi config generators can have a special
  490. // framework postfix.
  491. frameworkPostfix = this->GetFrameworkMultiConfigPostfix(config);
  492. if (!frameworkPostfix.empty()) {
  493. postfix = cmValue(frameworkPostfix);
  494. }
  495. }
  496. return postfix ? *postfix : std::string();
  497. }
  498. std::string cmGeneratorTarget::GetFrameworkMultiConfigPostfix(
  499. const std::string& config) const
  500. {
  501. cmValue postfix = nullptr;
  502. if (!config.empty()) {
  503. std::string configProp = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_",
  504. cmSystemTools::UpperCase(config));
  505. postfix = this->GetProperty(configProp);
  506. if (!this->IsImported() && postfix &&
  507. (this->IsFrameworkOnApple() &&
  508. !this->GetGlobalGenerator()->IsMultiConfig())) {
  509. postfix = nullptr;
  510. }
  511. }
  512. return postfix ? *postfix : std::string();
  513. }
  514. cmValue cmGeneratorTarget::GetFilePrefixInternal(
  515. std::string const& config, cmStateEnums::ArtifactType artifact,
  516. const std::string& language) const
  517. {
  518. // no prefix for non-main target types.
  519. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  520. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  521. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  522. this->GetType() != cmStateEnums::EXECUTABLE) {
  523. return nullptr;
  524. }
  525. const bool isImportedLibraryArtifact =
  526. (artifact == cmStateEnums::ImportLibraryArtifact);
  527. // Return an empty prefix for the import library if this platform
  528. // does not support import libraries.
  529. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  530. return nullptr;
  531. }
  532. // The implib option is only allowed for shared libraries, module
  533. // libraries, and executables.
  534. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  535. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  536. this->GetType() != cmStateEnums::EXECUTABLE) {
  537. artifact = cmStateEnums::RuntimeBinaryArtifact;
  538. }
  539. // Compute prefix value.
  540. cmValue targetPrefix =
  541. (isImportedLibraryArtifact ? this->GetProperty("IMPORT_PREFIX")
  542. : this->GetProperty("PREFIX"));
  543. if (!targetPrefix) {
  544. const char* prefixVar = this->Target->GetPrefixVariableInternal(artifact);
  545. if (!language.empty() && cmNonempty(prefixVar)) {
  546. std::string langPrefix = cmStrCat(prefixVar, "_", language);
  547. targetPrefix = this->Makefile->GetDefinition(langPrefix);
  548. }
  549. // if there is no prefix on the target nor specific language
  550. // use the cmake definition.
  551. if (!targetPrefix && prefixVar) {
  552. targetPrefix = this->Makefile->GetDefinition(prefixVar);
  553. }
  554. }
  555. return targetPrefix;
  556. }
  557. cmValue cmGeneratorTarget::GetFileSuffixInternal(
  558. std::string const& config, cmStateEnums::ArtifactType artifact,
  559. const std::string& language) const
  560. {
  561. // no suffix for non-main target types.
  562. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  563. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  564. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  565. this->GetType() != cmStateEnums::EXECUTABLE) {
  566. return nullptr;
  567. }
  568. const bool isImportedLibraryArtifact =
  569. (artifact == cmStateEnums::ImportLibraryArtifact);
  570. // Return an empty suffix for the import library if this platform
  571. // does not support import libraries.
  572. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  573. return nullptr;
  574. }
  575. // The implib option is only allowed for shared libraries, module
  576. // libraries, and executables.
  577. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  578. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  579. this->GetType() != cmStateEnums::EXECUTABLE) {
  580. artifact = cmStateEnums::RuntimeBinaryArtifact;
  581. }
  582. // Compute suffix value.
  583. cmValue targetSuffix =
  584. (isImportedLibraryArtifact ? this->GetProperty("IMPORT_SUFFIX")
  585. : this->GetProperty("SUFFIX"));
  586. if (!targetSuffix) {
  587. const char* suffixVar = this->Target->GetSuffixVariableInternal(artifact);
  588. if (!language.empty() && cmNonempty(suffixVar)) {
  589. std::string langSuffix = cmStrCat(suffixVar, "_", language);
  590. targetSuffix = this->Makefile->GetDefinition(langSuffix);
  591. }
  592. // if there is no suffix on the target nor specific language
  593. // use the cmake definition.
  594. if (!targetSuffix && suffixVar) {
  595. targetSuffix = this->Makefile->GetDefinition(suffixVar);
  596. }
  597. }
  598. return targetSuffix;
  599. }
  600. void cmGeneratorTarget::ClearSourcesCache()
  601. {
  602. this->AllConfigSources.clear();
  603. this->KindedSourcesMap.clear();
  604. this->SourcesAreContextDependent = Tribool::Indeterminate;
  605. this->Objects.clear();
  606. this->VisitedConfigsForObjects.clear();
  607. this->LinkImplMap.clear();
  608. this->LinkImplUsageRequirementsOnlyMap.clear();
  609. this->IncludeDirectoriesCache.clear();
  610. this->CompileOptionsCache.clear();
  611. this->CompileDefinitionsCache.clear();
  612. this->PrecompileHeadersCache.clear();
  613. this->LinkOptionsCache.clear();
  614. this->LinkDirectoriesCache.clear();
  615. this->RuntimeBinaryFullNameCache.clear();
  616. this->ImportLibraryFullNameCache.clear();
  617. }
  618. void cmGeneratorTarget::ClearLinkInterfaceCache()
  619. {
  620. this->LinkInterfaceMap.clear();
  621. this->LinkInterfaceUsageRequirementsOnlyMap.clear();
  622. }
  623. void cmGeneratorTarget::AddSourceCommon(const std::string& src, bool before)
  624. {
  625. this->SourceEntries.insert(
  626. before ? this->SourceEntries.begin() : this->SourceEntries.end(),
  627. CreateTargetPropertyEntry(
  628. *this->LocalGenerator->GetCMakeInstance(),
  629. BT<std::string>(src, this->Makefile->GetBacktrace()), true));
  630. this->ClearSourcesCache();
  631. }
  632. void cmGeneratorTarget::AddSource(const std::string& src, bool before)
  633. {
  634. this->Target->AddSource(src, before);
  635. this->AddSourceCommon(src, before);
  636. }
  637. void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
  638. {
  639. this->Target->AddTracedSources(srcs);
  640. if (!srcs.empty()) {
  641. this->AddSourceCommon(cmJoin(srcs, ";"));
  642. }
  643. }
  644. void cmGeneratorTarget::AddIncludeDirectory(const std::string& src,
  645. bool before)
  646. {
  647. this->Target->InsertInclude(
  648. BT<std::string>(src, this->Makefile->GetBacktrace()), before);
  649. this->IncludeDirectoriesEntries.insert(
  650. before ? this->IncludeDirectoriesEntries.begin()
  651. : this->IncludeDirectoriesEntries.end(),
  652. CreateTargetPropertyEntry(
  653. *this->Makefile->GetCMakeInstance(),
  654. BT<std::string>(src, this->Makefile->GetBacktrace()), true));
  655. }
  656. void cmGeneratorTarget::AddSystemIncludeDirectory(std::string const& inc,
  657. std::string const& lang)
  658. {
  659. std::string config_upper;
  660. auto const& configs =
  661. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  662. for (auto const& config : configs) {
  663. std::string inc_with_config = inc;
  664. if (!config.empty()) {
  665. cmSystemTools::ReplaceString(inc_with_config, "$<CONFIG>", config);
  666. config_upper = cmSystemTools::UpperCase(config);
  667. }
  668. auto const& key = cmStrCat(config_upper, "/", lang);
  669. this->Target->AddSystemIncludeDirectories({ inc_with_config });
  670. this->SystemIncludesCache[key].emplace_back(inc_with_config);
  671. // SystemIncludesCache should be sorted so that binary search can be used
  672. std::sort(this->SystemIncludesCache[key].begin(),
  673. this->SystemIncludesCache[key].end());
  674. }
  675. }
  676. std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
  677. cmSourceFile const* sf) const
  678. {
  679. auto i = this->SourceDepends.find(sf);
  680. if (i != this->SourceDepends.end()) {
  681. return &i->second.Depends;
  682. }
  683. return nullptr;
  684. }
  685. namespace {
  686. void handleSystemIncludesDep(cmLocalGenerator* lg,
  687. cmGeneratorTarget const* depTgt,
  688. const std::string& config,
  689. cmGeneratorTarget const* headTarget,
  690. cmGeneratorExpressionDAGChecker* dagChecker,
  691. cmList& result, bool excludeImported,
  692. std::string const& language)
  693. {
  694. if (cmValue dirs =
  695. depTgt->GetProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES")) {
  696. result.append(cmGeneratorExpression::Evaluate(
  697. *dirs, lg, config, headTarget, dagChecker, depTgt, language));
  698. }
  699. if (!depTgt->GetPropertyAsBool("SYSTEM")) {
  700. return;
  701. }
  702. if (depTgt->IsImported()) {
  703. if (excludeImported) {
  704. return;
  705. }
  706. if (depTgt->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
  707. return;
  708. }
  709. }
  710. if (cmValue dirs = depTgt->GetProperty("INTERFACE_INCLUDE_DIRECTORIES")) {
  711. result.append(cmGeneratorExpression::Evaluate(
  712. *dirs, lg, config, headTarget, dagChecker, depTgt, language));
  713. }
  714. if (depTgt->Target->IsFrameworkOnApple() ||
  715. depTgt->IsImportedFrameworkFolderOnApple(config)) {
  716. if (auto fwDescriptor = depTgt->GetGlobalGenerator()->SplitFrameworkPath(
  717. depTgt->GetLocation(config))) {
  718. result.push_back(fwDescriptor->Directory);
  719. result.push_back(fwDescriptor->GetFrameworkPath());
  720. }
  721. }
  722. }
  723. }
  724. /* clang-format off */
  725. #define IMPLEMENT_VISIT(KIND) \
  726. do { \
  727. KindedSources const& kinded = this->GetKindedSources(config); \
  728. for (SourceAndKind const& s : kinded.Sources) { \
  729. if (s.Kind == KIND) { \
  730. data.push_back(s.Source.Value); \
  731. } \
  732. } \
  733. } while (false)
  734. /* clang-format on */
  735. void cmGeneratorTarget::GetObjectSources(
  736. std::vector<cmSourceFile const*>& data, const std::string& config) const
  737. {
  738. IMPLEMENT_VISIT(SourceKindObjectSource);
  739. if (this->VisitedConfigsForObjects.count(config)) {
  740. return;
  741. }
  742. for (cmSourceFile const* it : data) {
  743. this->Objects[it];
  744. }
  745. this->LocalGenerator->ComputeObjectFilenames(this->Objects, this);
  746. this->VisitedConfigsForObjects.insert(config);
  747. }
  748. void cmGeneratorTarget::ComputeObjectMapping()
  749. {
  750. auto const& configs =
  751. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  752. std::set<std::string> configSet(configs.begin(), configs.end());
  753. if (configSet == this->VisitedConfigsForObjects) {
  754. return;
  755. }
  756. for (std::string const& c : configs) {
  757. std::vector<cmSourceFile const*> sourceFiles;
  758. this->GetObjectSources(sourceFiles, c);
  759. }
  760. }
  761. cmValue cmGeneratorTarget::GetFeature(const std::string& feature,
  762. const std::string& config) const
  763. {
  764. if (!config.empty()) {
  765. std::string featureConfig =
  766. cmStrCat(feature, '_', cmSystemTools::UpperCase(config));
  767. if (cmValue value = this->GetProperty(featureConfig)) {
  768. return value;
  769. }
  770. }
  771. if (cmValue value = this->GetProperty(feature)) {
  772. return value;
  773. }
  774. return this->LocalGenerator->GetFeature(feature, config);
  775. }
  776. std::string cmGeneratorTarget::GetLinkerTypeProperty(
  777. std::string const& lang, std::string const& config) const
  778. {
  779. std::string propName{ "LINKER_TYPE" };
  780. auto linkerType = this->GetProperty(propName);
  781. if (!linkerType.IsEmpty()) {
  782. cmGeneratorExpressionDAGChecker dagChecker(this, propName, nullptr,
  783. nullptr);
  784. auto ltype =
  785. cmGeneratorExpression::Evaluate(*linkerType, this->GetLocalGenerator(),
  786. config, this, &dagChecker, this, lang);
  787. if (this->IsDeviceLink()) {
  788. cmList list{ ltype };
  789. const auto DL_BEGIN = "<DEVICE_LINK>"_s;
  790. const auto DL_END = "</DEVICE_LINK>"_s;
  791. cm::erase_if(list, [&](const std::string& item) {
  792. return item == DL_BEGIN || item == DL_END;
  793. });
  794. return list.to_string();
  795. }
  796. return ltype;
  797. }
  798. return std::string{};
  799. }
  800. const char* cmGeneratorTarget::GetLinkPIEProperty(
  801. const std::string& config) const
  802. {
  803. static std::string PICValue;
  804. PICValue = this->GetLinkInterfaceDependentStringAsBoolProperty(
  805. "POSITION_INDEPENDENT_CODE", config);
  806. if (PICValue == "(unset)") {
  807. // POSITION_INDEPENDENT_CODE is not set
  808. return nullptr;
  809. }
  810. auto status = this->GetPolicyStatusCMP0083();
  811. return (status != cmPolicies::WARN && status != cmPolicies::OLD)
  812. ? PICValue.c_str()
  813. : nullptr;
  814. }
  815. bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang,
  816. std::string const& config) const
  817. {
  818. cmValue feature = this->GetFeature("INTERPROCEDURAL_OPTIMIZATION", config);
  819. if (!feature.IsOn()) {
  820. // 'INTERPROCEDURAL_OPTIMIZATION' is off, no need to check policies
  821. return false;
  822. }
  823. if (lang != "C" && lang != "CXX" && lang != "CUDA" && lang != "Fortran") {
  824. // We do not define IPO behavior for other languages.
  825. return false;
  826. }
  827. if (lang == "CUDA") {
  828. // CUDA IPO requires both CUDA_ARCHITECTURES and CUDA_SEPARABLE_COMPILATION
  829. if (cmIsOff(this->GetSafeProperty("CUDA_ARCHITECTURES")) ||
  830. cmIsOff(this->GetSafeProperty("CUDA_SEPARABLE_COMPILATION"))) {
  831. return false;
  832. }
  833. }
  834. cmPolicies::PolicyStatus cmp0069 = this->GetPolicyStatusCMP0069();
  835. if (cmp0069 == cmPolicies::OLD || cmp0069 == cmPolicies::WARN) {
  836. if (this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_LEGACY_BEHAVIOR")) {
  837. return true;
  838. }
  839. if (this->PolicyReportedCMP0069) {
  840. // problem is already reported, no need to issue a message
  841. return false;
  842. }
  843. const bool in_try_compile =
  844. this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile();
  845. if (cmp0069 == cmPolicies::WARN && !in_try_compile) {
  846. std::ostringstream w;
  847. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0069) << "\n";
  848. w << "INTERPROCEDURAL_OPTIMIZATION property will be ignored for target "
  849. << "'" << this->GetName() << "'.";
  850. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  851. MessageType::AUTHOR_WARNING, w.str(), this->GetBacktrace());
  852. this->PolicyReportedCMP0069 = true;
  853. }
  854. return false;
  855. }
  856. // Note: check consistency with messages from CheckIPOSupported
  857. const char* message = nullptr;
  858. if (!this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_SUPPORTED_BY_CMAKE")) {
  859. message = "CMake doesn't support IPO for current compiler";
  860. } else if (!this->Makefile->IsOn("_CMAKE_" + lang +
  861. "_IPO_MAY_BE_SUPPORTED_BY_COMPILER")) {
  862. message = "Compiler doesn't support IPO";
  863. } else if (!this->GlobalGenerator->IsIPOSupported()) {
  864. message = "CMake doesn't support IPO for current generator";
  865. }
  866. if (!message) {
  867. // No error/warning messages
  868. return true;
  869. }
  870. if (this->PolicyReportedCMP0069) {
  871. // problem is already reported, no need to issue a message
  872. return false;
  873. }
  874. this->PolicyReportedCMP0069 = true;
  875. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  876. MessageType::FATAL_ERROR, message, this->GetBacktrace());
  877. return false;
  878. }
  879. const std::string& cmGeneratorTarget::GetObjectName(cmSourceFile const* file)
  880. {
  881. this->ComputeObjectMapping();
  882. return this->Objects[file];
  883. }
  884. const char* cmGeneratorTarget::GetCustomObjectExtension() const
  885. {
  886. struct compiler_mode
  887. {
  888. std::string variable;
  889. std::string extension;
  890. };
  891. static std::array<compiler_mode, 4> const modes{
  892. { { "CUDA_PTX_COMPILATION", ".ptx" },
  893. { "CUDA_CUBIN_COMPILATION", ".cubin" },
  894. { "CUDA_FATBIN_COMPILATION", ".fatbin" },
  895. { "CUDA_OPTIX_COMPILATION", ".optixir" } }
  896. };
  897. std::string const& compiler =
  898. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  899. if (!compiler.empty()) {
  900. for (const auto& m : modes) {
  901. const bool has_extension = this->GetPropertyAsBool(m.variable);
  902. if (has_extension) {
  903. return m.extension.c_str();
  904. }
  905. }
  906. }
  907. return nullptr;
  908. }
  909. void cmGeneratorTarget::AddExplicitObjectName(cmSourceFile const* sf)
  910. {
  911. this->ExplicitObjectName.insert(sf);
  912. }
  913. bool cmGeneratorTarget::HasExplicitObjectName(cmSourceFile const* file) const
  914. {
  915. const_cast<cmGeneratorTarget*>(this)->ComputeObjectMapping();
  916. auto it = this->ExplicitObjectName.find(file);
  917. return it != this->ExplicitObjectName.end();
  918. }
  919. BTs<std::string> const* cmGeneratorTarget::GetLanguageStandardProperty(
  920. std::string const& lang, std::string const& config) const
  921. {
  922. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  923. auto langStandardIter = this->LanguageStandardMap.find(key);
  924. if (langStandardIter != this->LanguageStandardMap.end()) {
  925. return &langStandardIter->second;
  926. }
  927. return this->Target->GetLanguageStandardProperty(
  928. cmStrCat(lang, "_STANDARD"));
  929. }
  930. cmValue cmGeneratorTarget::GetLanguageStandard(std::string const& lang,
  931. std::string const& config) const
  932. {
  933. BTs<std::string> const* languageStandard =
  934. this->GetLanguageStandardProperty(lang, config);
  935. if (languageStandard) {
  936. return cmValue(languageStandard->Value);
  937. }
  938. return nullptr;
  939. }
  940. cmValue cmGeneratorTarget::GetPropertyWithPairedLanguageSupport(
  941. std::string const& lang, const char* suffix) const
  942. {
  943. cmValue propertyValue = this->Target->GetProperty(cmStrCat(lang, suffix));
  944. if (!propertyValue) {
  945. // Check if we should use the value set by another language.
  946. if (lang == "OBJC") {
  947. propertyValue = this->GetPropertyWithPairedLanguageSupport("C", suffix);
  948. } else if (lang == "OBJCXX" || lang == "CUDA" || lang == "HIP") {
  949. propertyValue =
  950. this->GetPropertyWithPairedLanguageSupport("CXX", suffix);
  951. }
  952. }
  953. return propertyValue;
  954. }
  955. cmValue cmGeneratorTarget::GetLanguageExtensions(std::string const& lang) const
  956. {
  957. return this->GetPropertyWithPairedLanguageSupport(lang, "_EXTENSIONS");
  958. }
  959. bool cmGeneratorTarget::GetLanguageStandardRequired(
  960. std::string const& lang) const
  961. {
  962. return this->GetPropertyWithPairedLanguageSupport(lang, "_STANDARD_REQUIRED")
  963. .IsOn();
  964. }
  965. void cmGeneratorTarget::GetModuleDefinitionSources(
  966. std::vector<cmSourceFile const*>& data, const std::string& config) const
  967. {
  968. IMPLEMENT_VISIT(SourceKindModuleDefinition);
  969. }
  970. void cmGeneratorTarget::GetHeaderSources(
  971. std::vector<cmSourceFile const*>& data, const std::string& config) const
  972. {
  973. IMPLEMENT_VISIT(SourceKindHeader);
  974. }
  975. void cmGeneratorTarget::GetCxxModuleSources(
  976. std::vector<cmSourceFile const*>& data, const std::string& config) const
  977. {
  978. IMPLEMENT_VISIT(SourceKindCxxModuleSource);
  979. }
  980. void cmGeneratorTarget::GetExtraSources(std::vector<cmSourceFile const*>& data,
  981. const std::string& config) const
  982. {
  983. IMPLEMENT_VISIT(SourceKindExtra);
  984. }
  985. void cmGeneratorTarget::GetCustomCommands(
  986. std::vector<cmSourceFile const*>& data, const std::string& config) const
  987. {
  988. IMPLEMENT_VISIT(SourceKindCustomCommand);
  989. }
  990. void cmGeneratorTarget::GetExternalObjects(
  991. std::vector<cmSourceFile const*>& data, const std::string& config) const
  992. {
  993. IMPLEMENT_VISIT(SourceKindExternalObject);
  994. }
  995. void cmGeneratorTarget::GetManifests(std::vector<cmSourceFile const*>& data,
  996. const std::string& config) const
  997. {
  998. IMPLEMENT_VISIT(SourceKindManifest);
  999. }
  1000. std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const
  1001. {
  1002. if (!this->UtilityItemsDone) {
  1003. this->UtilityItemsDone = true;
  1004. std::set<BT<std::pair<std::string, bool>>> const& utilities =
  1005. this->GetUtilities();
  1006. for (BT<std::pair<std::string, bool>> const& i : utilities) {
  1007. if (cmGeneratorTarget* gt =
  1008. this->LocalGenerator->FindGeneratorTargetToUse(i.Value.first)) {
  1009. this->UtilityItems.insert(cmLinkItem(gt, i.Value.second, i.Backtrace));
  1010. } else {
  1011. this->UtilityItems.insert(
  1012. cmLinkItem(i.Value.first, i.Value.second, i.Backtrace));
  1013. }
  1014. }
  1015. }
  1016. return this->UtilityItems;
  1017. }
  1018. const std::string& cmGeneratorTarget::GetLocation(
  1019. const std::string& config) const
  1020. {
  1021. static std::string location;
  1022. if (this->IsImported()) {
  1023. location = this->Target->ImportedGetFullPath(
  1024. config, cmStateEnums::RuntimeBinaryArtifact);
  1025. } else {
  1026. location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  1027. }
  1028. return location;
  1029. }
  1030. cm::optional<std::string> cmGeneratorTarget::MaybeGetLocation(
  1031. std::string const& config) const
  1032. {
  1033. cm::optional<std::string> location;
  1034. if (cmGeneratorTarget::ImportInfo const* imp = this->GetImportInfo(config)) {
  1035. if (!imp->Location.empty()) {
  1036. location = imp->Location;
  1037. }
  1038. } else {
  1039. location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  1040. }
  1041. return location;
  1042. }
  1043. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreBuildCommands()
  1044. const
  1045. {
  1046. return this->Target->GetPreBuildCommands();
  1047. }
  1048. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreLinkCommands()
  1049. const
  1050. {
  1051. return this->Target->GetPreLinkCommands();
  1052. }
  1053. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPostBuildCommands()
  1054. const
  1055. {
  1056. return this->Target->GetPostBuildCommands();
  1057. }
  1058. void cmGeneratorTarget::AppendCustomCommandSideEffects(
  1059. std::set<cmGeneratorTarget const*>& sideEffects) const
  1060. {
  1061. if (!this->GetPreBuildCommands().empty() ||
  1062. !this->GetPreLinkCommands().empty() ||
  1063. !this->GetPostBuildCommands().empty()) {
  1064. sideEffects.insert(this);
  1065. } else {
  1066. for (auto const& source : this->GetAllConfigSources()) {
  1067. if (source.Source->GetCustomCommand() != nullptr) {
  1068. sideEffects.insert(this);
  1069. break;
  1070. }
  1071. }
  1072. }
  1073. }
  1074. void cmGeneratorTarget::AppendLanguageSideEffects(
  1075. std::map<std::string, std::set<cmGeneratorTarget const*>>& sideEffects) const
  1076. {
  1077. static const std::set<cm::string_view> LANGS_WITH_NO_SIDE_EFFECTS = {
  1078. "C"_s, "CXX"_s, "OBJC"_s, "OBJCXX"_s, "ASM"_s, "CUDA"_s, "HIP"_s
  1079. };
  1080. for (auto const& lang : this->GetAllConfigCompileLanguages()) {
  1081. if (!LANGS_WITH_NO_SIDE_EFFECTS.count(lang)) {
  1082. sideEffects[lang].insert(this);
  1083. }
  1084. }
  1085. }
  1086. bool cmGeneratorTarget::IsInBuildSystem() const
  1087. {
  1088. if (this->IsImported()) {
  1089. return false;
  1090. }
  1091. switch (this->Target->GetType()) {
  1092. case cmStateEnums::EXECUTABLE:
  1093. case cmStateEnums::STATIC_LIBRARY:
  1094. case cmStateEnums::SHARED_LIBRARY:
  1095. case cmStateEnums::MODULE_LIBRARY:
  1096. case cmStateEnums::OBJECT_LIBRARY:
  1097. case cmStateEnums::UTILITY:
  1098. case cmStateEnums::GLOBAL_TARGET:
  1099. return true;
  1100. case cmStateEnums::INTERFACE_LIBRARY:
  1101. // An INTERFACE library is in the build system if it has SOURCES
  1102. // or C++ module filesets.
  1103. if (!this->SourceEntries.empty() ||
  1104. !this->Target->GetHeaderSetsEntries().empty() ||
  1105. !this->Target->GetCxxModuleSetsEntries().empty()) {
  1106. return true;
  1107. }
  1108. break;
  1109. case cmStateEnums::UNKNOWN_LIBRARY:
  1110. break;
  1111. }
  1112. return false;
  1113. }
  1114. bool cmGeneratorTarget::IsNormal() const
  1115. {
  1116. return this->Target->IsNormal();
  1117. }
  1118. bool cmGeneratorTarget::IsRuntimeBinary() const
  1119. {
  1120. return this->Target->IsRuntimeBinary();
  1121. }
  1122. bool cmGeneratorTarget::IsSynthetic() const
  1123. {
  1124. return this->Target->IsSynthetic();
  1125. }
  1126. bool cmGeneratorTarget::IsImported() const
  1127. {
  1128. return this->Target->IsImported();
  1129. }
  1130. bool cmGeneratorTarget::IsImportedGloballyVisible() const
  1131. {
  1132. return this->Target->IsImportedGloballyVisible();
  1133. }
  1134. bool cmGeneratorTarget::CanCompileSources() const
  1135. {
  1136. return this->Target->CanCompileSources();
  1137. }
  1138. bool cmGeneratorTarget::HasKnownRuntimeArtifactLocation(
  1139. std::string const& config) const
  1140. {
  1141. if (!this->IsRuntimeBinary()) {
  1142. return false;
  1143. }
  1144. if (!this->IsImported()) {
  1145. return true;
  1146. }
  1147. ImportInfo const* info = this->GetImportInfo(config);
  1148. return info && !info->Location.empty();
  1149. }
  1150. const std::string& cmGeneratorTarget::GetLocationForBuild() const
  1151. {
  1152. static std::string location;
  1153. if (this->IsImported()) {
  1154. location = this->Target->ImportedGetFullPath(
  1155. "", cmStateEnums::RuntimeBinaryArtifact);
  1156. return location;
  1157. }
  1158. // Now handle the deprecated build-time configuration location.
  1159. std::string const noConfig;
  1160. location = this->GetDirectory(noConfig);
  1161. cmValue cfgid = this->Makefile->GetDefinition("CMAKE_CFG_INTDIR");
  1162. if (cfgid && (*cfgid != ".")) {
  1163. location += "/";
  1164. location += *cfgid;
  1165. }
  1166. if (this->IsAppBundleOnApple()) {
  1167. std::string macdir = this->BuildBundleDirectory("", "", FullLevel);
  1168. if (!macdir.empty()) {
  1169. location += "/";
  1170. location += macdir;
  1171. }
  1172. }
  1173. location += "/";
  1174. location += this->GetFullName("", cmStateEnums::RuntimeBinaryArtifact);
  1175. return location;
  1176. }
  1177. bool cmGeneratorTarget::IsSystemIncludeDirectory(
  1178. const std::string& dir, const std::string& config,
  1179. const std::string& language) const
  1180. {
  1181. std::string config_upper;
  1182. if (!config.empty()) {
  1183. config_upper = cmSystemTools::UpperCase(config);
  1184. }
  1185. std::string key = cmStrCat(config_upper, '/', language);
  1186. auto iter = this->SystemIncludesCache.find(key);
  1187. if (iter == this->SystemIncludesCache.end()) {
  1188. cmGeneratorExpressionDAGChecker dagChecker(
  1189. this, "SYSTEM_INCLUDE_DIRECTORIES", nullptr, nullptr);
  1190. bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
  1191. cmList result;
  1192. for (std::string const& it : this->Target->GetSystemIncludeDirectories()) {
  1193. result.append(cmGeneratorExpression::Evaluate(it, this->LocalGenerator,
  1194. config, this, &dagChecker,
  1195. nullptr, language));
  1196. }
  1197. std::vector<cmGeneratorTarget const*> const& deps =
  1198. this->GetLinkImplementationClosure(config);
  1199. for (cmGeneratorTarget const* dep : deps) {
  1200. handleSystemIncludesDep(this->LocalGenerator, dep, config, this,
  1201. &dagChecker, result, excludeImported, language);
  1202. }
  1203. cmLinkImplementation const* impl =
  1204. this->GetLinkImplementation(config, LinkInterfaceFor::Usage);
  1205. if (impl != nullptr) {
  1206. auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
  1207. if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
  1208. for (auto const& lib : runtimeEntries->second) {
  1209. if (lib.Target) {
  1210. handleSystemIncludesDep(this->LocalGenerator, lib.Target, config,
  1211. this, &dagChecker, result, excludeImported,
  1212. language);
  1213. }
  1214. }
  1215. }
  1216. }
  1217. std::for_each(result.begin(), result.end(),
  1218. cmSystemTools::ConvertToUnixSlashes);
  1219. std::sort(result.begin(), result.end());
  1220. result.erase(std::unique(result.begin(), result.end()), result.end());
  1221. iter = this->SystemIncludesCache.emplace(key, result).first;
  1222. }
  1223. return std::binary_search(iter->second.begin(), iter->second.end(), dir);
  1224. }
  1225. bool cmGeneratorTarget::GetPropertyAsBool(const std::string& prop) const
  1226. {
  1227. return this->Target->GetPropertyAsBool(prop);
  1228. }
  1229. bool cmGeneratorTarget::MaybeHaveInterfaceProperty(
  1230. std::string const& prop, cmGeneratorExpressionContext* context,
  1231. LinkInterfaceFor interfaceFor) const
  1232. {
  1233. std::string const key = prop + '@' + context->Config;
  1234. auto i = this->MaybeInterfacePropertyExists.find(key);
  1235. if (i == this->MaybeInterfacePropertyExists.end()) {
  1236. // Insert an entry now in case there is a cycle.
  1237. i = this->MaybeInterfacePropertyExists.emplace(key, false).first;
  1238. bool& maybeInterfaceProp = i->second;
  1239. // If this target itself has a non-empty property value, we are done.
  1240. maybeInterfaceProp = cmNonempty(this->GetProperty(prop));
  1241. // Otherwise, recurse to interface dependencies.
  1242. if (!maybeInterfaceProp) {
  1243. cmGeneratorTarget const* headTarget =
  1244. context->HeadTarget ? context->HeadTarget : this;
  1245. if (cmLinkInterfaceLibraries const* iface =
  1246. this->GetLinkInterfaceLibraries(context->Config, headTarget,
  1247. interfaceFor)) {
  1248. if (iface->HadHeadSensitiveCondition) {
  1249. // With a different head target we may get to a library with
  1250. // this interface property.
  1251. maybeInterfaceProp = true;
  1252. } else {
  1253. // The transitive interface libraries do not depend on the
  1254. // head target, so we can follow them.
  1255. for (cmLinkItem const& lib : iface->Libraries) {
  1256. if (lib.Target &&
  1257. lib.Target->MaybeHaveInterfaceProperty(prop, context,
  1258. interfaceFor)) {
  1259. maybeInterfaceProp = true;
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. }
  1266. }
  1267. return i->second;
  1268. }
  1269. std::string cmGeneratorTarget::EvaluateInterfaceProperty(
  1270. std::string const& prop, cmGeneratorExpressionContext* context,
  1271. cmGeneratorExpressionDAGChecker* dagCheckerParent,
  1272. LinkInterfaceFor interfaceFor) const
  1273. {
  1274. std::string result;
  1275. // If the property does not appear transitively at all, we are done.
  1276. if (!this->MaybeHaveInterfaceProperty(prop, context, interfaceFor)) {
  1277. return result;
  1278. }
  1279. // Evaluate $<TARGET_PROPERTY:this,prop> as if it were compiled. This is
  1280. // a subset of TargetPropertyNode::Evaluate without stringify/parse steps
  1281. // but sufficient for transitive interface properties.
  1282. cmGeneratorExpressionDAGChecker dagChecker(context->Backtrace, this, prop,
  1283. nullptr, dagCheckerParent);
  1284. switch (dagChecker.Check()) {
  1285. case cmGeneratorExpressionDAGChecker::SELF_REFERENCE:
  1286. dagChecker.ReportError(
  1287. context, "$<TARGET_PROPERTY:" + this->GetName() + "," + prop + ">");
  1288. return result;
  1289. case cmGeneratorExpressionDAGChecker::CYCLIC_REFERENCE:
  1290. // No error. We just skip cyclic references.
  1291. case cmGeneratorExpressionDAGChecker::ALREADY_SEEN:
  1292. // No error. We have already seen this transitive property.
  1293. return result;
  1294. case cmGeneratorExpressionDAGChecker::DAG:
  1295. break;
  1296. }
  1297. cmGeneratorTarget const* headTarget =
  1298. context->HeadTarget ? context->HeadTarget : this;
  1299. if (cmValue p = this->GetProperty(prop)) {
  1300. result = cmGeneratorExpressionNode::EvaluateDependentExpression(
  1301. *p, context->LG, context, headTarget, &dagChecker, this);
  1302. }
  1303. if (cmLinkInterfaceLibraries const* iface = this->GetLinkInterfaceLibraries(
  1304. context->Config, headTarget, interfaceFor)) {
  1305. context->HadContextSensitiveCondition =
  1306. context->HadContextSensitiveCondition ||
  1307. iface->HadContextSensitiveCondition;
  1308. for (cmLinkItem const& lib : iface->Libraries) {
  1309. // Broken code can have a target in its own link interface.
  1310. // Don't follow such link interface entries so as not to create a
  1311. // self-referencing loop.
  1312. if (lib.Target && lib.Target != this) {
  1313. // Pretend $<TARGET_PROPERTY:lib.Target,prop> appeared in the
  1314. // above property and hand-evaluate it as if it were compiled.
  1315. // Create a context as cmCompiledGeneratorExpression::Evaluate does.
  1316. cmGeneratorExpressionContext libContext(
  1317. context->LG, context->Config, context->Quiet, headTarget, this,
  1318. context->EvaluateForBuildsystem, context->Backtrace,
  1319. context->Language);
  1320. std::string libResult = cmGeneratorExpression::StripEmptyListElements(
  1321. lib.Target->EvaluateInterfaceProperty(prop, &libContext, &dagChecker,
  1322. interfaceFor));
  1323. if (!libResult.empty()) {
  1324. if (result.empty()) {
  1325. result = std::move(libResult);
  1326. } else {
  1327. result.reserve(result.size() + 1 + libResult.size());
  1328. result += ";";
  1329. result += libResult;
  1330. }
  1331. }
  1332. context->HadContextSensitiveCondition =
  1333. context->HadContextSensitiveCondition ||
  1334. libContext.HadContextSensitiveCondition;
  1335. context->HadHeadSensitiveCondition =
  1336. context->HadHeadSensitiveCondition ||
  1337. libContext.HadHeadSensitiveCondition;
  1338. }
  1339. }
  1340. }
  1341. return result;
  1342. }
  1343. namespace {
  1344. enum class IncludeDirectoryFallBack
  1345. {
  1346. BINARY,
  1347. OBJECT
  1348. };
  1349. std::string AddLangSpecificInterfaceIncludeDirectories(
  1350. const cmGeneratorTarget* root, const cmGeneratorTarget* target,
  1351. const std::string& lang, const std::string& config,
  1352. const std::string& propertyName, IncludeDirectoryFallBack mode,
  1353. cmGeneratorExpressionDAGChecker* context)
  1354. {
  1355. cmGeneratorExpressionDAGChecker dag{ target->GetBacktrace(), target,
  1356. propertyName, nullptr, context };
  1357. switch (dag.Check()) {
  1358. case cmGeneratorExpressionDAGChecker::SELF_REFERENCE:
  1359. dag.ReportError(
  1360. nullptr, "$<TARGET_PROPERTY:" + target->GetName() + ",propertyName");
  1361. CM_FALLTHROUGH;
  1362. case cmGeneratorExpressionDAGChecker::CYCLIC_REFERENCE:
  1363. // No error. We just skip cyclic references.
  1364. case cmGeneratorExpressionDAGChecker::ALREADY_SEEN:
  1365. // No error. We have already seen this transitive property.
  1366. return "";
  1367. case cmGeneratorExpressionDAGChecker::DAG:
  1368. break;
  1369. }
  1370. std::string directories;
  1371. if (const auto* link_interface = target->GetLinkInterfaceLibraries(
  1372. config, root, LinkInterfaceFor::Usage)) {
  1373. for (const cmLinkItem& library : link_interface->Libraries) {
  1374. if (const cmGeneratorTarget* dependency = library.Target) {
  1375. if (cm::contains(dependency->GetAllConfigCompileLanguages(), lang)) {
  1376. auto* lg = dependency->GetLocalGenerator();
  1377. std::string value = dependency->GetSafeProperty(propertyName);
  1378. if (value.empty()) {
  1379. if (mode == IncludeDirectoryFallBack::BINARY) {
  1380. value = lg->GetCurrentBinaryDirectory();
  1381. } else if (mode == IncludeDirectoryFallBack::OBJECT) {
  1382. value = cmStrCat(lg->GetCurrentBinaryDirectory(), '/',
  1383. lg->GetTargetDirectory(dependency));
  1384. }
  1385. }
  1386. if (!directories.empty()) {
  1387. directories += ";";
  1388. }
  1389. directories += value;
  1390. }
  1391. }
  1392. }
  1393. }
  1394. return directories;
  1395. }
  1396. void AddLangSpecificImplicitIncludeDirectories(
  1397. const cmGeneratorTarget* target, const std::string& lang,
  1398. const std::string& config, const std::string& propertyName,
  1399. IncludeDirectoryFallBack mode, EvaluatedTargetPropertyEntries& entries)
  1400. {
  1401. if (const auto* libraries = target->GetLinkImplementationLibraries(
  1402. config, LinkInterfaceFor::Usage)) {
  1403. cmGeneratorExpressionDAGChecker dag{ target->GetBacktrace(), target,
  1404. propertyName, nullptr, nullptr };
  1405. for (const cmLinkImplItem& library : libraries->Libraries) {
  1406. if (const cmGeneratorTarget* dependency = library.Target) {
  1407. if (!dependency->IsInBuildSystem()) {
  1408. continue;
  1409. }
  1410. if (cm::contains(dependency->GetAllConfigCompileLanguages(), lang)) {
  1411. auto* lg = dependency->GetLocalGenerator();
  1412. EvaluatedTargetPropertyEntry entry{ library, library.Backtrace };
  1413. if (cmValue val = dependency->GetProperty(propertyName)) {
  1414. entry.Values.emplace_back(*val);
  1415. } else {
  1416. if (mode == IncludeDirectoryFallBack::BINARY) {
  1417. entry.Values.emplace_back(lg->GetCurrentBinaryDirectory());
  1418. } else if (mode == IncludeDirectoryFallBack::OBJECT) {
  1419. entry.Values.emplace_back(
  1420. dependency->GetObjectDirectory(config));
  1421. }
  1422. }
  1423. cmExpandList(
  1424. AddLangSpecificInterfaceIncludeDirectories(
  1425. target, dependency, lang, config, propertyName, mode, &dag),
  1426. entry.Values);
  1427. entries.Entries.emplace_back(std::move(entry));
  1428. }
  1429. }
  1430. }
  1431. }
  1432. }
  1433. void AddObjectEntries(cmGeneratorTarget const* headTarget,
  1434. std::string const& config,
  1435. cmGeneratorExpressionDAGChecker* dagChecker,
  1436. EvaluatedTargetPropertyEntries& entries)
  1437. {
  1438. if (cmLinkImplementationLibraries const* impl =
  1439. headTarget->GetLinkImplementationLibraries(config,
  1440. LinkInterfaceFor::Usage)) {
  1441. entries.HadContextSensitiveCondition = impl->HadContextSensitiveCondition;
  1442. for (cmLinkImplItem const& lib : impl->Libraries) {
  1443. if (lib.Target &&
  1444. lib.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1445. std::string uniqueName =
  1446. headTarget->GetGlobalGenerator()->IndexGeneratorTargetUniquely(
  1447. lib.Target);
  1448. std::string genex = "$<TARGET_OBJECTS:" + std::move(uniqueName) + ">";
  1449. cmGeneratorExpression ge(*headTarget->Makefile->GetCMakeInstance(),
  1450. lib.Backtrace);
  1451. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(genex);
  1452. cge->SetEvaluateForBuildsystem(true);
  1453. EvaluatedTargetPropertyEntry ee(lib, lib.Backtrace);
  1454. cmExpandList(cge->Evaluate(headTarget->GetLocalGenerator(), config,
  1455. headTarget, dagChecker),
  1456. ee.Values);
  1457. if (cge->GetHadContextSensitiveCondition()) {
  1458. ee.ContextDependent = true;
  1459. }
  1460. entries.Entries.emplace_back(std::move(ee));
  1461. }
  1462. }
  1463. }
  1464. }
  1465. void addFileSetEntry(cmGeneratorTarget const* headTarget,
  1466. std::string const& config,
  1467. cmGeneratorExpressionDAGChecker* dagChecker,
  1468. cmFileSet const* fileSet,
  1469. EvaluatedTargetPropertyEntries& entries)
  1470. {
  1471. auto dirCges = fileSet->CompileDirectoryEntries();
  1472. auto dirs = fileSet->EvaluateDirectoryEntries(
  1473. dirCges, headTarget->GetLocalGenerator(), config, headTarget, dagChecker);
  1474. bool contextSensitiveDirs = false;
  1475. for (auto const& dirCge : dirCges) {
  1476. if (dirCge->GetHadContextSensitiveCondition()) {
  1477. contextSensitiveDirs = true;
  1478. break;
  1479. }
  1480. }
  1481. cmake* cm = headTarget->GetLocalGenerator()->GetCMakeInstance();
  1482. for (auto& entryCge : fileSet->CompileFileEntries()) {
  1483. TargetPropertyEntryFileSet tpe(dirs, contextSensitiveDirs,
  1484. std::move(entryCge), fileSet);
  1485. entries.Entries.emplace_back(
  1486. EvaluateTargetPropertyEntry(headTarget, config, "", dagChecker, tpe));
  1487. EvaluatedTargetPropertyEntry const& entry = entries.Entries.back();
  1488. for (auto const& file : entry.Values) {
  1489. auto* sf = headTarget->Makefile->GetOrCreateSource(file);
  1490. if (fileSet->GetType() == "HEADERS"_s) {
  1491. sf->SetProperty("HEADER_FILE_ONLY", "TRUE");
  1492. }
  1493. #ifndef CMAKE_BOOTSTRAP
  1494. std::string e;
  1495. std::string w;
  1496. auto path = sf->ResolveFullPath(&e, &w);
  1497. if (!w.empty()) {
  1498. cm->IssueMessage(MessageType::AUTHOR_WARNING, w, entry.Backtrace);
  1499. }
  1500. if (path.empty()) {
  1501. if (!e.empty()) {
  1502. cm->IssueMessage(MessageType::FATAL_ERROR, e, entry.Backtrace);
  1503. }
  1504. return;
  1505. }
  1506. bool found = false;
  1507. for (auto const& sg : headTarget->Makefile->GetSourceGroups()) {
  1508. if (sg.MatchChildrenFiles(path)) {
  1509. found = true;
  1510. break;
  1511. }
  1512. }
  1513. if (!found) {
  1514. if (fileSet->GetType() == "HEADERS"_s) {
  1515. headTarget->Makefile->GetOrCreateSourceGroup("Header Files")
  1516. ->AddGroupFile(path);
  1517. }
  1518. }
  1519. #endif
  1520. }
  1521. }
  1522. }
  1523. void AddFileSetEntries(cmGeneratorTarget const* headTarget,
  1524. std::string const& config,
  1525. cmGeneratorExpressionDAGChecker* dagChecker,
  1526. EvaluatedTargetPropertyEntries& entries)
  1527. {
  1528. for (auto const& entry : headTarget->Target->GetHeaderSetsEntries()) {
  1529. for (auto const& name : cmList{ entry.Value }) {
  1530. auto const* headerSet = headTarget->Target->GetFileSet(name);
  1531. addFileSetEntry(headTarget, config, dagChecker, headerSet, entries);
  1532. }
  1533. }
  1534. for (auto const& entry : headTarget->Target->GetCxxModuleSetsEntries()) {
  1535. for (auto const& name : cmList{ entry.Value }) {
  1536. auto const* cxxModuleSet = headTarget->Target->GetFileSet(name);
  1537. addFileSetEntry(headTarget, config, dagChecker, cxxModuleSet, entries);
  1538. }
  1539. }
  1540. }
  1541. bool processSources(cmGeneratorTarget const* tgt,
  1542. EvaluatedTargetPropertyEntries& entries,
  1543. std::vector<BT<std::string>>& srcs,
  1544. std::unordered_set<std::string>& uniqueSrcs,
  1545. bool debugSources)
  1546. {
  1547. cmMakefile* mf = tgt->Target->GetMakefile();
  1548. bool contextDependent = entries.HadContextSensitiveCondition;
  1549. for (EvaluatedTargetPropertyEntry& entry : entries.Entries) {
  1550. if (entry.ContextDependent) {
  1551. contextDependent = true;
  1552. }
  1553. cmLinkImplItem const& item = entry.LinkImplItem;
  1554. std::string const& targetName = item.AsStr();
  1555. for (std::string& src : entry.Values) {
  1556. cmSourceFile* sf = mf->GetOrCreateSource(src);
  1557. std::string e;
  1558. std::string w;
  1559. std::string fullPath = sf->ResolveFullPath(&e, &w);
  1560. cmake* cm = tgt->GetLocalGenerator()->GetCMakeInstance();
  1561. if (!w.empty()) {
  1562. cm->IssueMessage(MessageType::AUTHOR_WARNING, w, entry.Backtrace);
  1563. }
  1564. if (fullPath.empty()) {
  1565. if (!e.empty()) {
  1566. cm->IssueMessage(MessageType::FATAL_ERROR, e, entry.Backtrace);
  1567. }
  1568. return contextDependent;
  1569. }
  1570. if (!targetName.empty() && !cmSystemTools::FileIsFullPath(src)) {
  1571. std::ostringstream err;
  1572. if (!targetName.empty()) {
  1573. err << "Target \"" << targetName
  1574. << "\" contains relative path in its INTERFACE_SOURCES:\n \""
  1575. << src << "\"";
  1576. } else {
  1577. err << "Found relative path while evaluating sources of \""
  1578. << tgt->GetName() << "\":\n \"" << src << "\"\n";
  1579. }
  1580. tgt->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
  1581. err.str());
  1582. return contextDependent;
  1583. }
  1584. src = fullPath;
  1585. }
  1586. std::string usedSources;
  1587. for (std::string const& src : entry.Values) {
  1588. if (uniqueSrcs.insert(src).second) {
  1589. srcs.emplace_back(src, entry.Backtrace);
  1590. if (debugSources) {
  1591. usedSources += " * " + src + "\n";
  1592. }
  1593. }
  1594. }
  1595. if (!usedSources.empty()) {
  1596. tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1597. MessageType::LOG,
  1598. std::string("Used sources for target ") + tgt->GetName() + ":\n" +
  1599. usedSources,
  1600. entry.Backtrace);
  1601. }
  1602. }
  1603. return contextDependent;
  1604. }
  1605. }
  1606. std::vector<BT<std::string>> cmGeneratorTarget::GetSourceFilePaths(
  1607. std::string const& config) const
  1608. {
  1609. std::vector<BT<std::string>> files;
  1610. if (!this->LocalGenerator->GetGlobalGenerator()->GetConfigureDoneCMP0026()) {
  1611. // At configure-time, this method can be called as part of getting the
  1612. // LOCATION property or to export() a file to be include()d. However
  1613. // there is no cmGeneratorTarget at configure-time, so search the SOURCES
  1614. // for TARGET_OBJECTS instead for backwards compatibility with OLD
  1615. // behavior of CMP0024 and CMP0026 only.
  1616. cmBTStringRange sourceEntries = this->Target->GetSourceEntries();
  1617. for (auto const& entry : sourceEntries) {
  1618. cmList items{ entry.Value };
  1619. for (auto const& item : items) {
  1620. if (cmHasLiteralPrefix(item, "$<TARGET_OBJECTS:") &&
  1621. item.back() == '>') {
  1622. continue;
  1623. }
  1624. files.emplace_back(item);
  1625. }
  1626. }
  1627. return files;
  1628. }
  1629. cmList debugProperties{ this->Makefile->GetDefinition(
  1630. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  1631. bool debugSources =
  1632. !this->DebugSourcesDone && cm::contains(debugProperties, "SOURCES");
  1633. if (this->LocalGenerator->GetGlobalGenerator()->GetConfigureDoneCMP0026()) {
  1634. this->DebugSourcesDone = true;
  1635. }
  1636. cmGeneratorExpressionDAGChecker dagChecker(this, "SOURCES", nullptr,
  1637. nullptr);
  1638. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  1639. this, config, std::string(), &dagChecker, this->SourceEntries);
  1640. std::unordered_set<std::string> uniqueSrcs;
  1641. bool contextDependentDirectSources =
  1642. processSources(this, entries, files, uniqueSrcs, debugSources);
  1643. // Collect INTERFACE_SOURCES of all direct link-dependencies.
  1644. EvaluatedTargetPropertyEntries linkInterfaceSourcesEntries;
  1645. AddInterfaceEntries(this, config, "INTERFACE_SOURCES", std::string(),
  1646. &dagChecker, linkInterfaceSourcesEntries,
  1647. IncludeRuntimeInterface::No, LinkInterfaceFor::Usage);
  1648. bool contextDependentInterfaceSources = processSources(
  1649. this, linkInterfaceSourcesEntries, files, uniqueSrcs, debugSources);
  1650. // Collect TARGET_OBJECTS of direct object link-dependencies.
  1651. bool contextDependentObjects = false;
  1652. if (this->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  1653. EvaluatedTargetPropertyEntries linkObjectsEntries;
  1654. AddObjectEntries(this, config, &dagChecker, linkObjectsEntries);
  1655. contextDependentObjects = processSources(this, linkObjectsEntries, files,
  1656. uniqueSrcs, debugSources);
  1657. // Note that for imported targets or multi-config generators supporting
  1658. // cross-config builds the paths to the object files must be per-config,
  1659. // so contextDependentObjects will be true here even if object libraries
  1660. // are specified without per-config generator expressions.
  1661. }
  1662. // Collect this target's file sets.
  1663. EvaluatedTargetPropertyEntries fileSetEntries;
  1664. AddFileSetEntries(this, config, &dagChecker, fileSetEntries);
  1665. bool contextDependentFileSets =
  1666. processSources(this, fileSetEntries, files, uniqueSrcs, debugSources);
  1667. // Determine if sources are context-dependent or not.
  1668. if (!contextDependentDirectSources && !contextDependentInterfaceSources &&
  1669. !contextDependentObjects && !contextDependentFileSets) {
  1670. this->SourcesAreContextDependent = Tribool::False;
  1671. } else {
  1672. this->SourcesAreContextDependent = Tribool::True;
  1673. }
  1674. return files;
  1675. }
  1676. void cmGeneratorTarget::GetSourceFiles(std::vector<cmSourceFile*>& files,
  1677. const std::string& config) const
  1678. {
  1679. std::vector<BT<cmSourceFile*>> tmp = this->GetSourceFiles(config);
  1680. files.reserve(tmp.size());
  1681. for (BT<cmSourceFile*>& v : tmp) {
  1682. files.push_back(v.Value);
  1683. }
  1684. }
  1685. std::vector<BT<cmSourceFile*>> cmGeneratorTarget::GetSourceFiles(
  1686. std::string const& config) const
  1687. {
  1688. std::vector<BT<cmSourceFile*>> files;
  1689. if (!this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  1690. // Since we are still configuring not all sources may exist yet,
  1691. // so we need to avoid full source classification because that
  1692. // requires the absolute paths to all sources to be determined.
  1693. // Since this is only for compatibility with old policies that
  1694. // projects should not depend on anymore, just compute the files
  1695. // without memoizing them.
  1696. std::vector<BT<std::string>> srcs = this->GetSourceFilePaths(config);
  1697. std::set<cmSourceFile*> emitted;
  1698. for (BT<std::string> const& s : srcs) {
  1699. cmSourceFile* sf = this->Makefile->GetOrCreateSource(s.Value);
  1700. if (emitted.insert(sf).second) {
  1701. files.emplace_back(sf, s.Backtrace);
  1702. }
  1703. }
  1704. return files;
  1705. }
  1706. KindedSources const& kinded = this->GetKindedSources(config);
  1707. files.reserve(kinded.Sources.size());
  1708. for (SourceAndKind const& si : kinded.Sources) {
  1709. files.push_back(si.Source);
  1710. }
  1711. return files;
  1712. }
  1713. void cmGeneratorTarget::GetSourceFilesWithoutObjectLibraries(
  1714. std::vector<cmSourceFile*>& files, const std::string& config) const
  1715. {
  1716. std::vector<BT<cmSourceFile*>> tmp =
  1717. this->GetSourceFilesWithoutObjectLibraries(config);
  1718. files.reserve(tmp.size());
  1719. for (BT<cmSourceFile*>& v : tmp) {
  1720. files.push_back(v.Value);
  1721. }
  1722. }
  1723. std::vector<BT<cmSourceFile*>>
  1724. cmGeneratorTarget::GetSourceFilesWithoutObjectLibraries(
  1725. std::string const& config) const
  1726. {
  1727. std::vector<BT<cmSourceFile*>> files;
  1728. KindedSources const& kinded = this->GetKindedSources(config);
  1729. files.reserve(kinded.Sources.size());
  1730. for (SourceAndKind const& si : kinded.Sources) {
  1731. if (si.Source.Value->GetObjectLibrary().empty()) {
  1732. files.push_back(si.Source);
  1733. }
  1734. }
  1735. return files;
  1736. }
  1737. cmGeneratorTarget::KindedSources const& cmGeneratorTarget::GetKindedSources(
  1738. std::string const& config) const
  1739. {
  1740. // If we already processed one configuration and found no dependency
  1741. // on configuration then always use the one result.
  1742. if (this->SourcesAreContextDependent == Tribool::False) {
  1743. return this->KindedSourcesMap.begin()->second;
  1744. }
  1745. // Lookup any existing link implementation for this configuration.
  1746. std::string const key = cmSystemTools::UpperCase(config);
  1747. auto it = this->KindedSourcesMap.find(key);
  1748. if (it != this->KindedSourcesMap.end()) {
  1749. if (!it->second.Initialized) {
  1750. std::ostringstream e;
  1751. e << "The SOURCES of \"" << this->GetName()
  1752. << "\" use a generator expression that depends on the "
  1753. "SOURCES themselves.";
  1754. this->GlobalGenerator->GetCMakeInstance()->IssueMessage(
  1755. MessageType::FATAL_ERROR, e.str(), this->GetBacktrace());
  1756. static KindedSources empty;
  1757. return empty;
  1758. }
  1759. return it->second;
  1760. }
  1761. // Add an entry to the map for this configuration.
  1762. KindedSources& files = this->KindedSourcesMap[key];
  1763. this->ComputeKindedSources(files, config);
  1764. files.Initialized = true;
  1765. return files;
  1766. }
  1767. void cmGeneratorTarget::ComputeKindedSources(KindedSources& files,
  1768. std::string const& config) const
  1769. {
  1770. // Get the source file paths by string.
  1771. std::vector<BT<std::string>> srcs = this->GetSourceFilePaths(config);
  1772. cmsys::RegularExpression header_regex(CM_HEADER_REGEX);
  1773. std::vector<cmSourceFile*> badObjLib;
  1774. std::set<cmSourceFile*> emitted;
  1775. for (BT<std::string> const& s : srcs) {
  1776. // Create each source at most once.
  1777. cmSourceFile* sf = this->Makefile->GetOrCreateSource(s.Value);
  1778. if (!emitted.insert(sf).second) {
  1779. continue;
  1780. }
  1781. // Compute the kind (classification) of this source file.
  1782. SourceKind kind;
  1783. std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
  1784. cmFileSet const* fs = this->GetFileSetForSource(config, sf);
  1785. if (sf->GetCustomCommand()) {
  1786. kind = SourceKindCustomCommand;
  1787. } else if (!this->Target->IsNormal() && !this->Target->IsImported() &&
  1788. fs && (fs->GetType() == "CXX_MODULES"_s)) {
  1789. kind = SourceKindCxxModuleSource;
  1790. } else if (this->Target->GetType() == cmStateEnums::UTILITY ||
  1791. this->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY
  1792. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  1793. // NOLINTNEXTLINE(bugprone-branch-clone)
  1794. ) {
  1795. kind = SourceKindExtra;
  1796. } else if (this->IsSourceFilePartOfUnityBatch(sf->ResolveFullPath())) {
  1797. kind = SourceKindUnityBatched;
  1798. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  1799. // NOLINTNEXTLINE(bugprone-branch-clone)
  1800. } else if (sf->GetPropertyAsBool("HEADER_FILE_ONLY")) {
  1801. kind = SourceKindHeader;
  1802. } else if (sf->GetPropertyAsBool("EXTERNAL_OBJECT")) {
  1803. kind = SourceKindExternalObject;
  1804. } else if (!sf->GetOrDetermineLanguage().empty()) {
  1805. kind = SourceKindObjectSource;
  1806. } else if (ext == "def") {
  1807. kind = SourceKindModuleDefinition;
  1808. if (this->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1809. badObjLib.push_back(sf);
  1810. }
  1811. } else if (ext == "idl") {
  1812. kind = SourceKindIDL;
  1813. if (this->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1814. badObjLib.push_back(sf);
  1815. }
  1816. } else if (ext == "resx") {
  1817. kind = SourceKindResx;
  1818. } else if (ext == "appxmanifest") {
  1819. kind = SourceKindAppManifest;
  1820. } else if (ext == "manifest") {
  1821. if (sf->GetPropertyAsBool("VS_DEPLOYMENT_CONTENT")) {
  1822. kind = SourceKindExtra;
  1823. } else {
  1824. kind = SourceKindManifest;
  1825. }
  1826. } else if (ext == "pfx") {
  1827. kind = SourceKindCertificate;
  1828. } else if (ext == "xaml") {
  1829. kind = SourceKindXaml;
  1830. } else if (header_regex.find(sf->ResolveFullPath())) {
  1831. kind = SourceKindHeader;
  1832. } else {
  1833. kind = SourceKindExtra;
  1834. }
  1835. // Save this classified source file in the result vector.
  1836. files.Sources.push_back({ BT<cmSourceFile*>(sf, s.Backtrace), kind });
  1837. }
  1838. if (!badObjLib.empty()) {
  1839. std::ostringstream e;
  1840. e << "OBJECT library \"" << this->GetName() << "\" contains:\n";
  1841. for (cmSourceFile* i : badObjLib) {
  1842. e << " " << i->GetLocation().GetName() << "\n";
  1843. }
  1844. e << "but may contain only sources that compile, header files, and "
  1845. "other files that would not affect linking of a normal library.";
  1846. this->GlobalGenerator->GetCMakeInstance()->IssueMessage(
  1847. MessageType::FATAL_ERROR, e.str(), this->GetBacktrace());
  1848. }
  1849. }
  1850. std::vector<cmGeneratorTarget::AllConfigSource> const&
  1851. cmGeneratorTarget::GetAllConfigSources() const
  1852. {
  1853. if (this->AllConfigSources.empty()) {
  1854. this->ComputeAllConfigSources();
  1855. }
  1856. return this->AllConfigSources;
  1857. }
  1858. void cmGeneratorTarget::ComputeAllConfigSources() const
  1859. {
  1860. std::vector<std::string> configs =
  1861. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1862. std::map<cmSourceFile const*, size_t> index;
  1863. for (size_t ci = 0; ci < configs.size(); ++ci) {
  1864. KindedSources const& sources = this->GetKindedSources(configs[ci]);
  1865. for (SourceAndKind const& src : sources.Sources) {
  1866. auto mi = index.find(src.Source.Value);
  1867. if (mi == index.end()) {
  1868. AllConfigSource acs;
  1869. acs.Source = src.Source.Value;
  1870. acs.Kind = src.Kind;
  1871. this->AllConfigSources.push_back(std::move(acs));
  1872. std::map<cmSourceFile const*, size_t>::value_type entry(
  1873. src.Source.Value, this->AllConfigSources.size() - 1);
  1874. mi = index.insert(entry).first;
  1875. }
  1876. this->AllConfigSources[mi->second].Configs.push_back(ci);
  1877. }
  1878. }
  1879. }
  1880. std::vector<cmGeneratorTarget::AllConfigSource>
  1881. cmGeneratorTarget::GetAllConfigSources(SourceKind kind) const
  1882. {
  1883. std::vector<AllConfigSource> result;
  1884. for (AllConfigSource const& source : this->GetAllConfigSources()) {
  1885. if (source.Kind == kind) {
  1886. result.push_back(source);
  1887. }
  1888. }
  1889. return result;
  1890. }
  1891. std::set<std::string> cmGeneratorTarget::GetAllConfigCompileLanguages() const
  1892. {
  1893. std::set<std::string> languages;
  1894. std::vector<AllConfigSource> const& sources = this->GetAllConfigSources();
  1895. for (AllConfigSource const& si : sources) {
  1896. std::string const& lang = si.Source->GetOrDetermineLanguage();
  1897. if (!lang.empty()) {
  1898. languages.emplace(lang);
  1899. }
  1900. }
  1901. return languages;
  1902. }
  1903. std::string cmGeneratorTarget::GetCompilePDBName(
  1904. const std::string& config) const
  1905. {
  1906. // Check for a per-configuration output directory target property.
  1907. std::string configUpper = cmSystemTools::UpperCase(config);
  1908. std::string configProp = cmStrCat("COMPILE_PDB_NAME_", configUpper);
  1909. cmValue config_name = this->GetProperty(configProp);
  1910. if (cmNonempty(config_name)) {
  1911. NameComponents const& components = GetFullNameInternalComponents(
  1912. config, cmStateEnums::RuntimeBinaryArtifact);
  1913. return components.prefix + *config_name + ".pdb";
  1914. }
  1915. cmValue name = this->GetProperty("COMPILE_PDB_NAME");
  1916. if (cmNonempty(name)) {
  1917. NameComponents const& components = GetFullNameInternalComponents(
  1918. config, cmStateEnums::RuntimeBinaryArtifact);
  1919. return components.prefix + *name + ".pdb";
  1920. }
  1921. return "";
  1922. }
  1923. std::string cmGeneratorTarget::GetCompilePDBPath(
  1924. const std::string& config) const
  1925. {
  1926. std::string dir = this->GetCompilePDBDirectory(config);
  1927. std::string name = this->GetCompilePDBName(config);
  1928. if (dir.empty() && !name.empty() && this->HaveWellDefinedOutputFiles()) {
  1929. dir = this->GetPDBDirectory(config);
  1930. }
  1931. if (!dir.empty()) {
  1932. dir += "/";
  1933. }
  1934. return dir + name;
  1935. }
  1936. bool cmGeneratorTarget::HasSOName(const std::string& config) const
  1937. {
  1938. // soname is supported only for shared libraries and modules,
  1939. // and then only when the platform supports an soname flag.
  1940. return ((this->GetType() == cmStateEnums::SHARED_LIBRARY) &&
  1941. !this->GetPropertyAsBool("NO_SONAME") &&
  1942. this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)));
  1943. }
  1944. bool cmGeneratorTarget::NeedRelinkBeforeInstall(
  1945. const std::string& config) const
  1946. {
  1947. // Only executables and shared libraries can have an rpath and may
  1948. // need relinking.
  1949. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  1950. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1951. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1952. return false;
  1953. }
  1954. // If there is no install location this target will not be installed
  1955. // and therefore does not need relinking.
  1956. if (!this->Target->GetHaveInstallRule()) {
  1957. return false;
  1958. }
  1959. // If skipping all rpaths completely then no relinking is needed.
  1960. if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
  1961. return false;
  1962. }
  1963. // If building with the install-tree rpath no relinking is needed.
  1964. if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
  1965. return false;
  1966. }
  1967. // If chrpath is going to be used no relinking is needed.
  1968. if (this->IsChrpathUsed(config)) {
  1969. return false;
  1970. }
  1971. // Check for rpath support on this platform.
  1972. std::string ll = this->GetLinkerLanguage(config);
  1973. if (!ll.empty()) {
  1974. std::string flagVar =
  1975. cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG");
  1976. if (!this->Makefile->IsSet(flagVar)) {
  1977. // There is no rpath support on this platform so nothing needs
  1978. // relinking.
  1979. return false;
  1980. }
  1981. } else {
  1982. // No linker language is known. This error will be reported by
  1983. // other code.
  1984. return false;
  1985. }
  1986. // If either a build or install tree rpath is set then the rpath
  1987. // will likely change between the build tree and install tree and
  1988. // this target must be relinked.
  1989. bool have_rpath =
  1990. this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH(config);
  1991. bool is_ninja = this->LocalGenerator->GetGlobalGenerator()->IsNinja();
  1992. if (have_rpath && is_ninja) {
  1993. std::ostringstream w;
  1994. /* clang-format off */
  1995. w <<
  1996. "The install of the " << this->GetName() << " target requires changing "
  1997. "an RPATH from the build tree, but this is not supported with the Ninja "
  1998. "generator unless on an ELF-based or XCOFF-based platform. "
  1999. "The CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this "
  2000. "relinking step."
  2001. ;
  2002. /* clang-format on */
  2003. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  2004. cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
  2005. }
  2006. return have_rpath;
  2007. }
  2008. bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const
  2009. {
  2010. // Only certain target types have an rpath.
  2011. if (!(this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2012. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2013. this->GetType() == cmStateEnums::EXECUTABLE)) {
  2014. return false;
  2015. }
  2016. // If the target will not be installed we do not need to change its
  2017. // rpath.
  2018. if (!this->Target->GetHaveInstallRule()) {
  2019. return false;
  2020. }
  2021. // Skip chrpath if skipping rpath altogether.
  2022. if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
  2023. return false;
  2024. }
  2025. // Skip chrpath if it does not need to be changed at install time.
  2026. if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
  2027. return false;
  2028. }
  2029. // Allow the user to disable builtin chrpath explicitly.
  2030. if (this->Makefile->IsOn("CMAKE_NO_BUILTIN_CHRPATH")) {
  2031. return false;
  2032. }
  2033. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  2034. return true;
  2035. }
  2036. // Enable if the rpath flag uses a separator and the target uses
  2037. // binaries we know how to edit.
  2038. std::string ll = this->GetLinkerLanguage(config);
  2039. if (!ll.empty()) {
  2040. std::string sepVar =
  2041. cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP");
  2042. cmValue sep = this->Makefile->GetDefinition(sepVar);
  2043. if (cmNonempty(sep)) {
  2044. // TODO: Add binary format check to ABI detection and get rid of
  2045. // CMAKE_EXECUTABLE_FORMAT.
  2046. if (cmValue fmt =
  2047. this->Makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT")) {
  2048. if (*fmt == "ELF") {
  2049. return true;
  2050. }
  2051. #if defined(CMake_USE_XCOFF_PARSER)
  2052. if (*fmt == "XCOFF") {
  2053. return true;
  2054. }
  2055. #endif
  2056. }
  2057. }
  2058. }
  2059. return false;
  2060. }
  2061. bool cmGeneratorTarget::IsImportedSharedLibWithoutSOName(
  2062. const std::string& config) const
  2063. {
  2064. if (this->IsImported() && this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2065. if (cmGeneratorTarget::ImportInfo const* info =
  2066. this->GetImportInfo(config)) {
  2067. return info->NoSOName;
  2068. }
  2069. }
  2070. return false;
  2071. }
  2072. bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
  2073. const std::string& config) const
  2074. {
  2075. TargetPtrToBoolMap& cache = this->MacOSXRpathInstallNameDirCache[config];
  2076. const auto lookup = cache.find(this->Target);
  2077. if (lookup != cache.cend()) {
  2078. return lookup->second;
  2079. }
  2080. const bool result = this->DetermineHasMacOSXRpathInstallNameDir(config);
  2081. cache[this->Target] = result;
  2082. return result;
  2083. }
  2084. bool cmGeneratorTarget::DetermineHasMacOSXRpathInstallNameDir(
  2085. const std::string& config) const
  2086. {
  2087. bool install_name_is_rpath = false;
  2088. bool macosx_rpath = false;
  2089. if (!this->IsImported()) {
  2090. if (this->GetType() != cmStateEnums::SHARED_LIBRARY) {
  2091. return false;
  2092. }
  2093. cmValue install_name = this->GetProperty("INSTALL_NAME_DIR");
  2094. bool use_install_name = this->MacOSXUseInstallNameDir();
  2095. if (install_name && use_install_name && *install_name == "@rpath") {
  2096. install_name_is_rpath = true;
  2097. } else if (install_name && use_install_name) {
  2098. return false;
  2099. }
  2100. if (!install_name_is_rpath) {
  2101. macosx_rpath = this->MacOSXRpathInstallNameDirDefault();
  2102. }
  2103. } else {
  2104. // Lookup the imported soname.
  2105. if (cmGeneratorTarget::ImportInfo const* info =
  2106. this->GetImportInfo(config)) {
  2107. if (!info->NoSOName && !info->SOName.empty()) {
  2108. if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
  2109. install_name_is_rpath = true;
  2110. }
  2111. } else {
  2112. std::string install_name;
  2113. cmSystemTools::GuessLibraryInstallName(info->Location, install_name);
  2114. if (install_name.find("@rpath") != std::string::npos) {
  2115. install_name_is_rpath = true;
  2116. }
  2117. }
  2118. }
  2119. }
  2120. if (!install_name_is_rpath && !macosx_rpath) {
  2121. return false;
  2122. }
  2123. if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
  2124. std::ostringstream w;
  2125. w << "Attempting to use ";
  2126. if (macosx_rpath) {
  2127. w << "MACOSX_RPATH";
  2128. } else {
  2129. w << "@rpath";
  2130. }
  2131. w << " without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set.";
  2132. w << " This could be because you are using a Mac OS X version";
  2133. w << " less than 10.5 or because CMake's platform configuration is";
  2134. w << " corrupt.";
  2135. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  2136. cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
  2137. }
  2138. return true;
  2139. }
  2140. bool cmGeneratorTarget::MacOSXRpathInstallNameDirDefault() const
  2141. {
  2142. // we can't do rpaths when unsupported
  2143. if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
  2144. return false;
  2145. }
  2146. cmValue macosx_rpath_str = this->GetProperty("MACOSX_RPATH");
  2147. if (macosx_rpath_str) {
  2148. return this->GetPropertyAsBool("MACOSX_RPATH");
  2149. }
  2150. cmPolicies::PolicyStatus cmp0042 = this->GetPolicyStatusCMP0042();
  2151. if (cmp0042 == cmPolicies::WARN) {
  2152. this->LocalGenerator->GetGlobalGenerator()->AddCMP0042WarnTarget(
  2153. this->GetName());
  2154. }
  2155. return cmp0042 == cmPolicies::NEW;
  2156. }
  2157. bool cmGeneratorTarget::MacOSXUseInstallNameDir() const
  2158. {
  2159. cmValue build_with_install_name =
  2160. this->GetProperty("BUILD_WITH_INSTALL_NAME_DIR");
  2161. if (build_with_install_name) {
  2162. return build_with_install_name.IsOn();
  2163. }
  2164. cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
  2165. if (cmp0068 == cmPolicies::NEW) {
  2166. return false;
  2167. }
  2168. bool use_install_name = this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH");
  2169. if (use_install_name && cmp0068 == cmPolicies::WARN) {
  2170. this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
  2171. this->GetName());
  2172. }
  2173. return use_install_name;
  2174. }
  2175. bool cmGeneratorTarget::CanGenerateInstallNameDir(
  2176. InstallNameType name_type) const
  2177. {
  2178. cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
  2179. if (cmp0068 == cmPolicies::NEW) {
  2180. return true;
  2181. }
  2182. bool skip = this->Makefile->IsOn("CMAKE_SKIP_RPATH");
  2183. if (name_type == INSTALL_NAME_FOR_INSTALL) {
  2184. skip |= this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  2185. } else {
  2186. skip |= this->GetPropertyAsBool("SKIP_BUILD_RPATH");
  2187. }
  2188. if (skip && cmp0068 == cmPolicies::WARN) {
  2189. this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
  2190. this->GetName());
  2191. }
  2192. return !skip;
  2193. }
  2194. std::string cmGeneratorTarget::GetSOName(
  2195. const std::string& config, cmStateEnums::ArtifactType artifact) const
  2196. {
  2197. if (this->IsImported()) {
  2198. // Lookup the imported soname.
  2199. if (cmGeneratorTarget::ImportInfo const* info =
  2200. this->GetImportInfo(config)) {
  2201. if (info->NoSOName) {
  2202. // The imported library has no builtin soname so the name
  2203. // searched at runtime will be just the filename.
  2204. return cmSystemTools::GetFilenameName(info->Location);
  2205. }
  2206. // Use the soname given if any.
  2207. if (this->IsFrameworkOnApple()) {
  2208. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  2209. info->SOName, cmGlobalGenerator::FrameworkFormat::Strict);
  2210. if (fwDescriptor) {
  2211. return fwDescriptor->GetVersionedName();
  2212. }
  2213. }
  2214. if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
  2215. return info->SOName.substr(cmStrLen("@rpath/"));
  2216. }
  2217. return info->SOName;
  2218. }
  2219. return "";
  2220. }
  2221. // Compute the soname that will be built.
  2222. return artifact == cmStateEnums::RuntimeBinaryArtifact
  2223. ? this->GetLibraryNames(config).SharedObject
  2224. : this->GetLibraryNames(config).ImportLibrary;
  2225. }
  2226. namespace {
  2227. bool shouldAddFullLevel(cmGeneratorTarget::BundleDirectoryLevel level)
  2228. {
  2229. return level == cmGeneratorTarget::FullLevel;
  2230. }
  2231. bool shouldAddContentLevel(cmGeneratorTarget::BundleDirectoryLevel level)
  2232. {
  2233. return level == cmGeneratorTarget::ContentLevel || shouldAddFullLevel(level);
  2234. }
  2235. }
  2236. std::string cmGeneratorTarget::GetAppBundleDirectory(
  2237. const std::string& config, BundleDirectoryLevel level) const
  2238. {
  2239. std::string fpath = cmStrCat(
  2240. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  2241. cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
  2242. fpath += (ext ? *ext : "app");
  2243. if (shouldAddContentLevel(level) &&
  2244. !this->Makefile->PlatformIsAppleEmbedded()) {
  2245. fpath += "/Contents";
  2246. if (shouldAddFullLevel(level)) {
  2247. fpath += "/MacOS";
  2248. }
  2249. }
  2250. return fpath;
  2251. }
  2252. bool cmGeneratorTarget::IsBundleOnApple() const
  2253. {
  2254. return this->IsFrameworkOnApple() || this->IsAppBundleOnApple() ||
  2255. this->IsCFBundleOnApple();
  2256. }
  2257. bool cmGeneratorTarget::IsWin32Executable(const std::string& config) const
  2258. {
  2259. return cmIsOn(cmGeneratorExpression::Evaluate(
  2260. this->GetSafeProperty("WIN32_EXECUTABLE"), this->LocalGenerator, config));
  2261. }
  2262. std::string cmGeneratorTarget::GetCFBundleDirectory(
  2263. const std::string& config, BundleDirectoryLevel level) const
  2264. {
  2265. std::string fpath = cmStrCat(
  2266. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  2267. std::string ext;
  2268. if (cmValue p = this->GetProperty("BUNDLE_EXTENSION")) {
  2269. ext = *p;
  2270. } else {
  2271. if (this->IsXCTestOnApple()) {
  2272. ext = "xctest";
  2273. } else {
  2274. ext = "bundle";
  2275. }
  2276. }
  2277. fpath += ext;
  2278. if (shouldAddContentLevel(level) &&
  2279. !this->Makefile->PlatformIsAppleEmbedded()) {
  2280. fpath += "/Contents";
  2281. if (shouldAddFullLevel(level)) {
  2282. fpath += "/MacOS";
  2283. }
  2284. }
  2285. return fpath;
  2286. }
  2287. std::string cmGeneratorTarget::GetFrameworkDirectory(
  2288. const std::string& config, BundleDirectoryLevel level) const
  2289. {
  2290. std::string fpath = cmStrCat(
  2291. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  2292. cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
  2293. fpath += (ext ? *ext : "framework");
  2294. if (shouldAddFullLevel(level) &&
  2295. !this->Makefile->PlatformIsAppleEmbedded()) {
  2296. fpath += "/Versions/";
  2297. fpath += this->GetFrameworkVersion();
  2298. }
  2299. return fpath;
  2300. }
  2301. std::string cmGeneratorTarget::GetFullName(
  2302. const std::string& config, cmStateEnums::ArtifactType artifact) const
  2303. {
  2304. if (this->IsImported()) {
  2305. return this->GetFullNameImported(config, artifact);
  2306. }
  2307. return this->GetFullNameInternal(config, artifact);
  2308. }
  2309. std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
  2310. const std::string& config) const
  2311. {
  2312. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  2313. // If building directly for installation then the build tree install_name
  2314. // is the same as the install tree.
  2315. if (this->MacOSXUseInstallNameDir()) {
  2316. std::string installPrefix =
  2317. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
  2318. return this->GetInstallNameDirForInstallTree(config, installPrefix);
  2319. }
  2320. // Use the build tree directory for the target.
  2321. if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_BUILD)) {
  2322. std::string dir;
  2323. if (this->MacOSXRpathInstallNameDirDefault()) {
  2324. dir = "@rpath";
  2325. } else {
  2326. dir = this->GetDirectory(config);
  2327. }
  2328. dir += "/";
  2329. return dir;
  2330. }
  2331. }
  2332. return "";
  2333. }
  2334. std::string cmGeneratorTarget::GetInstallNameDirForInstallTree(
  2335. const std::string& config, const std::string& installPrefix) const
  2336. {
  2337. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  2338. std::string dir;
  2339. cmValue install_name_dir = this->GetProperty("INSTALL_NAME_DIR");
  2340. if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_INSTALL)) {
  2341. if (cmNonempty(install_name_dir)) {
  2342. dir = *install_name_dir;
  2343. cmGeneratorExpression::ReplaceInstallPrefix(dir, installPrefix);
  2344. dir =
  2345. cmGeneratorExpression::Evaluate(dir, this->LocalGenerator, config);
  2346. if (!dir.empty()) {
  2347. dir = cmStrCat(dir, '/');
  2348. }
  2349. }
  2350. }
  2351. if (!install_name_dir) {
  2352. if (this->MacOSXRpathInstallNameDirDefault()) {
  2353. dir = "@rpath/";
  2354. }
  2355. }
  2356. return dir;
  2357. }
  2358. return "";
  2359. }
  2360. cmListFileBacktrace cmGeneratorTarget::GetBacktrace() const
  2361. {
  2362. return this->Target->GetBacktrace();
  2363. }
  2364. const std::set<BT<std::pair<std::string, bool>>>&
  2365. cmGeneratorTarget::GetUtilities() const
  2366. {
  2367. return this->Target->GetUtilities();
  2368. }
  2369. bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const
  2370. {
  2371. return this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2372. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2373. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2374. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2375. this->GetType() == cmStateEnums::EXECUTABLE;
  2376. }
  2377. const std::string* cmGeneratorTarget::GetExportMacro() const
  2378. {
  2379. // Define the symbol for targets that export symbols.
  2380. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2381. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2382. this->IsExecutableWithExports()) {
  2383. if (cmValue custom_export_name = this->GetProperty("DEFINE_SYMBOL")) {
  2384. this->ExportMacro = *custom_export_name;
  2385. } else {
  2386. std::string in = cmStrCat(this->GetName(), "_EXPORTS");
  2387. this->ExportMacro = cmSystemTools::MakeCidentifier(in);
  2388. }
  2389. return &this->ExportMacro;
  2390. }
  2391. return nullptr;
  2392. }
  2393. class cmTargetCollectLinkLanguages
  2394. {
  2395. public:
  2396. cmTargetCollectLinkLanguages(cmGeneratorTarget const* target,
  2397. std::string config,
  2398. std::unordered_set<std::string>& languages,
  2399. cmGeneratorTarget const* head, bool secondPass)
  2400. : Config(std::move(config))
  2401. , Languages(languages)
  2402. , HeadTarget(head)
  2403. , SecondPass(secondPass)
  2404. {
  2405. this->Visited.insert(target);
  2406. }
  2407. void Visit(cmLinkItem const& item)
  2408. {
  2409. if (!item.Target) {
  2410. return;
  2411. }
  2412. if (!this->Visited.insert(item.Target).second) {
  2413. return;
  2414. }
  2415. cmLinkInterface const* iface = item.Target->GetLinkInterface(
  2416. this->Config, this->HeadTarget, this->SecondPass);
  2417. if (!iface) {
  2418. return;
  2419. }
  2420. if (iface->HadLinkLanguageSensitiveCondition) {
  2421. this->HadLinkLanguageSensitiveCondition = true;
  2422. }
  2423. for (std::string const& language : iface->Languages) {
  2424. this->Languages.insert(language);
  2425. }
  2426. for (cmLinkItem const& lib : iface->Libraries) {
  2427. this->Visit(lib);
  2428. }
  2429. }
  2430. bool GetHadLinkLanguageSensitiveCondition() const
  2431. {
  2432. return this->HadLinkLanguageSensitiveCondition;
  2433. }
  2434. private:
  2435. std::string Config;
  2436. std::unordered_set<std::string>& Languages;
  2437. cmGeneratorTarget const* HeadTarget;
  2438. std::set<cmGeneratorTarget const*> Visited;
  2439. bool SecondPass;
  2440. bool HadLinkLanguageSensitiveCondition = false;
  2441. };
  2442. cmGeneratorTarget::LinkClosure const* cmGeneratorTarget::GetLinkClosure(
  2443. const std::string& config) const
  2444. {
  2445. // There is no link implementation for targets that cannot compile sources.
  2446. if (!this->CanCompileSources()) {
  2447. static LinkClosure const empty = { {}, {} };
  2448. return &empty;
  2449. }
  2450. std::string key(cmSystemTools::UpperCase(config));
  2451. auto i = this->LinkClosureMap.find(key);
  2452. if (i == this->LinkClosureMap.end()) {
  2453. LinkClosure lc;
  2454. this->ComputeLinkClosure(config, lc);
  2455. LinkClosureMapType::value_type entry(key, lc);
  2456. i = this->LinkClosureMap.insert(entry).first;
  2457. }
  2458. return &i->second;
  2459. }
  2460. class cmTargetSelectLinker
  2461. {
  2462. int Preference = 0;
  2463. cmGeneratorTarget const* Target;
  2464. cmGlobalGenerator* GG;
  2465. std::set<std::string> Preferred;
  2466. public:
  2467. cmTargetSelectLinker(cmGeneratorTarget const* target)
  2468. : Target(target)
  2469. {
  2470. this->GG = this->Target->GetLocalGenerator()->GetGlobalGenerator();
  2471. }
  2472. void Consider(const std::string& lang)
  2473. {
  2474. int preference = this->GG->GetLinkerPreference(lang);
  2475. if (preference > this->Preference) {
  2476. this->Preference = preference;
  2477. this->Preferred.clear();
  2478. }
  2479. if (preference == this->Preference) {
  2480. this->Preferred.insert(lang);
  2481. }
  2482. }
  2483. std::string Choose()
  2484. {
  2485. if (this->Preferred.empty()) {
  2486. return "";
  2487. }
  2488. if (this->Preferred.size() > 1) {
  2489. std::ostringstream e;
  2490. e << "Target " << this->Target->GetName()
  2491. << " contains multiple languages with the highest linker preference"
  2492. << " (" << this->Preference << "):\n";
  2493. for (std::string const& li : this->Preferred) {
  2494. e << " " << li << "\n";
  2495. }
  2496. e << "Set the LINKER_LANGUAGE property for this target.";
  2497. cmake* cm = this->Target->GetLocalGenerator()->GetCMakeInstance();
  2498. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  2499. this->Target->GetBacktrace());
  2500. }
  2501. return *this->Preferred.begin();
  2502. }
  2503. };
  2504. bool cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
  2505. LinkClosure& lc,
  2506. bool secondPass) const
  2507. {
  2508. // Get languages built in this target.
  2509. std::unordered_set<std::string> languages;
  2510. cmLinkImplementation const* impl =
  2511. this->GetLinkImplementation(config, LinkInterfaceFor::Link, secondPass);
  2512. assert(impl);
  2513. languages.insert(impl->Languages.cbegin(), impl->Languages.cend());
  2514. // Add interface languages from linked targets.
  2515. // cmTargetCollectLinkLanguages cll(this, config, languages, this,
  2516. // secondPass);
  2517. cmTargetCollectLinkLanguages cll(this, config, languages, this, secondPass);
  2518. for (cmLinkImplItem const& lib : impl->Libraries) {
  2519. cll.Visit(lib);
  2520. }
  2521. // Store the transitive closure of languages.
  2522. cm::append(lc.Languages, languages);
  2523. // Choose the language whose linker should be used.
  2524. if (secondPass || lc.LinkerLanguage.empty()) {
  2525. // Find the language with the highest preference value.
  2526. cmTargetSelectLinker tsl(this);
  2527. // First select from the languages compiled directly in this target.
  2528. for (std::string const& l : impl->Languages) {
  2529. tsl.Consider(l);
  2530. }
  2531. // Now consider languages that propagate from linked targets.
  2532. for (std::string const& lang : languages) {
  2533. std::string propagates =
  2534. "CMAKE_" + lang + "_LINKER_PREFERENCE_PROPAGATES";
  2535. if (this->Makefile->IsOn(propagates)) {
  2536. tsl.Consider(lang);
  2537. }
  2538. }
  2539. lc.LinkerLanguage = tsl.Choose();
  2540. }
  2541. return impl->HadLinkLanguageSensitiveCondition ||
  2542. cll.GetHadLinkLanguageSensitiveCondition();
  2543. }
  2544. void cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
  2545. LinkClosure& lc) const
  2546. {
  2547. bool secondPass = false;
  2548. {
  2549. LinkClosure linkClosure;
  2550. linkClosure.LinkerLanguage = this->LinkerLanguage;
  2551. bool hasHardCodedLinkerLanguage = this->Target->GetProperty("HAS_CXX") ||
  2552. !this->Target->GetSafeProperty("LINKER_LANGUAGE").empty();
  2553. // Get languages built in this target.
  2554. secondPass = this->ComputeLinkClosure(config, linkClosure, false) &&
  2555. !hasHardCodedLinkerLanguage;
  2556. this->LinkerLanguage = linkClosure.LinkerLanguage;
  2557. if (!secondPass) {
  2558. lc = std::move(linkClosure);
  2559. }
  2560. }
  2561. if (secondPass) {
  2562. LinkClosure linkClosure;
  2563. this->ComputeLinkClosure(config, linkClosure, secondPass);
  2564. lc = std::move(linkClosure);
  2565. // linker language must not be changed between the two passes
  2566. if (this->LinkerLanguage != lc.LinkerLanguage) {
  2567. std::ostringstream e;
  2568. e << "Evaluation of $<LINK_LANGUAGE:...> or $<LINK_LAND_AND_ID:...> "
  2569. "changes\nthe linker language for target \""
  2570. << this->GetName() << "\" (from '" << this->LinkerLanguage << "' to '"
  2571. << lc.LinkerLanguage << "') which is invalid.";
  2572. cmSystemTools::Error(e.str());
  2573. }
  2574. }
  2575. }
  2576. cmGeneratorTarget::NameComponents const&
  2577. cmGeneratorTarget::GetFullNameComponents(
  2578. std::string const& config, cmStateEnums::ArtifactType artifact) const
  2579. {
  2580. return this->GetFullNameInternalComponents(config, artifact);
  2581. }
  2582. std::string cmGeneratorTarget::BuildBundleDirectory(
  2583. const std::string& base, const std::string& config,
  2584. BundleDirectoryLevel level) const
  2585. {
  2586. std::string fpath = base;
  2587. if (this->IsAppBundleOnApple()) {
  2588. fpath += this->GetAppBundleDirectory(config, level);
  2589. }
  2590. if (this->IsFrameworkOnApple()) {
  2591. fpath += this->GetFrameworkDirectory(config, level);
  2592. }
  2593. if (this->IsCFBundleOnApple()) {
  2594. fpath += this->GetCFBundleDirectory(config, level);
  2595. }
  2596. return fpath;
  2597. }
  2598. std::string cmGeneratorTarget::GetMacContentDirectory(
  2599. const std::string& config, cmStateEnums::ArtifactType artifact) const
  2600. {
  2601. // Start with the output directory for the target.
  2602. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  2603. BundleDirectoryLevel level = ContentLevel;
  2604. if (this->IsFrameworkOnApple()) {
  2605. // additional files with a framework go into the version specific
  2606. // directory
  2607. level = FullLevel;
  2608. }
  2609. fpath = this->BuildBundleDirectory(fpath, config, level);
  2610. return fpath;
  2611. }
  2612. std::string cmGeneratorTarget::GetEffectiveFolderName() const
  2613. {
  2614. std::string effectiveFolder;
  2615. if (!this->GlobalGenerator->UseFolderProperty()) {
  2616. return effectiveFolder;
  2617. }
  2618. cmValue targetFolder = this->GetProperty("FOLDER");
  2619. if (targetFolder) {
  2620. effectiveFolder += *targetFolder;
  2621. }
  2622. return effectiveFolder;
  2623. }
  2624. cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
  2625. const std::string& config) const
  2626. {
  2627. // There is no compile information for imported targets.
  2628. if (this->IsImported()) {
  2629. return nullptr;
  2630. }
  2631. if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  2632. std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ",
  2633. this->GetName(), " which has type ",
  2634. cmState::GetTargetTypeName(this->GetType()));
  2635. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  2636. return nullptr;
  2637. }
  2638. // Lookup/compute/cache the compile information for this configuration.
  2639. std::string config_upper;
  2640. if (!config.empty()) {
  2641. config_upper = cmSystemTools::UpperCase(config);
  2642. }
  2643. auto i = this->CompileInfoMap.find(config_upper);
  2644. if (i == this->CompileInfoMap.end()) {
  2645. CompileInfo info;
  2646. this->ComputePDBOutputDir("COMPILE_PDB", config, info.CompilePdbDir);
  2647. CompileInfoMapType::value_type entry(config_upper, info);
  2648. i = this->CompileInfoMap.insert(entry).first;
  2649. }
  2650. return &i->second;
  2651. }
  2652. cmGeneratorTarget::ModuleDefinitionInfo const*
  2653. cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
  2654. {
  2655. // A module definition file only makes sense on certain target types.
  2656. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2657. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2658. !this->IsExecutableWithExports()) {
  2659. return nullptr;
  2660. }
  2661. // Lookup/compute/cache the compile information for this configuration.
  2662. std::string config_upper;
  2663. if (!config.empty()) {
  2664. config_upper = cmSystemTools::UpperCase(config);
  2665. }
  2666. auto i = this->ModuleDefinitionInfoMap.find(config_upper);
  2667. if (i == this->ModuleDefinitionInfoMap.end()) {
  2668. ModuleDefinitionInfo info;
  2669. this->ComputeModuleDefinitionInfo(config, info);
  2670. ModuleDefinitionInfoMapType::value_type entry(config_upper, info);
  2671. i = this->ModuleDefinitionInfoMap.insert(entry).first;
  2672. }
  2673. return &i->second;
  2674. }
  2675. void cmGeneratorTarget::ComputeModuleDefinitionInfo(
  2676. std::string const& config, ModuleDefinitionInfo& info) const
  2677. {
  2678. this->GetModuleDefinitionSources(info.Sources, config);
  2679. info.WindowsExportAllSymbols =
  2680. this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  2681. this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS");
  2682. #if !defined(CMAKE_BOOTSTRAP)
  2683. info.DefFileGenerated =
  2684. info.WindowsExportAllSymbols || info.Sources.size() > 1;
  2685. #else
  2686. // Our __create_def helper is not available during CMake bootstrap.
  2687. info.DefFileGenerated = false;
  2688. #endif
  2689. if (info.DefFileGenerated) {
  2690. info.DefFile =
  2691. this->GetObjectDirectory(config) /* has slash */ + "exports.def";
  2692. } else if (!info.Sources.empty()) {
  2693. info.DefFile = info.Sources.front()->GetFullPath();
  2694. }
  2695. }
  2696. bool cmGeneratorTarget::IsAIX() const
  2697. {
  2698. return this->Target->IsAIX();
  2699. }
  2700. bool cmGeneratorTarget::IsApple() const
  2701. {
  2702. return this->Target->IsApple();
  2703. }
  2704. bool cmGeneratorTarget::IsDLLPlatform() const
  2705. {
  2706. return this->Target->IsDLLPlatform();
  2707. }
  2708. void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
  2709. const std::string& config) const
  2710. {
  2711. const char* prop =
  2712. this->GetLinkInterfaceDependentStringProperty("AUTOUIC_OPTIONS", config);
  2713. if (!prop) {
  2714. return;
  2715. }
  2716. cmGeneratorExpressionDAGChecker dagChecker(this, "AUTOUIC_OPTIONS", nullptr,
  2717. nullptr);
  2718. cmExpandList(cmGeneratorExpression::Evaluate(prop, this->LocalGenerator,
  2719. config, this, &dagChecker),
  2720. result);
  2721. }
  2722. static void processILibs(const std::string& config,
  2723. cmGeneratorTarget const* headTarget,
  2724. cmLinkItem const& item, cmGlobalGenerator* gg,
  2725. std::vector<cmGeneratorTarget const*>& tgts,
  2726. std::set<cmGeneratorTarget const*>& emitted)
  2727. {
  2728. if (item.Target && emitted.insert(item.Target).second) {
  2729. tgts.push_back(item.Target);
  2730. if (cmLinkInterfaceLibraries const* iface =
  2731. item.Target->GetLinkInterfaceLibraries(config, headTarget,
  2732. LinkInterfaceFor::Usage)) {
  2733. for (cmLinkItem const& lib : iface->Libraries) {
  2734. processILibs(config, headTarget, lib, gg, tgts, emitted);
  2735. }
  2736. }
  2737. }
  2738. }
  2739. const std::vector<const cmGeneratorTarget*>&
  2740. cmGeneratorTarget::GetLinkImplementationClosure(
  2741. const std::string& config) const
  2742. {
  2743. // There is no link implementation for targets that cannot compile sources.
  2744. if (!this->CanCompileSources()) {
  2745. static std::vector<const cmGeneratorTarget*> const empty;
  2746. return empty;
  2747. }
  2748. LinkImplClosure& tgts = this->LinkImplClosureMap[config];
  2749. if (!tgts.Done) {
  2750. tgts.Done = true;
  2751. std::set<cmGeneratorTarget const*> emitted;
  2752. cmLinkImplementationLibraries const* impl =
  2753. this->GetLinkImplementationLibraries(config, LinkInterfaceFor::Usage);
  2754. assert(impl);
  2755. for (cmLinkImplItem const& lib : impl->Libraries) {
  2756. processILibs(config, this, lib,
  2757. this->LocalGenerator->GetGlobalGenerator(), tgts, emitted);
  2758. }
  2759. }
  2760. return tgts;
  2761. }
  2762. class cmTargetTraceDependencies
  2763. {
  2764. public:
  2765. cmTargetTraceDependencies(cmGeneratorTarget* target);
  2766. void Trace();
  2767. private:
  2768. cmGeneratorTarget* GeneratorTarget;
  2769. cmMakefile* Makefile;
  2770. cmLocalGenerator* LocalGenerator;
  2771. cmGlobalGenerator const* GlobalGenerator;
  2772. using SourceEntry = cmGeneratorTarget::SourceEntry;
  2773. SourceEntry* CurrentEntry;
  2774. std::queue<cmSourceFile*> SourceQueue;
  2775. std::set<cmSourceFile*> SourcesQueued;
  2776. using NameMapType = std::map<std::string, cmSourcesWithOutput>;
  2777. NameMapType NameMap;
  2778. std::vector<std::string> NewSources;
  2779. void QueueSource(cmSourceFile* sf);
  2780. void FollowName(std::string const& name);
  2781. void FollowNames(std::vector<std::string> const& names);
  2782. bool IsUtility(std::string const& dep);
  2783. void CheckCustomCommand(cmCustomCommand const& cc);
  2784. void CheckCustomCommands(const std::vector<cmCustomCommand>& commands);
  2785. };
  2786. cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target)
  2787. : GeneratorTarget(target)
  2788. {
  2789. // Convenience.
  2790. this->Makefile = target->Target->GetMakefile();
  2791. this->LocalGenerator = target->GetLocalGenerator();
  2792. this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
  2793. this->CurrentEntry = nullptr;
  2794. // Queue all the source files already specified for the target.
  2795. std::set<cmSourceFile*> emitted;
  2796. std::vector<std::string> const& configs =
  2797. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2798. for (std::string const& c : configs) {
  2799. std::vector<cmSourceFile*> sources;
  2800. this->GeneratorTarget->GetSourceFiles(sources, c);
  2801. for (cmSourceFile* sf : sources) {
  2802. const std::set<cmGeneratorTarget const*> tgts =
  2803. this->GlobalGenerator->GetFilenameTargetDepends(sf);
  2804. if (cm::contains(tgts, this->GeneratorTarget)) {
  2805. std::ostringstream e;
  2806. e << "Evaluation output file\n \"" << sf->ResolveFullPath()
  2807. << "\"\ndepends on the sources of a target it is used in. This "
  2808. "is a dependency loop and is not allowed.";
  2809. this->GeneratorTarget->LocalGenerator->IssueMessage(
  2810. MessageType::FATAL_ERROR, e.str());
  2811. return;
  2812. }
  2813. if (emitted.insert(sf).second && this->SourcesQueued.insert(sf).second) {
  2814. this->SourceQueue.push(sf);
  2815. }
  2816. }
  2817. }
  2818. // Queue pre-build, pre-link, and post-build rule dependencies.
  2819. this->CheckCustomCommands(this->GeneratorTarget->GetPreBuildCommands());
  2820. this->CheckCustomCommands(this->GeneratorTarget->GetPreLinkCommands());
  2821. this->CheckCustomCommands(this->GeneratorTarget->GetPostBuildCommands());
  2822. }
  2823. void cmTargetTraceDependencies::Trace()
  2824. {
  2825. // Process one dependency at a time until the queue is empty.
  2826. while (!this->SourceQueue.empty()) {
  2827. // Get the next source from the queue.
  2828. cmSourceFile* sf = this->SourceQueue.front();
  2829. this->SourceQueue.pop();
  2830. this->CurrentEntry = &this->GeneratorTarget->SourceDepends[sf];
  2831. // Queue dependencies added explicitly by the user.
  2832. if (cmValue additionalDeps = sf->GetProperty("OBJECT_DEPENDS")) {
  2833. cmList objDeps{ *additionalDeps };
  2834. for (auto& objDep : objDeps) {
  2835. if (cmSystemTools::FileIsFullPath(objDep)) {
  2836. objDep = cmSystemTools::CollapseFullPath(objDep);
  2837. }
  2838. }
  2839. this->FollowNames(objDeps);
  2840. }
  2841. // Queue the source needed to generate this file, if any.
  2842. this->FollowName(sf->ResolveFullPath());
  2843. // Queue dependencies added programmatically by commands.
  2844. this->FollowNames(sf->GetDepends());
  2845. // Queue custom command dependencies.
  2846. if (cmCustomCommand const* cc = sf->GetCustomCommand()) {
  2847. this->CheckCustomCommand(*cc);
  2848. }
  2849. }
  2850. this->CurrentEntry = nullptr;
  2851. this->GeneratorTarget->AddTracedSources(this->NewSources);
  2852. }
  2853. void cmTargetTraceDependencies::QueueSource(cmSourceFile* sf)
  2854. {
  2855. if (this->SourcesQueued.insert(sf).second) {
  2856. this->SourceQueue.push(sf);
  2857. // Make sure this file is in the target at the end.
  2858. this->NewSources.push_back(sf->ResolveFullPath());
  2859. }
  2860. }
  2861. void cmTargetTraceDependencies::FollowName(std::string const& name)
  2862. {
  2863. // Use lower bound with key comparison to not repeat the search for the
  2864. // insert position if the name could not be found (which is the common case).
  2865. auto i = this->NameMap.lower_bound(name);
  2866. if (i == this->NameMap.end() || i->first != name) {
  2867. // Check if we know how to generate this file.
  2868. cmSourcesWithOutput sources =
  2869. this->LocalGenerator->GetSourcesWithOutput(name);
  2870. // If we failed to find a target or source and we have a relative path, it
  2871. // might be a valid source if made relative to the current binary
  2872. // directory.
  2873. if (!sources.Target && !sources.Source &&
  2874. !cmSystemTools::FileIsFullPath(name)) {
  2875. auto fullname =
  2876. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/', name);
  2877. fullname = cmSystemTools::CollapseFullPath(
  2878. fullname, this->Makefile->GetHomeOutputDirectory());
  2879. sources = this->LocalGenerator->GetSourcesWithOutput(fullname);
  2880. }
  2881. i = this->NameMap.emplace_hint(i, name, sources);
  2882. }
  2883. if (cmTarget* t = i->second.Target) {
  2884. // The name is a byproduct of a utility target or a PRE_BUILD, PRE_LINK, or
  2885. // POST_BUILD command.
  2886. this->GeneratorTarget->Target->AddUtility(t->GetName(), false);
  2887. }
  2888. if (cmSourceFile* sf = i->second.Source) {
  2889. // For now only follow the dependency if the source file is not a
  2890. // byproduct. Semantics of byproducts in a non-Ninja context will have to
  2891. // be defined first.
  2892. if (!i->second.SourceIsByproduct) {
  2893. // Record the dependency we just followed.
  2894. if (this->CurrentEntry) {
  2895. this->CurrentEntry->Depends.push_back(sf);
  2896. }
  2897. this->QueueSource(sf);
  2898. }
  2899. }
  2900. }
  2901. void cmTargetTraceDependencies::FollowNames(
  2902. std::vector<std::string> const& names)
  2903. {
  2904. for (std::string const& name : names) {
  2905. this->FollowName(name);
  2906. }
  2907. }
  2908. bool cmTargetTraceDependencies::IsUtility(std::string const& dep)
  2909. {
  2910. // Dependencies on targets (utilities) are supposed to be named by
  2911. // just the target name. However for compatibility we support
  2912. // naming the output file generated by the target (assuming there is
  2913. // no output-name property which old code would not have set). In
  2914. // that case the target name will be the file basename of the
  2915. // dependency.
  2916. std::string util = cmSystemTools::GetFilenameName(dep);
  2917. if (cmSystemTools::GetFilenameLastExtension(util) == ".exe") {
  2918. util = cmSystemTools::GetFilenameWithoutLastExtension(util);
  2919. }
  2920. // Check for a target with this name.
  2921. if (cmGeneratorTarget* t =
  2922. this->GeneratorTarget->GetLocalGenerator()->FindGeneratorTargetToUse(
  2923. util)) {
  2924. // If we find the target and the dep was given as a full path,
  2925. // then make sure it was not a full path to something else, and
  2926. // the fact that the name matched a target was just a coincidence.
  2927. if (cmSystemTools::FileIsFullPath(dep)) {
  2928. if (t->GetType() >= cmStateEnums::EXECUTABLE &&
  2929. t->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  2930. // This is really only for compatibility so we do not need to
  2931. // worry about configuration names and output names.
  2932. std::string tLocation = t->GetLocationForBuild();
  2933. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  2934. std::string depLocation = cmSystemTools::GetFilenamePath(dep);
  2935. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  2936. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  2937. if (depLocation == tLocation) {
  2938. this->GeneratorTarget->Target->AddUtility(util, false);
  2939. return true;
  2940. }
  2941. }
  2942. } else {
  2943. // The original name of the dependency was not a full path. It
  2944. // must name a target, so add the target-level dependency.
  2945. this->GeneratorTarget->Target->AddUtility(util, true);
  2946. return true;
  2947. }
  2948. }
  2949. // The dependency does not name a target built in this project.
  2950. return false;
  2951. }
  2952. void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc)
  2953. {
  2954. // Collect dependencies referenced by all configurations.
  2955. std::set<std::string> depends;
  2956. for (std::string const& config :
  2957. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
  2958. for (cmCustomCommandGenerator const& ccg :
  2959. this->LocalGenerator->MakeCustomCommandGenerators(cc, config)) {
  2960. // Collect target-level dependencies referenced in command lines.
  2961. for (auto const& util : ccg.GetUtilities()) {
  2962. this->GeneratorTarget->Target->AddUtility(util);
  2963. }
  2964. // Collect file-level dependencies referenced in DEPENDS.
  2965. depends.insert(ccg.GetDepends().begin(), ccg.GetDepends().end());
  2966. }
  2967. }
  2968. // Queue file-level dependencies.
  2969. for (std::string const& dep : depends) {
  2970. if (!this->IsUtility(dep)) {
  2971. // The dependency does not name a target and may be a file we
  2972. // know how to generate. Queue it.
  2973. this->FollowName(dep);
  2974. }
  2975. }
  2976. }
  2977. void cmTargetTraceDependencies::CheckCustomCommands(
  2978. const std::vector<cmCustomCommand>& commands)
  2979. {
  2980. for (cmCustomCommand const& command : commands) {
  2981. this->CheckCustomCommand(command);
  2982. }
  2983. }
  2984. void cmGeneratorTarget::TraceDependencies()
  2985. {
  2986. // CMake-generated targets have no dependencies to trace. Normally tracing
  2987. // would find nothing anyway, but when building CMake itself the "install"
  2988. // target command ends up referencing the "cmake" target but we do not
  2989. // really want the dependency because "install" depend on "all" anyway.
  2990. if (this->GetType() == cmStateEnums::GLOBAL_TARGET) {
  2991. return;
  2992. }
  2993. // Use a helper object to trace the dependencies.
  2994. cmTargetTraceDependencies tracer(this);
  2995. tracer.Trace();
  2996. }
  2997. std::string cmGeneratorTarget::GetCompilePDBDirectory(
  2998. const std::string& config) const
  2999. {
  3000. if (CompileInfo const* info = this->GetCompileInfo(config)) {
  3001. return info->CompilePdbDir;
  3002. }
  3003. return "";
  3004. }
  3005. std::vector<std::string> cmGeneratorTarget::GetAppleArchs(
  3006. std::string const& config, cm::optional<std::string> lang) const
  3007. {
  3008. cmList archList;
  3009. if (!this->IsApple()) {
  3010. return std::move(archList.data());
  3011. }
  3012. cmValue archs = nullptr;
  3013. if (!config.empty()) {
  3014. std::string defVarName =
  3015. cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config));
  3016. archs = this->GetProperty(defVarName);
  3017. }
  3018. if (!archs) {
  3019. archs = this->GetProperty("OSX_ARCHITECTURES");
  3020. }
  3021. if (archs) {
  3022. archList.assign(*archs);
  3023. }
  3024. if (archList.empty() &&
  3025. // Fall back to a default architecture if no compiler target is set.
  3026. (!lang ||
  3027. this->Makefile
  3028. ->GetDefinition(cmStrCat("CMAKE_", *lang, "_COMPILER_TARGET"))
  3029. .IsEmpty())) {
  3030. archList.assign(
  3031. this->Makefile->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  3032. }
  3033. return std::move(archList.data());
  3034. }
  3035. void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
  3036. cmSourceFile const& sf) const
  3037. {
  3038. cmValue lang = sf.GetProperty("LANGUAGE");
  3039. if (!lang) {
  3040. return;
  3041. }
  3042. switch (this->GetPolicyStatusCMP0119()) {
  3043. case cmPolicies::WARN:
  3044. CM_FALLTHROUGH;
  3045. case cmPolicies::OLD:
  3046. // The OLD behavior is to not add explicit language flags.
  3047. return;
  3048. case cmPolicies::REQUIRED_ALWAYS:
  3049. case cmPolicies::REQUIRED_IF_USED:
  3050. case cmPolicies::NEW:
  3051. // The NEW behavior is to add explicit language flags.
  3052. break;
  3053. }
  3054. this->LocalGenerator->AppendFeatureOptions(flags, *lang,
  3055. "EXPLICIT_LANGUAGE");
  3056. }
  3057. void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
  3058. std::string const& config,
  3059. std::string& flags) const
  3060. {
  3061. std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
  3062. if (arch.empty()) {
  3063. switch (this->GetPolicyStatusCMP0104()) {
  3064. case cmPolicies::WARN:
  3065. if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
  3066. this->Makefile->IssueMessage(
  3067. MessageType::AUTHOR_WARNING,
  3068. cmPolicies::GetPolicyWarning(cmPolicies::CMP0104) +
  3069. "\nCUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  3070. "\".");
  3071. }
  3072. CM_FALLTHROUGH;
  3073. case cmPolicies::OLD:
  3074. break;
  3075. default:
  3076. this->Makefile->IssueMessage(
  3077. MessageType::FATAL_ERROR,
  3078. "CUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  3079. "\".");
  3080. }
  3081. }
  3082. // If CUDA_ARCHITECTURES is false we don't add any architectures.
  3083. if (cmIsOff(arch)) {
  3084. return;
  3085. }
  3086. return this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
  3087. std::move(arch), flags);
  3088. }
  3089. void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
  3090. std::string const& config,
  3091. std::string const& lang,
  3092. std::string arch,
  3093. std::string& flags) const
  3094. {
  3095. std::string const& compiler = this->Makefile->GetSafeDefinition(
  3096. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  3097. const bool ipoEnabled = this->IsIPOEnabled(lang, config);
  3098. // Check for special modes: `all`, `all-major`.
  3099. if (arch == "all" || arch == "all-major") {
  3100. if (compiler == "NVIDIA" &&
  3101. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  3102. this->Makefile->GetDefinition(cmStrCat(
  3103. "CMAKE_", lang, "_COMPILER_VERSION")),
  3104. "11.5")) {
  3105. flags = cmStrCat(flags, " -arch=", arch);
  3106. return;
  3107. }
  3108. if (arch == "all") {
  3109. arch = *this->Makefile->GetDefinition(
  3110. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
  3111. } else if (arch == "all-major") {
  3112. arch = *this->Makefile->GetDefinition(
  3113. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
  3114. }
  3115. } else if (arch == "native") {
  3116. cmValue native = this->Makefile->GetDefinition(
  3117. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
  3118. if (native.IsEmpty()) {
  3119. this->Makefile->IssueMessage(
  3120. MessageType::FATAL_ERROR,
  3121. cmStrCat(lang,
  3122. "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
  3123. "detected."));
  3124. }
  3125. if (compiler == "NVIDIA" &&
  3126. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  3127. this->Makefile->GetDefinition(cmStrCat(
  3128. "CMAKE_", lang, "_COMPILER_VERSION")),
  3129. "11.6")) {
  3130. flags = cmStrCat(flags, " -arch=", arch);
  3131. return;
  3132. }
  3133. arch = *native;
  3134. }
  3135. struct CudaArchitecture
  3136. {
  3137. std::string name;
  3138. bool real{ true };
  3139. bool virtual_{ true };
  3140. };
  3141. std::vector<CudaArchitecture> architectures;
  3142. {
  3143. cmList options(arch);
  3144. for (auto& option : options) {
  3145. CudaArchitecture architecture;
  3146. // Architecture name is up to the first specifier.
  3147. std::size_t pos = option.find_first_of('-');
  3148. architecture.name = option.substr(0, pos);
  3149. if (pos != std::string::npos) {
  3150. cm::string_view specifier{ option.c_str() + pos + 1,
  3151. option.length() - pos - 1 };
  3152. if (specifier == "real") {
  3153. architecture.real = true;
  3154. architecture.virtual_ = false;
  3155. } else if (specifier == "virtual") {
  3156. architecture.real = false;
  3157. architecture.virtual_ = true;
  3158. } else {
  3159. this->Makefile->IssueMessage(
  3160. MessageType::FATAL_ERROR,
  3161. "Unknown CUDA architecture specifier \"" + std::string(specifier) +
  3162. "\".");
  3163. }
  3164. }
  3165. architectures.emplace_back(architecture);
  3166. }
  3167. }
  3168. if (compiler == "NVIDIA") {
  3169. if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
  3170. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  3171. cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
  3172. flags += *cudaIPOFlags;
  3173. }
  3174. }
  3175. for (CudaArchitecture& architecture : architectures) {
  3176. flags +=
  3177. " \"--generate-code=arch=compute_" + architecture.name + ",code=[";
  3178. if (architecture.virtual_) {
  3179. flags += "compute_" + architecture.name;
  3180. if (ipoEnabled || architecture.real) {
  3181. flags += ",";
  3182. }
  3183. }
  3184. if (ipoEnabled) {
  3185. if (compileOrLink == cmBuildStep::Compile) {
  3186. flags += "lto_" + architecture.name;
  3187. } else if (compileOrLink == cmBuildStep::Link) {
  3188. flags += "sm_" + architecture.name;
  3189. }
  3190. } else if (architecture.real) {
  3191. flags += "sm_" + architecture.name;
  3192. }
  3193. flags += "]\"";
  3194. }
  3195. } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
  3196. for (CudaArchitecture& architecture : architectures) {
  3197. flags += " --cuda-gpu-arch=sm_" + architecture.name;
  3198. if (!architecture.real) {
  3199. this->Makefile->IssueMessage(
  3200. MessageType::WARNING,
  3201. "Clang doesn't support disabling CUDA real code generation.");
  3202. }
  3203. if (!architecture.virtual_) {
  3204. flags += " --no-cuda-include-ptx=sm_" + architecture.name;
  3205. }
  3206. }
  3207. }
  3208. }
  3209. void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
  3210. {
  3211. const std::string& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  3212. // If ISPC_TARGET is false we don't add any architectures.
  3213. if (cmIsOff(arch)) {
  3214. return;
  3215. }
  3216. std::string const& compiler =
  3217. this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
  3218. if (compiler == "Intel") {
  3219. cmList targets(arch);
  3220. if (!targets.empty()) {
  3221. flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
  3222. }
  3223. }
  3224. }
  3225. void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
  3226. std::string const& config,
  3227. std::string& flags) const
  3228. {
  3229. std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
  3230. if (arch.empty()) {
  3231. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  3232. "HIP_ARCHITECTURES is empty for target \"" +
  3233. this->GetName() + "\".");
  3234. }
  3235. // If HIP_ARCHITECTURES is false we don't add any architectures.
  3236. if (cmIsOff(arch)) {
  3237. return;
  3238. }
  3239. if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
  3240. return this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
  3241. std::move(arch), flags);
  3242. }
  3243. cmList options(arch);
  3244. for (std::string& option : options) {
  3245. flags += " --offload-arch=" + option;
  3246. }
  3247. }
  3248. void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
  3249. {
  3250. std::string const& compiler =
  3251. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  3252. if (compiler == "Clang") {
  3253. // Pass CUDA toolkit explicitly to Clang.
  3254. // Clang's searching for the system CUDA toolkit isn't very good and it's
  3255. // expected the user will explicitly pass the toolkit path.
  3256. // This also avoids Clang having to search for the toolkit on every
  3257. // invocation.
  3258. std::string toolkitRoot =
  3259. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
  3260. if (!toolkitRoot.empty()) {
  3261. flags += " --cuda-path=" +
  3262. this->LocalGenerator->ConvertToOutputFormat(toolkitRoot,
  3263. cmOutputConverter::SHELL);
  3264. }
  3265. }
  3266. }
  3267. //----------------------------------------------------------------------------
  3268. std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
  3269. std::string const& var, std::string const& lang,
  3270. std::string const& config) const
  3271. {
  3272. if (this->IsIPOEnabled(lang, config)) {
  3273. std::string varIPO = var + "_IPO";
  3274. if (this->Makefile->IsDefinitionSet(varIPO)) {
  3275. return varIPO;
  3276. }
  3277. }
  3278. return var;
  3279. }
  3280. //----------------------------------------------------------------------------
  3281. std::string cmGeneratorTarget::GetCreateRuleVariable(
  3282. std::string const& lang, std::string const& config) const
  3283. {
  3284. switch (this->GetType()) {
  3285. case cmStateEnums::STATIC_LIBRARY: {
  3286. std::string var = "CMAKE_" + lang + "_CREATE_STATIC_LIBRARY";
  3287. return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
  3288. }
  3289. case cmStateEnums::SHARED_LIBRARY:
  3290. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY";
  3291. case cmStateEnums::MODULE_LIBRARY:
  3292. return "CMAKE_" + lang + "_CREATE_SHARED_MODULE";
  3293. case cmStateEnums::EXECUTABLE:
  3294. if (this->IsExecutableWithExports()) {
  3295. std::string linkExeWithExports =
  3296. "CMAKE_" + lang + "_LINK_EXECUTABLE_WITH_EXPORTS";
  3297. if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
  3298. return linkExeWithExports;
  3299. }
  3300. }
  3301. return "CMAKE_" + lang + "_LINK_EXECUTABLE";
  3302. default:
  3303. break;
  3304. }
  3305. return "";
  3306. }
  3307. //----------------------------------------------------------------------------
  3308. std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
  3309. const std::string& lang) const
  3310. {
  3311. cmValue val =
  3312. this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
  3313. if (!cmNonempty(val)) {
  3314. return {};
  3315. }
  3316. std::string path = *val;
  3317. if (!cmSystemTools::FileIsFullPath(path)) {
  3318. path =
  3319. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
  3320. }
  3321. return cmSystemTools::CollapseFullPath(path);
  3322. }
  3323. namespace {
  3324. void processIncludeDirectories(cmGeneratorTarget const* tgt,
  3325. EvaluatedTargetPropertyEntries& entries,
  3326. std::vector<BT<std::string>>& includes,
  3327. std::unordered_set<std::string>& uniqueIncludes,
  3328. bool debugIncludes)
  3329. {
  3330. for (EvaluatedTargetPropertyEntry& entry : entries.Entries) {
  3331. cmLinkImplItem const& item = entry.LinkImplItem;
  3332. std::string const& targetName = item.AsStr();
  3333. bool const fromImported = item.Target && item.Target->IsImported();
  3334. bool const checkCMP0027 = item.CheckCMP0027;
  3335. std::string usedIncludes;
  3336. for (std::string& entryInclude : entry.Values) {
  3337. if (fromImported && !cmSystemTools::FileExists(entryInclude)) {
  3338. std::ostringstream e;
  3339. MessageType messageType = MessageType::FATAL_ERROR;
  3340. if (checkCMP0027) {
  3341. switch (tgt->GetPolicyStatusCMP0027()) {
  3342. case cmPolicies::WARN:
  3343. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0027) << "\n";
  3344. CM_FALLTHROUGH;
  3345. case cmPolicies::OLD:
  3346. messageType = MessageType::AUTHOR_WARNING;
  3347. break;
  3348. case cmPolicies::REQUIRED_ALWAYS:
  3349. case cmPolicies::REQUIRED_IF_USED:
  3350. case cmPolicies::NEW:
  3351. break;
  3352. }
  3353. }
  3354. /* clang-format off */
  3355. e << "Imported target \"" << targetName << "\" includes "
  3356. "non-existent path\n \"" << entryInclude << "\"\nin its "
  3357. "INTERFACE_INCLUDE_DIRECTORIES. Possible reasons include:\n"
  3358. "* The path was deleted, renamed, or moved to another "
  3359. "location.\n"
  3360. "* An install or uninstall procedure did not complete "
  3361. "successfully.\n"
  3362. "* The installation package was faulty and references files it "
  3363. "does not provide.\n";
  3364. /* clang-format on */
  3365. tgt->GetLocalGenerator()->IssueMessage(messageType, e.str());
  3366. return;
  3367. }
  3368. if (!cmSystemTools::FileIsFullPath(entryInclude)) {
  3369. std::ostringstream e;
  3370. bool noMessage = false;
  3371. MessageType messageType = MessageType::FATAL_ERROR;
  3372. if (!targetName.empty()) {
  3373. /* clang-format off */
  3374. e << "Target \"" << targetName << "\" contains relative "
  3375. "path in its INTERFACE_INCLUDE_DIRECTORIES:\n"
  3376. " \"" << entryInclude << "\"";
  3377. /* clang-format on */
  3378. } else {
  3379. switch (tgt->GetPolicyStatusCMP0021()) {
  3380. case cmPolicies::WARN: {
  3381. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0021) << "\n";
  3382. messageType = MessageType::AUTHOR_WARNING;
  3383. } break;
  3384. case cmPolicies::OLD:
  3385. noMessage = true;
  3386. break;
  3387. case cmPolicies::REQUIRED_IF_USED:
  3388. case cmPolicies::REQUIRED_ALWAYS:
  3389. case cmPolicies::NEW:
  3390. // Issue the fatal message.
  3391. break;
  3392. }
  3393. e << "Found relative path while evaluating include directories of "
  3394. "\""
  3395. << tgt->GetName() << "\":\n \"" << entryInclude << "\"\n";
  3396. }
  3397. if (!noMessage) {
  3398. tgt->GetLocalGenerator()->IssueMessage(messageType, e.str());
  3399. if (messageType == MessageType::FATAL_ERROR) {
  3400. return;
  3401. }
  3402. }
  3403. }
  3404. if (!cmIsOff(entryInclude)) {
  3405. cmSystemTools::ConvertToUnixSlashes(entryInclude);
  3406. }
  3407. if (uniqueIncludes.insert(entryInclude).second) {
  3408. includes.emplace_back(entryInclude, entry.Backtrace);
  3409. if (debugIncludes) {
  3410. usedIncludes += " * " + entryInclude + "\n";
  3411. }
  3412. }
  3413. }
  3414. if (!usedIncludes.empty()) {
  3415. tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  3416. MessageType::LOG,
  3417. std::string("Used includes for target ") + tgt->GetName() + ":\n" +
  3418. usedIncludes,
  3419. entry.Backtrace);
  3420. }
  3421. }
  3422. }
  3423. }
  3424. std::vector<BT<std::string>> cmGeneratorTarget::GetIncludeDirectories(
  3425. const std::string& config, const std::string& lang) const
  3426. {
  3427. ConfigAndLanguage cacheKey(config, lang);
  3428. {
  3429. auto it = this->IncludeDirectoriesCache.find(cacheKey);
  3430. if (it != this->IncludeDirectoriesCache.end()) {
  3431. return it->second;
  3432. }
  3433. }
  3434. std::vector<BT<std::string>> includes;
  3435. std::unordered_set<std::string> uniqueIncludes;
  3436. cmGeneratorExpressionDAGChecker dagChecker(this, "INCLUDE_DIRECTORIES",
  3437. nullptr, nullptr);
  3438. cmList debugProperties{ this->Makefile->GetDefinition(
  3439. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3440. bool debugIncludes = !this->DebugIncludesDone &&
  3441. cm::contains(debugProperties, "INCLUDE_DIRECTORIES");
  3442. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3443. this->DebugIncludesDone = true;
  3444. }
  3445. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  3446. this, config, lang, &dagChecker, this->IncludeDirectoriesEntries);
  3447. if (lang == "Swift") {
  3448. AddLangSpecificImplicitIncludeDirectories(
  3449. this, lang, config, "Swift_MODULE_DIRECTORY",
  3450. IncludeDirectoryFallBack::BINARY, entries);
  3451. }
  3452. if (this->CanCompileSources() && (lang != "Swift" && lang != "Fortran")) {
  3453. const std::string propertyName = "ISPC_HEADER_DIRECTORY";
  3454. // If this target has ISPC sources make sure to add the header
  3455. // directory to other compilation units
  3456. if (cm::contains(this->GetAllConfigCompileLanguages(), "ISPC")) {
  3457. if (cmValue val = this->GetProperty(propertyName)) {
  3458. includes.emplace_back(*val);
  3459. } else {
  3460. includes.emplace_back(this->GetObjectDirectory(config));
  3461. }
  3462. }
  3463. AddLangSpecificImplicitIncludeDirectories(
  3464. this, "ISPC", config, propertyName, IncludeDirectoryFallBack::OBJECT,
  3465. entries);
  3466. }
  3467. AddInterfaceEntries(this, config, "INTERFACE_INCLUDE_DIRECTORIES", lang,
  3468. &dagChecker, entries, IncludeRuntimeInterface::Yes);
  3469. processIncludeDirectories(this, entries, includes, uniqueIncludes,
  3470. debugIncludes);
  3471. if (this->IsApple()) {
  3472. if (cmLinkImplementationLibraries const* impl =
  3473. this->GetLinkImplementationLibraries(config,
  3474. LinkInterfaceFor::Usage)) {
  3475. for (cmLinkImplItem const& lib : impl->Libraries) {
  3476. std::string libDir;
  3477. if (lib.Target == nullptr) {
  3478. libDir = cmSystemTools::CollapseFullPath(
  3479. lib.AsStr(), this->Makefile->GetHomeOutputDirectory());
  3480. } else if (lib.Target->Target->IsFrameworkOnApple() ||
  3481. this->IsImportedFrameworkFolderOnApple(config)) {
  3482. libDir = lib.Target->GetLocation(config);
  3483. } else {
  3484. continue;
  3485. }
  3486. auto fwDescriptor =
  3487. this->GetGlobalGenerator()->SplitFrameworkPath(libDir);
  3488. if (!fwDescriptor) {
  3489. continue;
  3490. }
  3491. auto fwInclude = fwDescriptor->GetFrameworkPath();
  3492. if (uniqueIncludes.insert(fwInclude).second) {
  3493. includes.emplace_back(fwInclude, cmListFileBacktrace());
  3494. }
  3495. }
  3496. }
  3497. }
  3498. this->IncludeDirectoriesCache.emplace(cacheKey, includes);
  3499. return includes;
  3500. }
  3501. enum class OptionsParse
  3502. {
  3503. None,
  3504. Shell
  3505. };
  3506. namespace {
  3507. const auto DL_BEGIN = "<DEVICE_LINK>"_s;
  3508. const auto DL_END = "</DEVICE_LINK>"_s;
  3509. void processOptions(cmGeneratorTarget const* tgt,
  3510. EvaluatedTargetPropertyEntries const& entries,
  3511. std::vector<BT<std::string>>& options,
  3512. std::unordered_set<std::string>& uniqueOptions,
  3513. bool debugOptions, const char* logName, OptionsParse parse,
  3514. bool processDeviceOptions = false)
  3515. {
  3516. bool splitOption = !processDeviceOptions;
  3517. for (EvaluatedTargetPropertyEntry const& entry : entries.Entries) {
  3518. std::string usedOptions;
  3519. for (std::string const& opt : entry.Values) {
  3520. if (processDeviceOptions && (opt == DL_BEGIN || opt == DL_END)) {
  3521. options.emplace_back(opt, entry.Backtrace);
  3522. splitOption = opt == DL_BEGIN;
  3523. continue;
  3524. }
  3525. if (uniqueOptions.insert(opt).second) {
  3526. if (parse == OptionsParse::Shell &&
  3527. cmHasLiteralPrefix(opt, "SHELL:")) {
  3528. if (splitOption) {
  3529. std::vector<std::string> tmp;
  3530. cmSystemTools::ParseUnixCommandLine(opt.c_str() + 6, tmp);
  3531. for (std::string& o : tmp) {
  3532. options.emplace_back(std::move(o), entry.Backtrace);
  3533. }
  3534. } else {
  3535. options.emplace_back(std::string(opt.c_str() + 6),
  3536. entry.Backtrace);
  3537. }
  3538. } else {
  3539. options.emplace_back(opt, entry.Backtrace);
  3540. }
  3541. if (debugOptions) {
  3542. usedOptions += " * " + opt + "\n";
  3543. }
  3544. }
  3545. }
  3546. if (!usedOptions.empty()) {
  3547. tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  3548. MessageType::LOG,
  3549. std::string("Used ") + logName + std::string(" for target ") +
  3550. tgt->GetName() + ":\n" + usedOptions,
  3551. entry.Backtrace);
  3552. }
  3553. }
  3554. }
  3555. std::vector<BT<std::string>> wrapOptions(
  3556. std::vector<std::string>& options, const cmListFileBacktrace& bt,
  3557. const std::vector<std::string>& wrapperFlag, const std::string& wrapperSep,
  3558. bool concatFlagAndArgs)
  3559. {
  3560. std::vector<BT<std::string>> result;
  3561. if (options.empty()) {
  3562. return result;
  3563. }
  3564. if (wrapperFlag.empty()) {
  3565. // nothing specified, insert elements as is
  3566. result.reserve(options.size());
  3567. for (std::string& o : options) {
  3568. result.emplace_back(std::move(o), bt);
  3569. }
  3570. return result;
  3571. }
  3572. for (std::vector<std::string>::size_type index = 0; index < options.size();
  3573. index++) {
  3574. if (cmHasLiteralPrefix(options[index], "LINKER:")) {
  3575. // LINKER wrapper specified, insert elements as is
  3576. result.emplace_back(std::move(options[index]), bt);
  3577. continue;
  3578. }
  3579. if (cmHasLiteralPrefix(options[index], "-Wl,")) {
  3580. // replace option by LINKER wrapper
  3581. result.emplace_back(options[index].replace(0, 4, "LINKER:"), bt);
  3582. continue;
  3583. }
  3584. if (cmHasLiteralPrefix(options[index], "-Xlinker=")) {
  3585. // replace option by LINKER wrapper
  3586. result.emplace_back(options[index].replace(0, 9, "LINKER:"), bt);
  3587. continue;
  3588. }
  3589. if (options[index] == "-Xlinker") {
  3590. // replace option by LINKER wrapper
  3591. if (index + 1 < options.size()) {
  3592. result.emplace_back("LINKER:" + options[++index], bt);
  3593. } else {
  3594. result.emplace_back(std::move(options[index]), bt);
  3595. }
  3596. continue;
  3597. }
  3598. // collect all options which must be transformed
  3599. std::vector<std::string> opts;
  3600. while (index < options.size()) {
  3601. if (!cmHasLiteralPrefix(options[index], "LINKER:") &&
  3602. !cmHasLiteralPrefix(options[index], "-Wl,") &&
  3603. !cmHasLiteralPrefix(options[index], "-Xlinker")) {
  3604. opts.emplace_back(std::move(options[index++]));
  3605. } else {
  3606. --index;
  3607. break;
  3608. }
  3609. }
  3610. if (opts.empty()) {
  3611. continue;
  3612. }
  3613. if (!wrapperSep.empty()) {
  3614. if (concatFlagAndArgs) {
  3615. // insert flag elements except last one
  3616. for (auto i = wrapperFlag.begin(); i != wrapperFlag.end() - 1; ++i) {
  3617. result.emplace_back(*i, bt);
  3618. }
  3619. // concatenate last flag element and all list values
  3620. // in one option
  3621. result.emplace_back(wrapperFlag.back() + cmJoin(opts, wrapperSep), bt);
  3622. } else {
  3623. for (std::string const& i : wrapperFlag) {
  3624. result.emplace_back(i, bt);
  3625. }
  3626. // concatenate all list values in one option
  3627. result.emplace_back(cmJoin(opts, wrapperSep), bt);
  3628. }
  3629. } else {
  3630. // prefix each element of list with wrapper
  3631. if (concatFlagAndArgs) {
  3632. std::transform(opts.begin(), opts.end(), opts.begin(),
  3633. [&wrapperFlag](std::string const& o) -> std::string {
  3634. return wrapperFlag.back() + o;
  3635. });
  3636. }
  3637. for (std::string& o : opts) {
  3638. for (auto i = wrapperFlag.begin(),
  3639. e = concatFlagAndArgs ? wrapperFlag.end() - 1
  3640. : wrapperFlag.end();
  3641. i != e; ++i) {
  3642. result.emplace_back(*i, bt);
  3643. }
  3644. result.emplace_back(std::move(o), bt);
  3645. }
  3646. }
  3647. }
  3648. return result;
  3649. }
  3650. }
  3651. void cmGeneratorTarget::GetCompileOptions(std::vector<std::string>& result,
  3652. const std::string& config,
  3653. const std::string& language) const
  3654. {
  3655. std::vector<BT<std::string>> tmp = this->GetCompileOptions(config, language);
  3656. result.reserve(tmp.size());
  3657. for (BT<std::string>& v : tmp) {
  3658. result.emplace_back(std::move(v.Value));
  3659. }
  3660. }
  3661. std::vector<BT<std::string>> cmGeneratorTarget::GetCompileOptions(
  3662. std::string const& config, std::string const& language) const
  3663. {
  3664. ConfigAndLanguage cacheKey(config, language);
  3665. {
  3666. auto it = this->CompileOptionsCache.find(cacheKey);
  3667. if (it != this->CompileOptionsCache.end()) {
  3668. return it->second;
  3669. }
  3670. }
  3671. std::vector<BT<std::string>> result;
  3672. std::unordered_set<std::string> uniqueOptions;
  3673. cmGeneratorExpressionDAGChecker dagChecker(this, "COMPILE_OPTIONS", nullptr,
  3674. nullptr);
  3675. cmList debugProperties{ this->Makefile->GetDefinition(
  3676. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3677. bool debugOptions = !this->DebugCompileOptionsDone &&
  3678. cm::contains(debugProperties, "COMPILE_OPTIONS");
  3679. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3680. this->DebugCompileOptionsDone = true;
  3681. }
  3682. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  3683. this, config, language, &dagChecker, this->CompileOptionsEntries);
  3684. AddInterfaceEntries(this, config, "INTERFACE_COMPILE_OPTIONS", language,
  3685. &dagChecker, entries, IncludeRuntimeInterface::Yes);
  3686. processOptions(this, entries, result, uniqueOptions, debugOptions,
  3687. "compile options", OptionsParse::Shell);
  3688. CompileOptionsCache.emplace(cacheKey, result);
  3689. return result;
  3690. }
  3691. void cmGeneratorTarget::GetCompileFeatures(std::vector<std::string>& result,
  3692. const std::string& config) const
  3693. {
  3694. std::vector<BT<std::string>> tmp = this->GetCompileFeatures(config);
  3695. result.reserve(tmp.size());
  3696. for (BT<std::string>& v : tmp) {
  3697. result.emplace_back(std::move(v.Value));
  3698. }
  3699. }
  3700. std::vector<BT<std::string>> cmGeneratorTarget::GetCompileFeatures(
  3701. std::string const& config) const
  3702. {
  3703. std::vector<BT<std::string>> result;
  3704. std::unordered_set<std::string> uniqueFeatures;
  3705. cmGeneratorExpressionDAGChecker dagChecker(this, "COMPILE_FEATURES", nullptr,
  3706. nullptr);
  3707. cmList debugProperties{ this->Makefile->GetDefinition(
  3708. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3709. bool debugFeatures = !this->DebugCompileFeaturesDone &&
  3710. cm::contains(debugProperties, "COMPILE_FEATURES");
  3711. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3712. this->DebugCompileFeaturesDone = true;
  3713. }
  3714. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  3715. this, config, std::string(), &dagChecker, this->CompileFeaturesEntries);
  3716. AddInterfaceEntries(this, config, "INTERFACE_COMPILE_FEATURES",
  3717. std::string(), &dagChecker, entries,
  3718. IncludeRuntimeInterface::Yes);
  3719. processOptions(this, entries, result, uniqueFeatures, debugFeatures,
  3720. "compile features", OptionsParse::None);
  3721. return result;
  3722. }
  3723. void cmGeneratorTarget::GetCompileDefinitions(
  3724. std::vector<std::string>& result, const std::string& config,
  3725. const std::string& language) const
  3726. {
  3727. std::vector<BT<std::string>> tmp =
  3728. this->GetCompileDefinitions(config, language);
  3729. result.reserve(tmp.size());
  3730. for (BT<std::string>& v : tmp) {
  3731. result.emplace_back(std::move(v.Value));
  3732. }
  3733. }
  3734. std::vector<BT<std::string>> cmGeneratorTarget::GetCompileDefinitions(
  3735. std::string const& config, std::string const& language) const
  3736. {
  3737. ConfigAndLanguage cacheKey(config, language);
  3738. {
  3739. auto it = this->CompileDefinitionsCache.find(cacheKey);
  3740. if (it != this->CompileDefinitionsCache.end()) {
  3741. return it->second;
  3742. }
  3743. }
  3744. std::vector<BT<std::string>> list;
  3745. std::unordered_set<std::string> uniqueOptions;
  3746. cmGeneratorExpressionDAGChecker dagChecker(this, "COMPILE_DEFINITIONS",
  3747. nullptr, nullptr);
  3748. cmList debugProperties{ this->Makefile->GetDefinition(
  3749. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3750. bool debugDefines = !this->DebugCompileDefinitionsDone &&
  3751. cm::contains(debugProperties, "COMPILE_DEFINITIONS");
  3752. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3753. this->DebugCompileDefinitionsDone = true;
  3754. }
  3755. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  3756. this, config, language, &dagChecker, this->CompileDefinitionsEntries);
  3757. AddInterfaceEntries(this, config, "INTERFACE_COMPILE_DEFINITIONS", language,
  3758. &dagChecker, entries, IncludeRuntimeInterface::Yes);
  3759. if (!config.empty()) {
  3760. std::string configPropName =
  3761. "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config);
  3762. cmValue configProp = this->GetProperty(configPropName);
  3763. if (configProp) {
  3764. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0043)) {
  3765. case cmPolicies::WARN: {
  3766. this->LocalGenerator->IssueMessage(
  3767. MessageType::AUTHOR_WARNING,
  3768. cmPolicies::GetPolicyWarning(cmPolicies::CMP0043));
  3769. CM_FALLTHROUGH;
  3770. }
  3771. case cmPolicies::OLD: {
  3772. std::unique_ptr<TargetPropertyEntry> entry =
  3773. CreateTargetPropertyEntry(
  3774. *this->LocalGenerator->GetCMakeInstance(), *configProp);
  3775. entries.Entries.emplace_back(EvaluateTargetPropertyEntry(
  3776. this, config, language, &dagChecker, *entry));
  3777. } break;
  3778. case cmPolicies::NEW:
  3779. case cmPolicies::REQUIRED_ALWAYS:
  3780. case cmPolicies::REQUIRED_IF_USED:
  3781. break;
  3782. }
  3783. }
  3784. }
  3785. processOptions(this, entries, list, uniqueOptions, debugDefines,
  3786. "compile definitions", OptionsParse::None);
  3787. this->CompileDefinitionsCache.emplace(cacheKey, list);
  3788. return list;
  3789. }
  3790. std::vector<BT<std::string>> cmGeneratorTarget::GetPrecompileHeaders(
  3791. const std::string& config, const std::string& language) const
  3792. {
  3793. ConfigAndLanguage cacheKey(config, language);
  3794. {
  3795. auto it = this->PrecompileHeadersCache.find(cacheKey);
  3796. if (it != this->PrecompileHeadersCache.end()) {
  3797. return it->second;
  3798. }
  3799. }
  3800. std::unordered_set<std::string> uniqueOptions;
  3801. cmGeneratorExpressionDAGChecker dagChecker(this, "PRECOMPILE_HEADERS",
  3802. nullptr, nullptr);
  3803. cmList debugProperties{ this->Makefile->GetDefinition(
  3804. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3805. bool debugDefines = !this->DebugPrecompileHeadersDone &&
  3806. std::find(debugProperties.begin(), debugProperties.end(),
  3807. "PRECOMPILE_HEADERS") != debugProperties.end();
  3808. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3809. this->DebugPrecompileHeadersDone = true;
  3810. }
  3811. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  3812. this, config, language, &dagChecker, this->PrecompileHeadersEntries);
  3813. AddInterfaceEntries(this, config, "INTERFACE_PRECOMPILE_HEADERS", language,
  3814. &dagChecker, entries, IncludeRuntimeInterface::Yes);
  3815. std::vector<BT<std::string>> list;
  3816. processOptions(this, entries, list, uniqueOptions, debugDefines,
  3817. "precompile headers", OptionsParse::None);
  3818. this->PrecompileHeadersCache.emplace(cacheKey, list);
  3819. return list;
  3820. }
  3821. std::vector<std::string> cmGeneratorTarget::GetPchArchs(
  3822. std::string const& config, std::string const& lang) const
  3823. {
  3824. std::vector<std::string> pchArchs;
  3825. if (!this->GetGlobalGenerator()->IsXcode()) {
  3826. pchArchs = this->GetAppleArchs(config, lang);
  3827. }
  3828. if (pchArchs.size() < 2) {
  3829. // We do not need per-arch PCH files when building for one architecture.
  3830. pchArchs = { {} };
  3831. }
  3832. return pchArchs;
  3833. }
  3834. std::string cmGeneratorTarget::GetPchHeader(const std::string& config,
  3835. const std::string& language,
  3836. const std::string& arch) const
  3837. {
  3838. if (language != "C" && language != "CXX" && language != "OBJC" &&
  3839. language != "OBJCXX") {
  3840. return std::string();
  3841. }
  3842. if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  3843. return std::string();
  3844. }
  3845. const cmGeneratorTarget* generatorTarget = this;
  3846. cmValue pchReuseFrom =
  3847. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  3848. const auto inserted =
  3849. this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
  3850. if (inserted.second) {
  3851. const std::vector<BT<std::string>> headers =
  3852. this->GetPrecompileHeaders(config, language);
  3853. if (headers.empty() && !pchReuseFrom) {
  3854. return std::string();
  3855. }
  3856. std::string& filename = inserted.first->second;
  3857. if (pchReuseFrom) {
  3858. generatorTarget =
  3859. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  3860. }
  3861. const std::map<std::string, std::string> languageToExtension = {
  3862. { "C", ".h" },
  3863. { "CXX", ".hxx" },
  3864. { "OBJC", ".objc.h" },
  3865. { "OBJCXX", ".objcxx.hxx" }
  3866. };
  3867. filename = generatorTarget->GetSupportDirectory();
  3868. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  3869. filename = cmStrCat(filename, "/", config);
  3870. }
  3871. filename =
  3872. cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat("_", arch),
  3873. languageToExtension.at(language));
  3874. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  3875. if (!pchReuseFrom) {
  3876. cmValue pchPrologue =
  3877. this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
  3878. cmValue pchEpilogue =
  3879. this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
  3880. std::string firstHeaderOnDisk;
  3881. {
  3882. cmGeneratedFileStream file(
  3883. filename_tmp, false,
  3884. this->GetGlobalGenerator()->GetMakefileEncoding());
  3885. file << "/* generated by CMake */\n\n";
  3886. if (pchPrologue) {
  3887. file << *pchPrologue << "\n";
  3888. }
  3889. if (this->GetGlobalGenerator()->IsXcode()) {
  3890. file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  3891. }
  3892. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  3893. file << "#ifdef __cplusplus\n";
  3894. }
  3895. for (auto const& header_bt : headers) {
  3896. if (header_bt.Value.empty()) {
  3897. continue;
  3898. }
  3899. if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
  3900. file << "#include " << header_bt.Value << "\n";
  3901. } else {
  3902. file << "#include \"" << header_bt.Value << "\"\n";
  3903. }
  3904. if (cmSystemTools::FileExists(header_bt.Value) &&
  3905. firstHeaderOnDisk.empty()) {
  3906. firstHeaderOnDisk = header_bt.Value;
  3907. }
  3908. }
  3909. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  3910. file << "#endif // __cplusplus\n";
  3911. }
  3912. if (this->GetGlobalGenerator()->IsXcode()) {
  3913. file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  3914. }
  3915. if (pchEpilogue) {
  3916. file << *pchEpilogue << "\n";
  3917. }
  3918. }
  3919. if (!firstHeaderOnDisk.empty()) {
  3920. cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
  3921. }
  3922. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  3923. }
  3924. }
  3925. return inserted.first->second;
  3926. }
  3927. std::string cmGeneratorTarget::GetPchSource(const std::string& config,
  3928. const std::string& language,
  3929. const std::string& arch) const
  3930. {
  3931. if (language != "C" && language != "CXX" && language != "OBJC" &&
  3932. language != "OBJCXX") {
  3933. return std::string();
  3934. }
  3935. const auto inserted =
  3936. this->PchSources.insert(std::make_pair(language + config + arch, ""));
  3937. if (inserted.second) {
  3938. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  3939. if (pchHeader.empty()) {
  3940. return std::string();
  3941. }
  3942. std::string& filename = inserted.first->second;
  3943. const cmGeneratorTarget* generatorTarget = this;
  3944. cmValue pchReuseFrom =
  3945. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  3946. if (pchReuseFrom) {
  3947. generatorTarget =
  3948. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  3949. }
  3950. filename = cmStrCat(generatorTarget->GetSupportDirectory(), "/cmake_pch");
  3951. // For GCC the source extension will be transformed into .h[xx].gch
  3952. if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  3953. const std::map<std::string, std::string> languageToExtension = {
  3954. { "C", ".h.c" },
  3955. { "CXX", ".hxx.cxx" },
  3956. { "OBJC", ".objc.h.m" },
  3957. { "OBJCXX", ".objcxx.hxx.mm" }
  3958. };
  3959. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat("_", arch),
  3960. languageToExtension.at(language));
  3961. } else {
  3962. const std::map<std::string, std::string> languageToExtension = {
  3963. { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
  3964. };
  3965. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat("_", arch),
  3966. languageToExtension.at(language));
  3967. }
  3968. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  3969. if (!pchReuseFrom) {
  3970. {
  3971. cmGeneratedFileStream file(filename_tmp);
  3972. file << "/* generated by CMake */\n";
  3973. }
  3974. cmFileTimes::Copy(pchHeader, filename_tmp);
  3975. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  3976. }
  3977. }
  3978. return inserted.first->second;
  3979. }
  3980. std::string cmGeneratorTarget::GetPchFileObject(const std::string& config,
  3981. const std::string& language,
  3982. const std::string& arch)
  3983. {
  3984. if (language != "C" && language != "CXX" && language != "OBJC" &&
  3985. language != "OBJCXX") {
  3986. return std::string();
  3987. }
  3988. const auto inserted =
  3989. this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
  3990. if (inserted.second) {
  3991. const std::string pchSource = this->GetPchSource(config, language, arch);
  3992. if (pchSource.empty()) {
  3993. return std::string();
  3994. }
  3995. std::string& filename = inserted.first->second;
  3996. auto* pchSf = this->Makefile->GetOrCreateSource(
  3997. pchSource, false, cmSourceFileLocationKind::Known);
  3998. filename = cmStrCat(this->ObjectDirectory, this->GetObjectName(pchSf));
  3999. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  4000. cmSystemTools::ReplaceString(
  4001. filename, this->GetGlobalGenerator()->GetCMakeCFGIntDir(), config);
  4002. }
  4003. }
  4004. return inserted.first->second;
  4005. }
  4006. std::string cmGeneratorTarget::GetPchFile(const std::string& config,
  4007. const std::string& language,
  4008. const std::string& arch)
  4009. {
  4010. const auto inserted =
  4011. this->PchFiles.insert(std::make_pair(language + config + arch, ""));
  4012. if (inserted.second) {
  4013. std::string& pchFile = inserted.first->second;
  4014. const std::string pchExtension =
  4015. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  4016. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  4017. auto replaceExtension = [](const std::string& str,
  4018. const std::string& ext) -> std::string {
  4019. auto dot_pos = str.rfind('.');
  4020. std::string result;
  4021. if (dot_pos != std::string::npos) {
  4022. result = str.substr(0, dot_pos);
  4023. }
  4024. result += ext;
  4025. return result;
  4026. };
  4027. cmGeneratorTarget* generatorTarget = this;
  4028. cmValue pchReuseFrom =
  4029. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  4030. if (pchReuseFrom) {
  4031. generatorTarget =
  4032. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  4033. }
  4034. const std::string pchFileObject =
  4035. generatorTarget->GetPchFileObject(config, language, arch);
  4036. if (!pchExtension.empty()) {
  4037. pchFile = replaceExtension(pchFileObject, pchExtension);
  4038. }
  4039. } else {
  4040. pchFile = this->GetPchHeader(config, language, arch);
  4041. pchFile += pchExtension;
  4042. }
  4043. }
  4044. return inserted.first->second;
  4045. }
  4046. std::string cmGeneratorTarget::GetPchCreateCompileOptions(
  4047. const std::string& config, const std::string& language,
  4048. const std::string& arch)
  4049. {
  4050. const auto inserted = this->PchCreateCompileOptions.insert(
  4051. std::make_pair(language + config + arch, ""));
  4052. if (inserted.second) {
  4053. std::string& createOptionList = inserted.first->second;
  4054. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  4055. createOptionList = this->Makefile->GetSafeDefinition(
  4056. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  4057. }
  4058. if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
  4059. std::string varName = cmStrCat(
  4060. "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
  4061. std::string instantiateOption =
  4062. this->Makefile->GetSafeDefinition(varName);
  4063. if (!instantiateOption.empty()) {
  4064. createOptionList = cmStrCat(createOptionList, ";", instantiateOption);
  4065. }
  4066. }
  4067. const std::string createOptVar =
  4068. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
  4069. createOptionList = cmStrCat(
  4070. createOptionList, ";", this->Makefile->GetSafeDefinition(createOptVar));
  4071. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  4072. const std::string pchFile = this->GetPchFile(config, language, arch);
  4073. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>", pchHeader);
  4074. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
  4075. }
  4076. return inserted.first->second;
  4077. }
  4078. std::string cmGeneratorTarget::GetPchUseCompileOptions(
  4079. const std::string& config, const std::string& language,
  4080. const std::string& arch)
  4081. {
  4082. const auto inserted = this->PchUseCompileOptions.insert(
  4083. std::make_pair(language + config + arch, ""));
  4084. if (inserted.second) {
  4085. std::string& useOptionList = inserted.first->second;
  4086. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  4087. useOptionList = this->Makefile->GetSafeDefinition(
  4088. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  4089. }
  4090. const std::string useOptVar =
  4091. cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
  4092. std::string const& useOptionListProperty =
  4093. this->GetSafeProperty(useOptVar);
  4094. useOptionList = cmStrCat(
  4095. useOptionList, ";",
  4096. useOptionListProperty.empty()
  4097. ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
  4098. : useOptionListProperty);
  4099. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  4100. const std::string pchFile = this->GetPchFile(config, language, arch);
  4101. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
  4102. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
  4103. }
  4104. return inserted.first->second;
  4105. }
  4106. void cmGeneratorTarget::AddSourceFileToUnityBatch(
  4107. const std::string& sourceFilename)
  4108. {
  4109. this->UnityBatchedSourceFiles.insert(sourceFilename);
  4110. }
  4111. bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
  4112. const std::string& sourceFilename) const
  4113. {
  4114. if (!this->GetPropertyAsBool("UNITY_BUILD")) {
  4115. return false;
  4116. }
  4117. return this->UnityBatchedSourceFiles.find(sourceFilename) !=
  4118. this->UnityBatchedSourceFiles.end();
  4119. }
  4120. void cmGeneratorTarget::GetLinkOptions(std::vector<std::string>& result,
  4121. const std::string& config,
  4122. const std::string& language) const
  4123. {
  4124. if (this->IsDeviceLink() &&
  4125. this->GetPolicyStatusCMP0105() != cmPolicies::NEW) {
  4126. // link options are not propagated to the device link step
  4127. return;
  4128. }
  4129. std::vector<BT<std::string>> tmp = this->GetLinkOptions(config, language);
  4130. result.reserve(tmp.size());
  4131. for (BT<std::string>& v : tmp) {
  4132. result.emplace_back(std::move(v.Value));
  4133. }
  4134. }
  4135. std::vector<BT<std::string>> cmGeneratorTarget::GetLinkOptions(
  4136. std::string const& config, std::string const& language) const
  4137. {
  4138. ConfigAndLanguage cacheKey(
  4139. config, cmStrCat(language, this->IsDeviceLink() ? "-device" : ""));
  4140. {
  4141. auto it = this->LinkOptionsCache.find(cacheKey);
  4142. if (it != this->LinkOptionsCache.end()) {
  4143. return it->second;
  4144. }
  4145. }
  4146. std::vector<BT<std::string>> result;
  4147. std::unordered_set<std::string> uniqueOptions;
  4148. cmGeneratorExpressionDAGChecker dagChecker(this, "LINK_OPTIONS", nullptr,
  4149. nullptr);
  4150. cmList debugProperties{ this->Makefile->GetDefinition(
  4151. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  4152. bool debugOptions = !this->DebugLinkOptionsDone &&
  4153. cm::contains(debugProperties, "LINK_OPTIONS");
  4154. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  4155. this->DebugLinkOptionsDone = true;
  4156. }
  4157. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  4158. this, config, language, &dagChecker, this->LinkOptionsEntries);
  4159. AddInterfaceEntries(this, config, "INTERFACE_LINK_OPTIONS", language,
  4160. &dagChecker, entries, IncludeRuntimeInterface::Yes,
  4161. this->GetPolicyStatusCMP0099() == cmPolicies::NEW
  4162. ? LinkInterfaceFor::Link
  4163. : LinkInterfaceFor::Usage);
  4164. processOptions(this, entries, result, uniqueOptions, debugOptions,
  4165. "link options", OptionsParse::Shell, this->IsDeviceLink());
  4166. if (this->IsDeviceLink()) {
  4167. // wrap host link options
  4168. const std::string wrapper(this->Makefile->GetSafeDefinition(
  4169. "CMAKE_" + language + "_DEVICE_COMPILER_WRAPPER_FLAG"));
  4170. cmList wrapperFlag{ wrapper };
  4171. const std::string wrapperSep(this->Makefile->GetSafeDefinition(
  4172. "CMAKE_" + language + "_DEVICE_COMPILER_WRAPPER_FLAG_SEP"));
  4173. bool concatFlagAndArgs = true;
  4174. if (!wrapperFlag.empty() && wrapperFlag.back() == " ") {
  4175. concatFlagAndArgs = false;
  4176. wrapperFlag.pop_back();
  4177. }
  4178. auto it = result.begin();
  4179. while (it != result.end()) {
  4180. if (it->Value == DL_BEGIN) {
  4181. // device link options, no treatment
  4182. it = result.erase(it);
  4183. it = std::find_if(it, result.end(), [](const BT<std::string>& item) {
  4184. return item.Value == DL_END;
  4185. });
  4186. if (it != result.end()) {
  4187. it = result.erase(it);
  4188. }
  4189. } else {
  4190. // host link options must be wrapped
  4191. std::vector<std::string> options;
  4192. cmSystemTools::ParseUnixCommandLine(it->Value.c_str(), options);
  4193. auto hostOptions = wrapOptions(options, it->Backtrace, wrapperFlag,
  4194. wrapperSep, concatFlagAndArgs);
  4195. it = result.erase(it);
  4196. // some compilers (like gcc 4.8 or Intel 19.0 or XLC 16) do not respect
  4197. // C++11 standard: 'std::vector::insert()' do not returns an iterator,
  4198. // so need to recompute the iterator after insertion.
  4199. if (it == result.end()) {
  4200. cm::append(result, hostOptions);
  4201. it = result.end();
  4202. } else {
  4203. auto index = it - result.begin();
  4204. result.insert(it, hostOptions.begin(), hostOptions.end());
  4205. it = result.begin() + index + hostOptions.size();
  4206. }
  4207. }
  4208. }
  4209. }
  4210. // Last step: replace "LINKER:" prefixed elements by
  4211. // actual linker wrapper
  4212. result = this->ResolveLinkerWrapper(result, language);
  4213. this->LinkOptionsCache.emplace(cacheKey, result);
  4214. return result;
  4215. }
  4216. std::vector<BT<std::string>>& cmGeneratorTarget::ResolveLinkerWrapper(
  4217. std::vector<BT<std::string>>& result, const std::string& language,
  4218. bool joinItems) const
  4219. {
  4220. // replace "LINKER:" prefixed elements by actual linker wrapper
  4221. const std::string wrapper(this->Makefile->GetSafeDefinition(
  4222. "CMAKE_" + language +
  4223. (this->IsDeviceLink() ? "_DEVICE_LINKER_WRAPPER_FLAG"
  4224. : "_LINKER_WRAPPER_FLAG")));
  4225. cmList wrapperFlag{ wrapper };
  4226. const std::string wrapperSep(this->Makefile->GetSafeDefinition(
  4227. "CMAKE_" + language +
  4228. (this->IsDeviceLink() ? "_DEVICE_LINKER_WRAPPER_FLAG_SEP"
  4229. : "_LINKER_WRAPPER_FLAG_SEP")));
  4230. bool concatFlagAndArgs = true;
  4231. if (!wrapperFlag.empty() && wrapperFlag.back() == " ") {
  4232. concatFlagAndArgs = false;
  4233. wrapperFlag.pop_back();
  4234. }
  4235. const std::string LINKER{ "LINKER:" };
  4236. const std::string SHELL{ "SHELL:" };
  4237. const std::string LINKER_SHELL = LINKER + SHELL;
  4238. std::vector<BT<std::string>>::iterator entry;
  4239. while ((entry = std::find_if(result.begin(), result.end(),
  4240. [&LINKER](BT<std::string> const& item) -> bool {
  4241. return item.Value.compare(0, LINKER.length(),
  4242. LINKER) == 0;
  4243. })) != result.end()) {
  4244. std::string value = std::move(entry->Value);
  4245. cmListFileBacktrace bt = std::move(entry->Backtrace);
  4246. entry = result.erase(entry);
  4247. std::vector<std::string> linkerOptions;
  4248. if (value.compare(0, LINKER_SHELL.length(), LINKER_SHELL) == 0) {
  4249. cmSystemTools::ParseUnixCommandLine(
  4250. value.c_str() + LINKER_SHELL.length(), linkerOptions);
  4251. } else {
  4252. linkerOptions = cmTokenize(value.substr(LINKER.length()), ",");
  4253. }
  4254. if (linkerOptions.empty() ||
  4255. (linkerOptions.size() == 1 && linkerOptions.front().empty())) {
  4256. continue;
  4257. }
  4258. // for now, raise an error if prefix SHELL: is part of arguments
  4259. if (std::find_if(linkerOptions.begin(), linkerOptions.end(),
  4260. [&SHELL](const std::string& item) -> bool {
  4261. return item.find(SHELL) != std::string::npos;
  4262. }) != linkerOptions.end()) {
  4263. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  4264. MessageType::FATAL_ERROR,
  4265. "'SHELL:' prefix is not supported as part of 'LINKER:' arguments.",
  4266. this->GetBacktrace());
  4267. return result;
  4268. }
  4269. std::vector<BT<std::string>> options = wrapOptions(
  4270. linkerOptions, bt, wrapperFlag, wrapperSep, concatFlagAndArgs);
  4271. if (joinItems) {
  4272. result.insert(entry,
  4273. cmJoin(cmRange<decltype(options.cbegin())>(
  4274. options.cbegin(), options.cend()),
  4275. " "_s));
  4276. } else {
  4277. result.insert(entry, options.begin(), options.end());
  4278. }
  4279. }
  4280. return result;
  4281. }
  4282. void cmGeneratorTarget::GetStaticLibraryLinkOptions(
  4283. std::vector<std::string>& result, const std::string& config,
  4284. const std::string& language) const
  4285. {
  4286. std::vector<BT<std::string>> tmp =
  4287. this->GetStaticLibraryLinkOptions(config, language);
  4288. result.reserve(tmp.size());
  4289. for (BT<std::string>& v : tmp) {
  4290. result.emplace_back(std::move(v.Value));
  4291. }
  4292. }
  4293. std::vector<BT<std::string>> cmGeneratorTarget::GetStaticLibraryLinkOptions(
  4294. std::string const& config, std::string const& language) const
  4295. {
  4296. std::vector<BT<std::string>> result;
  4297. std::unordered_set<std::string> uniqueOptions;
  4298. cmGeneratorExpressionDAGChecker dagChecker(this, "STATIC_LIBRARY_OPTIONS",
  4299. nullptr, nullptr);
  4300. EvaluatedTargetPropertyEntries entries;
  4301. if (cmValue linkOptions = this->GetProperty("STATIC_LIBRARY_OPTIONS")) {
  4302. std::unique_ptr<TargetPropertyEntry> entry = CreateTargetPropertyEntry(
  4303. *this->LocalGenerator->GetCMakeInstance(), *linkOptions);
  4304. entries.Entries.emplace_back(EvaluateTargetPropertyEntry(
  4305. this, config, language, &dagChecker, *entry));
  4306. }
  4307. processOptions(this, entries, result, uniqueOptions, false,
  4308. "static library link options", OptionsParse::Shell);
  4309. return result;
  4310. }
  4311. namespace {
  4312. void processLinkDirectories(cmGeneratorTarget const* tgt,
  4313. EvaluatedTargetPropertyEntries& entries,
  4314. std::vector<BT<std::string>>& directories,
  4315. std::unordered_set<std::string>& uniqueDirectories,
  4316. bool debugDirectories)
  4317. {
  4318. for (EvaluatedTargetPropertyEntry& entry : entries.Entries) {
  4319. cmLinkImplItem const& item = entry.LinkImplItem;
  4320. std::string const& targetName = item.AsStr();
  4321. std::string usedDirectories;
  4322. for (std::string& entryDirectory : entry.Values) {
  4323. if (!cmSystemTools::FileIsFullPath(entryDirectory)) {
  4324. std::ostringstream e;
  4325. bool noMessage = false;
  4326. MessageType messageType = MessageType::FATAL_ERROR;
  4327. if (!targetName.empty()) {
  4328. /* clang-format off */
  4329. e << "Target \"" << targetName << "\" contains relative "
  4330. "path in its INTERFACE_LINK_DIRECTORIES:\n"
  4331. " \"" << entryDirectory << "\"";
  4332. /* clang-format on */
  4333. } else {
  4334. switch (tgt->GetPolicyStatusCMP0081()) {
  4335. case cmPolicies::WARN: {
  4336. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0081) << "\n";
  4337. messageType = MessageType::AUTHOR_WARNING;
  4338. } break;
  4339. case cmPolicies::OLD:
  4340. noMessage = true;
  4341. break;
  4342. case cmPolicies::REQUIRED_IF_USED:
  4343. case cmPolicies::REQUIRED_ALWAYS:
  4344. case cmPolicies::NEW:
  4345. // Issue the fatal message.
  4346. break;
  4347. }
  4348. e << "Found relative path while evaluating link directories of "
  4349. "\""
  4350. << tgt->GetName() << "\":\n \"" << entryDirectory << "\"\n";
  4351. }
  4352. if (!noMessage) {
  4353. tgt->GetLocalGenerator()->IssueMessage(messageType, e.str());
  4354. if (messageType == MessageType::FATAL_ERROR) {
  4355. return;
  4356. }
  4357. }
  4358. }
  4359. // Sanitize the path the same way the link_directories command does
  4360. // in case projects set the LINK_DIRECTORIES property directly.
  4361. cmSystemTools::ConvertToUnixSlashes(entryDirectory);
  4362. if (uniqueDirectories.insert(entryDirectory).second) {
  4363. directories.emplace_back(entryDirectory, entry.Backtrace);
  4364. if (debugDirectories) {
  4365. usedDirectories += " * " + entryDirectory + "\n";
  4366. }
  4367. }
  4368. }
  4369. if (!usedDirectories.empty()) {
  4370. tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  4371. MessageType::LOG,
  4372. std::string("Used link directories for target ") + tgt->GetName() +
  4373. ":\n" + usedDirectories,
  4374. entry.Backtrace);
  4375. }
  4376. }
  4377. }
  4378. }
  4379. void cmGeneratorTarget::GetLinkDirectories(std::vector<std::string>& result,
  4380. const std::string& config,
  4381. const std::string& language) const
  4382. {
  4383. std::vector<BT<std::string>> tmp =
  4384. this->GetLinkDirectories(config, language);
  4385. result.reserve(tmp.size());
  4386. for (BT<std::string>& v : tmp) {
  4387. result.emplace_back(std::move(v.Value));
  4388. }
  4389. }
  4390. std::vector<BT<std::string>> cmGeneratorTarget::GetLinkDirectories(
  4391. std::string const& config, std::string const& language) const
  4392. {
  4393. ConfigAndLanguage cacheKey(
  4394. config, cmStrCat(language, this->IsDeviceLink() ? "-device" : ""));
  4395. {
  4396. auto it = this->LinkDirectoriesCache.find(cacheKey);
  4397. if (it != this->LinkDirectoriesCache.end()) {
  4398. return it->second;
  4399. }
  4400. }
  4401. std::vector<BT<std::string>> result;
  4402. std::unordered_set<std::string> uniqueDirectories;
  4403. cmGeneratorExpressionDAGChecker dagChecker(this, "LINK_DIRECTORIES", nullptr,
  4404. nullptr);
  4405. cmList debugProperties{ this->Makefile->GetDefinition(
  4406. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  4407. bool debugDirectories = !this->DebugLinkDirectoriesDone &&
  4408. cm::contains(debugProperties, "LINK_DIRECTORIES");
  4409. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  4410. this->DebugLinkDirectoriesDone = true;
  4411. }
  4412. EvaluatedTargetPropertyEntries entries = EvaluateTargetPropertyEntries(
  4413. this, config, language, &dagChecker, this->LinkDirectoriesEntries);
  4414. AddInterfaceEntries(this, config, "INTERFACE_LINK_DIRECTORIES", language,
  4415. &dagChecker, entries, IncludeRuntimeInterface::Yes,
  4416. this->GetPolicyStatusCMP0099() == cmPolicies::NEW
  4417. ? LinkInterfaceFor::Link
  4418. : LinkInterfaceFor::Usage);
  4419. processLinkDirectories(this, entries, result, uniqueDirectories,
  4420. debugDirectories);
  4421. this->LinkDirectoriesCache.emplace(cacheKey, result);
  4422. return result;
  4423. }
  4424. void cmGeneratorTarget::GetLinkDepends(std::vector<std::string>& result,
  4425. const std::string& config,
  4426. const std::string& language) const
  4427. {
  4428. std::vector<BT<std::string>> tmp = this->GetLinkDepends(config, language);
  4429. result.reserve(tmp.size());
  4430. for (BT<std::string>& v : tmp) {
  4431. result.emplace_back(std::move(v.Value));
  4432. }
  4433. }
  4434. std::vector<BT<std::string>> cmGeneratorTarget::GetLinkDepends(
  4435. std::string const& config, std::string const& language) const
  4436. {
  4437. std::vector<BT<std::string>> result;
  4438. std::unordered_set<std::string> uniqueOptions;
  4439. cmGeneratorExpressionDAGChecker dagChecker(this, "LINK_DEPENDS", nullptr,
  4440. nullptr);
  4441. EvaluatedTargetPropertyEntries entries;
  4442. if (cmValue linkDepends = this->GetProperty("LINK_DEPENDS")) {
  4443. cmList depends{ *linkDepends };
  4444. for (const auto& depend : depends) {
  4445. std::unique_ptr<TargetPropertyEntry> entry = CreateTargetPropertyEntry(
  4446. *this->LocalGenerator->GetCMakeInstance(), depend);
  4447. entries.Entries.emplace_back(EvaluateTargetPropertyEntry(
  4448. this, config, language, &dagChecker, *entry));
  4449. }
  4450. }
  4451. AddInterfaceEntries(this, config, "INTERFACE_LINK_DEPENDS", language,
  4452. &dagChecker, entries, IncludeRuntimeInterface::Yes,
  4453. this->GetPolicyStatusCMP0099() == cmPolicies::NEW
  4454. ? LinkInterfaceFor::Link
  4455. : LinkInterfaceFor::Usage);
  4456. processOptions(this, entries, result, uniqueOptions, false, "link depends",
  4457. OptionsParse::None);
  4458. return result;
  4459. }
  4460. void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const
  4461. {
  4462. if (this->IsImported()) {
  4463. return;
  4464. }
  4465. cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
  4466. // Get the names.
  4467. cmGeneratorTarget::Names targetNames;
  4468. if (this->GetType() == cmStateEnums::EXECUTABLE) {
  4469. targetNames = this->GetExecutableNames(config);
  4470. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4471. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4472. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4473. targetNames = this->GetLibraryNames(config);
  4474. } else {
  4475. return;
  4476. }
  4477. // Get the directory.
  4478. std::string dir =
  4479. this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
  4480. // Add each name.
  4481. std::string f;
  4482. if (!targetNames.Output.empty()) {
  4483. f = cmStrCat(dir, '/', targetNames.Output);
  4484. gg->AddToManifest(f);
  4485. }
  4486. if (!targetNames.SharedObject.empty()) {
  4487. f = cmStrCat(dir, '/', targetNames.SharedObject);
  4488. gg->AddToManifest(f);
  4489. }
  4490. if (!targetNames.Real.empty()) {
  4491. f = cmStrCat(dir, '/', targetNames.Real);
  4492. gg->AddToManifest(f);
  4493. }
  4494. if (!targetNames.PDB.empty()) {
  4495. f = cmStrCat(dir, '/', targetNames.PDB);
  4496. gg->AddToManifest(f);
  4497. }
  4498. dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
  4499. if (!targetNames.ImportOutput.empty()) {
  4500. f = cmStrCat(dir, '/', targetNames.ImportOutput);
  4501. gg->AddToManifest(f);
  4502. }
  4503. if (!targetNames.ImportLibrary.empty()) {
  4504. f = cmStrCat(dir, '/', targetNames.ImportLibrary);
  4505. gg->AddToManifest(f);
  4506. }
  4507. if (!targetNames.ImportReal.empty()) {
  4508. f = cmStrCat(dir, '/', targetNames.ImportReal);
  4509. gg->AddToManifest(f);
  4510. }
  4511. }
  4512. cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
  4513. std::string const& lang, std::string const& config) const
  4514. {
  4515. cm::optional<cmStandardLevel> level;
  4516. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  4517. auto i = this->ExplicitStandardLevel.find(key);
  4518. if (i != this->ExplicitStandardLevel.end()) {
  4519. level = i->second;
  4520. }
  4521. return level;
  4522. }
  4523. void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
  4524. std::string const& config,
  4525. cmStandardLevel level)
  4526. {
  4527. auto e = this->ExplicitStandardLevel.emplace(
  4528. cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
  4529. if (!e.second && e.first->second < level) {
  4530. e.first->second = level;
  4531. }
  4532. }
  4533. bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
  4534. {
  4535. cmStandardLevelResolver standardResolver(this->Makefile);
  4536. for (std::string const& lang :
  4537. this->Makefile->GetState()->GetEnabledLanguages()) {
  4538. if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
  4539. if (cm::optional<cmStandardLevel> langLevel =
  4540. standardResolver.LanguageStandardLevel(lang, *languageStd)) {
  4541. this->UpdateExplicitStandardLevel(lang, config, *langLevel);
  4542. }
  4543. }
  4544. }
  4545. // Compute the language standard based on the compile features.
  4546. std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
  4547. for (BT<std::string> const& f : features) {
  4548. std::string lang;
  4549. if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
  4550. lang, nullptr)) {
  4551. return false;
  4552. }
  4553. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  4554. cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
  4555. cm::optional<cmStandardLevel> featureLevel;
  4556. std::string newRequiredStandard;
  4557. if (!standardResolver.GetNewRequiredStandard(
  4558. this->Target->GetName(), f.Value, currentLanguageStandard,
  4559. featureLevel, newRequiredStandard)) {
  4560. return false;
  4561. }
  4562. if (featureLevel) {
  4563. this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
  4564. }
  4565. if (!newRequiredStandard.empty()) {
  4566. BTs<std::string>& languageStandardProperty =
  4567. this->LanguageStandardMap[key];
  4568. if (languageStandardProperty.Value != newRequiredStandard) {
  4569. languageStandardProperty.Value = newRequiredStandard;
  4570. languageStandardProperty.Backtraces.clear();
  4571. }
  4572. languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
  4573. }
  4574. }
  4575. return true;
  4576. }
  4577. bool cmGeneratorTarget::ComputeCompileFeatures(
  4578. std::string const& config, std::set<LanguagePair> const& languagePairs)
  4579. {
  4580. for (const auto& language : languagePairs) {
  4581. BTs<std::string> const* generatorTargetLanguageStandard =
  4582. this->GetLanguageStandardProperty(language.first, config);
  4583. if (!generatorTargetLanguageStandard) {
  4584. // If the standard isn't explicitly set we copy it over from the
  4585. // specified paired language.
  4586. std::string key =
  4587. cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
  4588. BTs<std::string> const* standardToCopy =
  4589. this->GetLanguageStandardProperty(language.second, config);
  4590. if (standardToCopy) {
  4591. this->LanguageStandardMap[key] = *standardToCopy;
  4592. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  4593. } else {
  4594. cmValue defaultStandard = this->Makefile->GetDefinition(
  4595. cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
  4596. if (defaultStandard) {
  4597. this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
  4598. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  4599. }
  4600. }
  4601. // Custom updates for the CUDA standard.
  4602. if (generatorTargetLanguageStandard != nullptr &&
  4603. (language.first == "CUDA")) {
  4604. if (generatorTargetLanguageStandard->Value == "98") {
  4605. this->LanguageStandardMap[key].Value = "03";
  4606. }
  4607. }
  4608. }
  4609. }
  4610. return true;
  4611. }
  4612. std::string cmGeneratorTarget::GetImportedLibName(
  4613. std::string const& config) const
  4614. {
  4615. if (cmGeneratorTarget::ImportInfo const* info =
  4616. this->GetImportInfo(config)) {
  4617. return info->LibName;
  4618. }
  4619. return std::string();
  4620. }
  4621. std::string cmGeneratorTarget::GetFullPath(const std::string& config,
  4622. cmStateEnums::ArtifactType artifact,
  4623. bool realname) const
  4624. {
  4625. if (this->IsImported()) {
  4626. return this->Target->ImportedGetFullPath(config, artifact);
  4627. }
  4628. return this->NormalGetFullPath(config, artifact, realname);
  4629. }
  4630. std::string cmGeneratorTarget::NormalGetFullPath(
  4631. const std::string& config, cmStateEnums::ArtifactType artifact,
  4632. bool realname) const
  4633. {
  4634. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  4635. if (this->IsAppBundleOnApple()) {
  4636. fpath =
  4637. cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
  4638. }
  4639. // Add the full name of the target.
  4640. switch (artifact) {
  4641. case cmStateEnums::RuntimeBinaryArtifact:
  4642. if (realname) {
  4643. fpath += this->NormalGetRealName(config);
  4644. } else {
  4645. fpath +=
  4646. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
  4647. }
  4648. break;
  4649. case cmStateEnums::ImportLibraryArtifact:
  4650. if (realname) {
  4651. fpath +=
  4652. this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
  4653. } else {
  4654. fpath +=
  4655. this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
  4656. }
  4657. break;
  4658. }
  4659. return fpath;
  4660. }
  4661. std::string cmGeneratorTarget::NormalGetRealName(
  4662. const std::string& config, cmStateEnums::ArtifactType artifact) const
  4663. {
  4664. // This should not be called for imported targets.
  4665. // TODO: Split cmTarget into a class hierarchy to get compile-time
  4666. // enforcement of the limited imported target API.
  4667. if (this->IsImported()) {
  4668. std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
  4669. this->GetName());
  4670. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  4671. }
  4672. Names names = this->GetType() == cmStateEnums::EXECUTABLE
  4673. ? this->GetExecutableNames(config)
  4674. : this->GetLibraryNames(config);
  4675. // Compute the real name that will be built.
  4676. return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
  4677. : names.ImportReal;
  4678. }
  4679. cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
  4680. const std::string& config) const
  4681. {
  4682. cmGeneratorTarget::Names targetNames;
  4683. // This should not be called for imported targets.
  4684. // TODO: Split cmTarget into a class hierarchy to get compile-time
  4685. // enforcement of the limited imported target API.
  4686. if (this->IsImported()) {
  4687. std::string msg =
  4688. cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
  4689. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  4690. }
  4691. // Check for library version properties.
  4692. cmValue version = this->GetProperty("VERSION");
  4693. cmValue soversion = this->GetProperty("SOVERSION");
  4694. if (!this->HasSOName(config) ||
  4695. this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
  4696. this->IsFrameworkOnApple()) {
  4697. // Versioning is supported only for shared libraries and modules,
  4698. // and then only when the platform supports an soname flag.
  4699. version = nullptr;
  4700. soversion = nullptr;
  4701. }
  4702. if (version && !soversion) {
  4703. // The soversion must be set if the library version is set. Use
  4704. // the library version as the soversion.
  4705. soversion = version;
  4706. }
  4707. if (!version && soversion) {
  4708. // Use the soversion as the library version.
  4709. version = soversion;
  4710. }
  4711. // Get the components of the library name.
  4712. NameComponents const& components = this->GetFullNameInternalComponents(
  4713. config, cmStateEnums::RuntimeBinaryArtifact);
  4714. // The library name.
  4715. targetNames.Base = components.base;
  4716. targetNames.Output =
  4717. cmStrCat(components.prefix, targetNames.Base, components.suffix);
  4718. if (this->IsFrameworkOnApple()) {
  4719. targetNames.Real = components.prefix;
  4720. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  4721. targetNames.Real +=
  4722. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  4723. }
  4724. targetNames.Real += cmStrCat(targetNames.Base, components.suffix);
  4725. targetNames.SharedObject = targetNames.Real;
  4726. } else {
  4727. // The library's soname.
  4728. this->ComputeVersionedName(targetNames.SharedObject, components.prefix,
  4729. targetNames.Base, components.suffix,
  4730. targetNames.Output, soversion);
  4731. // The library's real name on disk.
  4732. this->ComputeVersionedName(targetNames.Real, components.prefix,
  4733. targetNames.Base, components.suffix,
  4734. targetNames.Output, version);
  4735. }
  4736. // The import library names.
  4737. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4738. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4739. NameComponents const& importComponents =
  4740. this->GetFullNameInternalComponents(config,
  4741. cmStateEnums::ImportLibraryArtifact);
  4742. targetNames.ImportOutput = cmStrCat(
  4743. importComponents.prefix, importComponents.base, importComponents.suffix);
  4744. if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
  4745. targetNames.ImportReal = components.prefix;
  4746. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  4747. targetNames.ImportReal +=
  4748. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  4749. }
  4750. targetNames.ImportReal +=
  4751. cmStrCat(importComponents.base, importComponents.suffix);
  4752. targetNames.ImportLibrary = targetNames.ImportOutput;
  4753. } else {
  4754. // The import library's soname.
  4755. this->ComputeVersionedName(
  4756. targetNames.ImportLibrary, importComponents.prefix,
  4757. importComponents.base, importComponents.suffix,
  4758. targetNames.ImportOutput, soversion);
  4759. // The import library's real name on disk.
  4760. this->ComputeVersionedName(
  4761. targetNames.ImportReal, importComponents.prefix, importComponents.base,
  4762. importComponents.suffix, targetNames.ImportOutput, version);
  4763. }
  4764. }
  4765. // The program database file name.
  4766. targetNames.PDB = this->GetPDBName(config);
  4767. return targetNames;
  4768. }
  4769. cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
  4770. const std::string& config) const
  4771. {
  4772. cmGeneratorTarget::Names targetNames;
  4773. // This should not be called for imported targets.
  4774. // TODO: Split cmTarget into a class hierarchy to get compile-time
  4775. // enforcement of the limited imported target API.
  4776. if (this->IsImported()) {
  4777. std::string msg = cmStrCat(
  4778. "GetExecutableNames called on imported target: ", this->GetName());
  4779. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  4780. }
  4781. // This versioning is supported only for executables and then only
  4782. // when the platform supports symbolic links.
  4783. #if defined(_WIN32) && !defined(__CYGWIN__)
  4784. cmValue version;
  4785. #else
  4786. // Check for executable version properties.
  4787. cmValue version = this->GetProperty("VERSION");
  4788. if (this->GetType() != cmStateEnums::EXECUTABLE ||
  4789. this->Makefile->IsOn("XCODE")) {
  4790. version = nullptr;
  4791. }
  4792. #endif
  4793. // Get the components of the executable name.
  4794. NameComponents const& components = this->GetFullNameInternalComponents(
  4795. config, cmStateEnums::RuntimeBinaryArtifact);
  4796. // The executable name.
  4797. targetNames.Base = components.base;
  4798. targetNames.Output =
  4799. components.prefix + targetNames.Base + components.suffix;
  4800. // The executable's real name on disk.
  4801. #if defined(__CYGWIN__)
  4802. targetNames.Real = components.prefix + targetNames.Base;
  4803. #else
  4804. targetNames.Real = targetNames.Output;
  4805. #endif
  4806. if (version) {
  4807. targetNames.Real += "-";
  4808. targetNames.Real += *version;
  4809. }
  4810. #if defined(__CYGWIN__)
  4811. targetNames.Real += components.suffix;
  4812. #endif
  4813. // The import library name.
  4814. targetNames.ImportLibrary =
  4815. this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
  4816. targetNames.ImportReal = targetNames.ImportLibrary;
  4817. targetNames.ImportOutput = targetNames.ImportLibrary;
  4818. // The program database file name.
  4819. targetNames.PDB = this->GetPDBName(config);
  4820. return targetNames;
  4821. }
  4822. std::string cmGeneratorTarget::GetFullNameInternal(
  4823. const std::string& config, cmStateEnums::ArtifactType artifact) const
  4824. {
  4825. NameComponents const& components =
  4826. this->GetFullNameInternalComponents(config, artifact);
  4827. return components.prefix + components.base + components.suffix;
  4828. }
  4829. std::string cmGeneratorTarget::ImportedGetLocation(
  4830. const std::string& config) const
  4831. {
  4832. assert(this->IsImported());
  4833. return this->Target->ImportedGetFullPath(
  4834. config, cmStateEnums::RuntimeBinaryArtifact);
  4835. }
  4836. std::string cmGeneratorTarget::GetFullNameImported(
  4837. const std::string& config, cmStateEnums::ArtifactType artifact) const
  4838. {
  4839. return cmSystemTools::GetFilenameName(
  4840. this->Target->ImportedGetFullPath(config, artifact));
  4841. }
  4842. cmGeneratorTarget::NameComponents const&
  4843. cmGeneratorTarget::GetFullNameInternalComponents(
  4844. std::string const& config, cmStateEnums::ArtifactType artifact) const
  4845. {
  4846. assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
  4847. artifact == cmStateEnums::ImportLibraryArtifact);
  4848. FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
  4849. ? RuntimeBinaryFullNameCache
  4850. : ImportLibraryFullNameCache;
  4851. auto search = cache.find(config);
  4852. if (search != cache.end()) {
  4853. return search->second;
  4854. }
  4855. // Use just the target name for non-main target types.
  4856. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4857. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4858. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  4859. this->GetType() != cmStateEnums::EXECUTABLE) {
  4860. NameComponents components;
  4861. components.base = this->GetName();
  4862. return cache.emplace(config, std::move(components)).first->second;
  4863. }
  4864. const bool isImportedLibraryArtifact =
  4865. (artifact == cmStateEnums::ImportLibraryArtifact);
  4866. // Return an empty name for the import library if this platform
  4867. // does not support import libraries.
  4868. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  4869. return cache.emplace(config, NameComponents()).first->second;
  4870. }
  4871. NameComponents parts;
  4872. std::string& outPrefix = parts.prefix;
  4873. std::string& outBase = parts.base;
  4874. std::string& outSuffix = parts.suffix;
  4875. // retrieve prefix and suffix
  4876. std::string ll = this->GetLinkerLanguage(config);
  4877. cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
  4878. cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
  4879. // The implib option is only allowed for shared libraries, module
  4880. // libraries, and executables.
  4881. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4882. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  4883. this->GetType() != cmStateEnums::EXECUTABLE) {
  4884. artifact = cmStateEnums::RuntimeBinaryArtifact;
  4885. }
  4886. // Compute the full name for main target types.
  4887. std::string configPostfix = this->GetFilePostfix(config);
  4888. // frameworks have directory prefix
  4889. std::string fw_prefix;
  4890. if (this->IsFrameworkOnApple()) {
  4891. fw_prefix =
  4892. cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
  4893. targetPrefix = cmValue(fw_prefix);
  4894. if (!isImportedLibraryArtifact) {
  4895. // no suffix
  4896. targetSuffix = nullptr;
  4897. }
  4898. }
  4899. if (this->IsCFBundleOnApple()) {
  4900. fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
  4901. targetPrefix = cmValue(fw_prefix);
  4902. targetSuffix = nullptr;
  4903. }
  4904. // Begin the final name with the prefix.
  4905. outPrefix = targetPrefix ? *targetPrefix : "";
  4906. // Append the target name or property-specified name.
  4907. outBase += this->GetOutputName(config, artifact);
  4908. // Append the per-configuration postfix.
  4909. // When using Xcode, the postfix should be part of the suffix rather than
  4910. // the base, because the suffix ends up being used in Xcode's
  4911. // EXECUTABLE_SUFFIX attribute.
  4912. if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
  4913. configPostfix += *targetSuffix;
  4914. targetSuffix = cmValue(configPostfix);
  4915. } else {
  4916. outBase += configPostfix;
  4917. }
  4918. // Name shared libraries with their version number on some platforms.
  4919. if (cmValue soversion = this->GetProperty("SOVERSION")) {
  4920. cmValue dllProp;
  4921. if (this->IsDLLPlatform()) {
  4922. dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
  4923. }
  4924. if (this->GetType() == cmStateEnums::SHARED_LIBRARY &&
  4925. !isImportedLibraryArtifact &&
  4926. (dllProp.IsOn() ||
  4927. (!dllProp.IsSet() &&
  4928. this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
  4929. outBase += "-";
  4930. outBase += *soversion;
  4931. }
  4932. }
  4933. // Append the suffix.
  4934. outSuffix = targetSuffix ? *targetSuffix : "";
  4935. return cache.emplace(config, std::move(parts)).first->second;
  4936. }
  4937. std::string cmGeneratorTarget::GetLinkerLanguage(
  4938. const std::string& config) const
  4939. {
  4940. return this->GetLinkClosure(config)->LinkerLanguage;
  4941. }
  4942. std::string cmGeneratorTarget::GetLinkerTool(const std::string& config) const
  4943. {
  4944. return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
  4945. }
  4946. std::string cmGeneratorTarget::GetLinkerTool(const std::string& lang,
  4947. const std::string& config) const
  4948. {
  4949. auto usingLinker =
  4950. cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
  4951. "LINKER_");
  4952. auto format = this->Makefile->GetDefinition(cmStrCat(usingLinker, "MODE"));
  4953. if (!format || format != "TOOL"_s) {
  4954. return this->Makefile->GetDefinition("CMAKE_LINKER");
  4955. }
  4956. auto linkerType = this->GetLinkerTypeProperty(lang, config);
  4957. if (linkerType.empty()) {
  4958. linkerType = "DEFAULT";
  4959. }
  4960. usingLinker = cmStrCat(usingLinker, linkerType);
  4961. auto linkerTool = this->Makefile->GetDefinition(usingLinker);
  4962. if (!linkerTool) {
  4963. if (this->GetGlobalGenerator()->IsVisualStudio() &&
  4964. linkerType == "DEFAULT"_s) {
  4965. return std::string{};
  4966. }
  4967. // fall-back to generic definition
  4968. linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
  4969. if (linkerType != "DEFAULT"_s) {
  4970. auto isCMakeLinkerType = [](const std::string& type) -> bool {
  4971. return std::all_of(type.cbegin(), type.cend(),
  4972. [](char c) { return std::isupper(c); });
  4973. };
  4974. if (isCMakeLinkerType(linkerType)) {
  4975. this->LocalGenerator->IssueMessage(
  4976. MessageType::FATAL_ERROR,
  4977. cmStrCat("LINKER_TYPE '", linkerType,
  4978. "' is unknown or not supported by this toolchain."));
  4979. } else {
  4980. this->LocalGenerator->IssueMessage(
  4981. MessageType::FATAL_ERROR,
  4982. cmStrCat("LINKER_TYPE '", linkerType,
  4983. "' is unknown. Did you forget to define the '", usingLinker,
  4984. "' variable?"));
  4985. }
  4986. }
  4987. }
  4988. return linkerTool;
  4989. }
  4990. bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
  4991. std::string const& config) const
  4992. {
  4993. // FIXME(#25486): Account for the LINKER_TYPE target property.
  4994. // Also factor out the hard-coded list below into a platform
  4995. // information table based on the linker id.
  4996. std::string ll = this->GetLinkerLanguage(config);
  4997. std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
  4998. cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
  4999. // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
  5000. // recursively by default. The Solaris linker has similar behavior.
  5001. return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
  5002. }
  5003. std::string cmGeneratorTarget::GetPDBOutputName(
  5004. const std::string& config) const
  5005. {
  5006. std::string base =
  5007. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact);
  5008. std::vector<std::string> props;
  5009. std::string configUpper = cmSystemTools::UpperCase(config);
  5010. if (!configUpper.empty()) {
  5011. // PDB_NAME_<CONFIG>
  5012. props.push_back("PDB_NAME_" + configUpper);
  5013. }
  5014. // PDB_NAME
  5015. props.emplace_back("PDB_NAME");
  5016. for (std::string const& p : props) {
  5017. if (cmValue outName = this->GetProperty(p)) {
  5018. base = *outName;
  5019. break;
  5020. }
  5021. }
  5022. return base;
  5023. }
  5024. std::string cmGeneratorTarget::GetPDBName(const std::string& config) const
  5025. {
  5026. NameComponents const& parts = this->GetFullNameInternalComponents(
  5027. config, cmStateEnums::RuntimeBinaryArtifact);
  5028. std::vector<std::string> props;
  5029. std::string configUpper = cmSystemTools::UpperCase(config);
  5030. if (!configUpper.empty()) {
  5031. // PDB_NAME_<CONFIG>
  5032. props.push_back("PDB_NAME_" + configUpper);
  5033. }
  5034. // PDB_NAME
  5035. props.emplace_back("PDB_NAME");
  5036. for (std::string const& p : props) {
  5037. if (cmValue outName = this->GetProperty(p)) {
  5038. return parts.prefix + *outName + ".pdb";
  5039. }
  5040. }
  5041. return parts.prefix + parts.base + ".pdb";
  5042. }
  5043. std::string cmGeneratorTarget::GetObjectDirectory(
  5044. std::string const& config) const
  5045. {
  5046. std::string obj_dir =
  5047. this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
  5048. #if defined(__APPLE__)
  5049. // Replace Xcode's placeholder for the object file directory since
  5050. // installation and export scripts need to know the real directory.
  5051. // Xcode has build-time settings (e.g. for sanitizers) that affect this,
  5052. // but we use the default here. Users that want to enable sanitizers
  5053. // will do so at the cost of object library installation and export.
  5054. cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
  5055. "Objects-normal");
  5056. #endif
  5057. return obj_dir;
  5058. }
  5059. void cmGeneratorTarget::GetTargetObjectNames(
  5060. std::string const& config, std::vector<std::string>& objects) const
  5061. {
  5062. std::vector<cmSourceFile const*> objectSources;
  5063. this->GetObjectSources(objectSources, config);
  5064. std::map<cmSourceFile const*, std::string> mapping;
  5065. for (cmSourceFile const* sf : objectSources) {
  5066. mapping[sf];
  5067. }
  5068. this->LocalGenerator->ComputeObjectFilenames(mapping, this);
  5069. for (cmSourceFile const* src : objectSources) {
  5070. // Find the object file name corresponding to this source file.
  5071. auto map_it = mapping.find(src);
  5072. // It must exist because we populated the mapping just above.
  5073. assert(!map_it->second.empty());
  5074. objects.push_back(map_it->second);
  5075. }
  5076. // We need to compute the relative path from the root of
  5077. // of the object directory to handle subdirectory paths
  5078. std::string rootObjectDir = this->GetObjectDirectory(config);
  5079. rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
  5080. auto ispcObjects = this->GetGeneratedISPCObjects(config);
  5081. for (std::string const& output : ispcObjects) {
  5082. auto relativePathFromObjectDir = output.substr(rootObjectDir.size());
  5083. objects.push_back(relativePathFromObjectDir);
  5084. }
  5085. }
  5086. bool cmGeneratorTarget::StrictTargetComparison::operator()(
  5087. cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
  5088. {
  5089. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  5090. if (nameResult == 0) {
  5091. return strcmp(
  5092. t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
  5093. t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
  5094. }
  5095. return nameResult < 0;
  5096. }
  5097. struct cmGeneratorTarget::SourceFileFlags
  5098. cmGeneratorTarget::GetTargetSourceFileFlags(const cmSourceFile* sf) const
  5099. {
  5100. struct SourceFileFlags flags;
  5101. this->ConstructSourceFileFlags();
  5102. auto si = this->SourceFlagsMap.find(sf);
  5103. if (si != this->SourceFlagsMap.end()) {
  5104. flags = si->second;
  5105. } else {
  5106. // Handle the MACOSX_PACKAGE_LOCATION property on source files that
  5107. // were not listed in one of the other lists.
  5108. if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
  5109. flags.MacFolder = location->c_str();
  5110. const bool stripResources =
  5111. this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
  5112. if (*location == "Resources") {
  5113. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  5114. if (stripResources) {
  5115. flags.MacFolder = "";
  5116. }
  5117. } else if (cmHasLiteralPrefix(*location, "Resources/")) {
  5118. flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
  5119. if (stripResources) {
  5120. flags.MacFolder += cmStrLen("Resources/");
  5121. }
  5122. } else {
  5123. flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
  5124. }
  5125. }
  5126. }
  5127. return flags;
  5128. }
  5129. void cmGeneratorTarget::ConstructSourceFileFlags() const
  5130. {
  5131. if (this->SourceFileFlagsConstructed) {
  5132. return;
  5133. }
  5134. this->SourceFileFlagsConstructed = true;
  5135. // Process public headers to mark the source files.
  5136. if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
  5137. cmList relFiles{ *files };
  5138. for (auto const& relFile : relFiles) {
  5139. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  5140. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  5141. flags.MacFolder = "Headers";
  5142. flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
  5143. }
  5144. }
  5145. }
  5146. // Process private headers after public headers so that they take
  5147. // precedence if a file is listed in both.
  5148. if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
  5149. cmList relFiles{ *files };
  5150. for (auto const& relFile : relFiles) {
  5151. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  5152. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  5153. flags.MacFolder = "PrivateHeaders";
  5154. flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
  5155. }
  5156. }
  5157. }
  5158. // Mark sources listed as resources.
  5159. if (cmValue files = this->GetProperty("RESOURCE")) {
  5160. cmList relFiles{ *files };
  5161. for (auto const& relFile : relFiles) {
  5162. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  5163. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  5164. flags.MacFolder = "";
  5165. if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
  5166. flags.MacFolder = "Resources";
  5167. }
  5168. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  5169. }
  5170. }
  5171. }
  5172. }
  5173. const cmGeneratorTarget::CompatibleInterfacesBase&
  5174. cmGeneratorTarget::GetCompatibleInterfaces(std::string const& config) const
  5175. {
  5176. cmGeneratorTarget::CompatibleInterfaces& compat =
  5177. this->CompatibleInterfacesMap[config];
  5178. if (!compat.Done) {
  5179. compat.Done = true;
  5180. compat.PropsBool.insert("POSITION_INDEPENDENT_CODE");
  5181. compat.PropsString.insert("AUTOUIC_OPTIONS");
  5182. std::vector<cmGeneratorTarget const*> const& deps =
  5183. this->GetLinkImplementationClosure(config);
  5184. for (cmGeneratorTarget const* li : deps) {
  5185. #define CM_READ_COMPATIBLE_INTERFACE(X, x) \
  5186. if (cmValue prop = li->GetProperty("COMPATIBLE_INTERFACE_" #X)) { \
  5187. cmList props(*prop); \
  5188. compat.Props##x.insert(props.begin(), props.end()); \
  5189. }
  5190. CM_READ_COMPATIBLE_INTERFACE(BOOL, Bool)
  5191. CM_READ_COMPATIBLE_INTERFACE(STRING, String)
  5192. CM_READ_COMPATIBLE_INTERFACE(NUMBER_MIN, NumberMin)
  5193. CM_READ_COMPATIBLE_INTERFACE(NUMBER_MAX, NumberMax)
  5194. #undef CM_READ_COMPATIBLE_INTERFACE
  5195. }
  5196. }
  5197. return compat;
  5198. }
  5199. bool cmGeneratorTarget::IsLinkInterfaceDependentBoolProperty(
  5200. const std::string& p, const std::string& config) const
  5201. {
  5202. if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  5203. this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  5204. return false;
  5205. }
  5206. return this->GetCompatibleInterfaces(config).PropsBool.count(p) > 0;
  5207. }
  5208. bool cmGeneratorTarget::IsLinkInterfaceDependentStringProperty(
  5209. const std::string& p, const std::string& config) const
  5210. {
  5211. if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  5212. this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  5213. return false;
  5214. }
  5215. return this->GetCompatibleInterfaces(config).PropsString.count(p) > 0;
  5216. }
  5217. bool cmGeneratorTarget::IsLinkInterfaceDependentNumberMinProperty(
  5218. const std::string& p, const std::string& config) const
  5219. {
  5220. if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  5221. this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  5222. return false;
  5223. }
  5224. return this->GetCompatibleInterfaces(config).PropsNumberMin.count(p) > 0;
  5225. }
  5226. bool cmGeneratorTarget::IsLinkInterfaceDependentNumberMaxProperty(
  5227. const std::string& p, const std::string& config) const
  5228. {
  5229. if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  5230. this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  5231. return false;
  5232. }
  5233. return this->GetCompatibleInterfaces(config).PropsNumberMax.count(p) > 0;
  5234. }
  5235. enum CompatibleType
  5236. {
  5237. BoolType,
  5238. StringType,
  5239. NumberMinType,
  5240. NumberMaxType
  5241. };
  5242. template <typename PropertyType>
  5243. PropertyType getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
  5244. const std::string& prop,
  5245. const std::string& config,
  5246. CompatibleType, PropertyType*);
  5247. template <>
  5248. bool getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
  5249. const std::string& prop,
  5250. const std::string& config,
  5251. CompatibleType /*unused*/,
  5252. bool* /*unused*/)
  5253. {
  5254. return tgt->GetLinkInterfaceDependentBoolProperty(prop, config);
  5255. }
  5256. template <>
  5257. const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
  5258. const std::string& prop,
  5259. const std::string& config,
  5260. CompatibleType t,
  5261. const char** /*unused*/)
  5262. {
  5263. switch (t) {
  5264. case BoolType:
  5265. assert(false &&
  5266. "String compatibility check function called for boolean");
  5267. return nullptr;
  5268. case StringType:
  5269. return tgt->GetLinkInterfaceDependentStringProperty(prop, config);
  5270. case NumberMinType:
  5271. return tgt->GetLinkInterfaceDependentNumberMinProperty(prop, config);
  5272. case NumberMaxType:
  5273. return tgt->GetLinkInterfaceDependentNumberMaxProperty(prop, config);
  5274. }
  5275. assert(false && "Unreachable!");
  5276. return nullptr;
  5277. }
  5278. template <typename PropertyType>
  5279. void checkPropertyConsistency(cmGeneratorTarget const* depender,
  5280. cmGeneratorTarget const* dependee,
  5281. const std::string& propName,
  5282. std::set<std::string>& emitted,
  5283. const std::string& config, CompatibleType t,
  5284. PropertyType* /*unused*/)
  5285. {
  5286. cmValue prop = dependee->GetProperty(propName);
  5287. if (!prop) {
  5288. return;
  5289. }
  5290. cmList props{ *prop };
  5291. std::string pdir =
  5292. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Help/prop_tgt/");
  5293. for (std::string const& p : props) {
  5294. std::string pname = cmSystemTools::HelpFileName(p);
  5295. std::string pfile = pdir + pname + ".rst";
  5296. if (cmSystemTools::FileExists(pfile, true)) {
  5297. std::ostringstream e;
  5298. e << "Target \"" << dependee->GetName() << "\" has property \"" << p
  5299. << "\" listed in its " << propName
  5300. << " property. "
  5301. "This is not allowed. Only user-defined properties may appear "
  5302. "listed in the "
  5303. << propName << " property.";
  5304. depender->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
  5305. e.str());
  5306. return;
  5307. }
  5308. if (emitted.insert(p).second) {
  5309. getLinkInterfaceDependentProperty<PropertyType>(depender, p, config, t,
  5310. nullptr);
  5311. if (cmSystemTools::GetErrorOccurredFlag()) {
  5312. return;
  5313. }
  5314. }
  5315. }
  5316. }
  5317. namespace {
  5318. std::string intersect(const std::set<std::string>& s1,
  5319. const std::set<std::string>& s2)
  5320. {
  5321. std::set<std::string> intersect;
  5322. std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
  5323. std::inserter(intersect, intersect.begin()));
  5324. if (!intersect.empty()) {
  5325. return *intersect.begin();
  5326. }
  5327. return "";
  5328. }
  5329. std::string intersect(const std::set<std::string>& s1,
  5330. const std::set<std::string>& s2,
  5331. const std::set<std::string>& s3)
  5332. {
  5333. std::string result;
  5334. result = intersect(s1, s2);
  5335. if (!result.empty()) {
  5336. return result;
  5337. }
  5338. result = intersect(s1, s3);
  5339. if (!result.empty()) {
  5340. return result;
  5341. }
  5342. return intersect(s2, s3);
  5343. }
  5344. std::string intersect(const std::set<std::string>& s1,
  5345. const std::set<std::string>& s2,
  5346. const std::set<std::string>& s3,
  5347. const std::set<std::string>& s4)
  5348. {
  5349. std::string result;
  5350. result = intersect(s1, s2);
  5351. if (!result.empty()) {
  5352. return result;
  5353. }
  5354. result = intersect(s1, s3);
  5355. if (!result.empty()) {
  5356. return result;
  5357. }
  5358. result = intersect(s1, s4);
  5359. if (!result.empty()) {
  5360. return result;
  5361. }
  5362. return intersect(s2, s3, s4);
  5363. }
  5364. }
  5365. void cmGeneratorTarget::CheckPropertyCompatibility(
  5366. cmComputeLinkInformation& info, const std::string& config) const
  5367. {
  5368. const cmComputeLinkInformation::ItemVector& deps = info.GetItems();
  5369. std::set<std::string> emittedBools;
  5370. static const std::string strBool = "COMPATIBLE_INTERFACE_BOOL";
  5371. std::set<std::string> emittedStrings;
  5372. static const std::string strString = "COMPATIBLE_INTERFACE_STRING";
  5373. std::set<std::string> emittedMinNumbers;
  5374. static const std::string strNumMin = "COMPATIBLE_INTERFACE_NUMBER_MIN";
  5375. std::set<std::string> emittedMaxNumbers;
  5376. static const std::string strNumMax = "COMPATIBLE_INTERFACE_NUMBER_MAX";
  5377. for (auto const& dep : deps) {
  5378. if (!dep.Target || dep.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  5379. continue;
  5380. }
  5381. checkPropertyConsistency<bool>(this, dep.Target, strBool, emittedBools,
  5382. config, BoolType, nullptr);
  5383. if (cmSystemTools::GetErrorOccurredFlag()) {
  5384. return;
  5385. }
  5386. checkPropertyConsistency<const char*>(this, dep.Target, strString,
  5387. emittedStrings, config, StringType,
  5388. nullptr);
  5389. if (cmSystemTools::GetErrorOccurredFlag()) {
  5390. return;
  5391. }
  5392. checkPropertyConsistency<const char*>(this, dep.Target, strNumMin,
  5393. emittedMinNumbers, config,
  5394. NumberMinType, nullptr);
  5395. if (cmSystemTools::GetErrorOccurredFlag()) {
  5396. return;
  5397. }
  5398. checkPropertyConsistency<const char*>(this, dep.Target, strNumMax,
  5399. emittedMaxNumbers, config,
  5400. NumberMaxType, nullptr);
  5401. if (cmSystemTools::GetErrorOccurredFlag()) {
  5402. return;
  5403. }
  5404. }
  5405. std::string prop = intersect(emittedBools, emittedStrings, emittedMinNumbers,
  5406. emittedMaxNumbers);
  5407. if (!prop.empty()) {
  5408. // Use a sorted std::vector to keep the error message sorted.
  5409. std::vector<std::string> props;
  5410. auto i = emittedBools.find(prop);
  5411. if (i != emittedBools.end()) {
  5412. props.push_back(strBool);
  5413. }
  5414. i = emittedStrings.find(prop);
  5415. if (i != emittedStrings.end()) {
  5416. props.push_back(strString);
  5417. }
  5418. i = emittedMinNumbers.find(prop);
  5419. if (i != emittedMinNumbers.end()) {
  5420. props.push_back(strNumMin);
  5421. }
  5422. i = emittedMaxNumbers.find(prop);
  5423. if (i != emittedMaxNumbers.end()) {
  5424. props.push_back(strNumMax);
  5425. }
  5426. std::sort(props.begin(), props.end());
  5427. std::string propsString = cmStrCat(
  5428. cmJoin(cmMakeRange(props).retreat(1), ", "), " and the ", props.back());
  5429. std::ostringstream e;
  5430. e << "Property \"" << prop << "\" appears in both the " << propsString
  5431. << " property in the dependencies of target \"" << this->GetName()
  5432. << "\". This is not allowed. A property may only require "
  5433. "compatibility "
  5434. "in a boolean interpretation, a numeric minimum, a numeric maximum "
  5435. "or a "
  5436. "string interpretation, but not a mixture.";
  5437. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  5438. }
  5439. }
  5440. template <typename PropertyType>
  5441. std::string valueAsString(PropertyType);
  5442. template <>
  5443. std::string valueAsString<bool>(bool value)
  5444. {
  5445. return value ? "TRUE" : "FALSE";
  5446. }
  5447. template <>
  5448. std::string valueAsString<const char*>(const char* value)
  5449. {
  5450. return value ? value : "(unset)";
  5451. }
  5452. template <>
  5453. std::string valueAsString<std::string>(std::string value)
  5454. {
  5455. return value;
  5456. }
  5457. template <>
  5458. std::string valueAsString<cmValue>(cmValue value)
  5459. {
  5460. return value ? *value : std::string("(unset)");
  5461. }
  5462. template <>
  5463. std::string valueAsString<std::nullptr_t>(std::nullptr_t /*unused*/)
  5464. {
  5465. return "(unset)";
  5466. }
  5467. static std::string compatibilityType(CompatibleType t)
  5468. {
  5469. switch (t) {
  5470. case BoolType:
  5471. return "Boolean compatibility";
  5472. case StringType:
  5473. return "String compatibility";
  5474. case NumberMaxType:
  5475. return "Numeric maximum compatibility";
  5476. case NumberMinType:
  5477. return "Numeric minimum compatibility";
  5478. }
  5479. assert(false && "Unreachable!");
  5480. return "";
  5481. }
  5482. static std::string compatibilityAgree(CompatibleType t, bool dominant)
  5483. {
  5484. switch (t) {
  5485. case BoolType:
  5486. case StringType:
  5487. return dominant ? "(Disagree)\n" : "(Agree)\n";
  5488. case NumberMaxType:
  5489. case NumberMinType:
  5490. return dominant ? "(Dominant)\n" : "(Ignored)\n";
  5491. }
  5492. assert(false && "Unreachable!");
  5493. return "";
  5494. }
  5495. template <typename PropertyType>
  5496. PropertyType getTypedProperty(
  5497. cmGeneratorTarget const* tgt, const std::string& prop,
  5498. cmGeneratorExpressionInterpreter* genexInterpreter = nullptr);
  5499. template <>
  5500. bool getTypedProperty<bool>(cmGeneratorTarget const* tgt,
  5501. const std::string& prop,
  5502. cmGeneratorExpressionInterpreter* genexInterpreter)
  5503. {
  5504. if (genexInterpreter == nullptr) {
  5505. return tgt->GetPropertyAsBool(prop);
  5506. }
  5507. cmValue value = tgt->GetProperty(prop);
  5508. return cmIsOn(genexInterpreter->Evaluate(value ? *value : "", prop));
  5509. }
  5510. template <>
  5511. const char* getTypedProperty<const char*>(
  5512. cmGeneratorTarget const* tgt, const std::string& prop,
  5513. cmGeneratorExpressionInterpreter* genexInterpreter)
  5514. {
  5515. cmValue value = tgt->GetProperty(prop);
  5516. if (genexInterpreter == nullptr) {
  5517. return value.GetCStr();
  5518. }
  5519. return genexInterpreter->Evaluate(value ? *value : "", prop).c_str();
  5520. }
  5521. template <>
  5522. std::string getTypedProperty<std::string>(
  5523. cmGeneratorTarget const* tgt, const std::string& prop,
  5524. cmGeneratorExpressionInterpreter* genexInterpreter)
  5525. {
  5526. cmValue value = tgt->GetProperty(prop);
  5527. if (genexInterpreter == nullptr) {
  5528. return valueAsString(value);
  5529. }
  5530. return genexInterpreter->Evaluate(value ? *value : "", prop);
  5531. }
  5532. template <typename PropertyType>
  5533. PropertyType impliedValue(PropertyType);
  5534. template <>
  5535. bool impliedValue<bool>(bool /*unused*/)
  5536. {
  5537. return false;
  5538. }
  5539. template <>
  5540. const char* impliedValue<const char*>(const char* /*unused*/)
  5541. {
  5542. return "";
  5543. }
  5544. template <>
  5545. std::string impliedValue<std::string>(std::string /*unused*/) // NOLINT(*)
  5546. {
  5547. return std::string();
  5548. }
  5549. template <typename PropertyType>
  5550. std::pair<bool, PropertyType> consistentProperty(PropertyType lhs,
  5551. PropertyType rhs,
  5552. CompatibleType t);
  5553. template <>
  5554. std::pair<bool, bool> consistentProperty(bool lhs, bool rhs,
  5555. CompatibleType /*unused*/)
  5556. {
  5557. return { lhs == rhs, lhs };
  5558. }
  5559. static std::pair<bool, const char*> consistentStringProperty(const char* lhs,
  5560. const char* rhs)
  5561. {
  5562. const bool b = strcmp(lhs, rhs) == 0;
  5563. return { b, b ? lhs : nullptr };
  5564. }
  5565. static std::pair<bool, std::string> consistentStringProperty(
  5566. const std::string& lhs, const std::string& rhs)
  5567. {
  5568. const bool b = lhs == rhs;
  5569. return { b, b ? lhs : valueAsString(nullptr) };
  5570. }
  5571. static std::pair<bool, const char*> consistentNumberProperty(const char* lhs,
  5572. const char* rhs,
  5573. CompatibleType t)
  5574. {
  5575. char* pEnd;
  5576. long lnum = strtol(lhs, &pEnd, 0);
  5577. if (pEnd == lhs || *pEnd != '\0' || errno == ERANGE) {
  5578. return { false, nullptr };
  5579. }
  5580. long rnum = strtol(rhs, &pEnd, 0);
  5581. if (pEnd == rhs || *pEnd != '\0' || errno == ERANGE) {
  5582. return { false, nullptr };
  5583. }
  5584. if (t == NumberMaxType) {
  5585. return { true, std::max(lnum, rnum) == lnum ? lhs : rhs };
  5586. }
  5587. return { true, std::min(lnum, rnum) == lnum ? lhs : rhs };
  5588. }
  5589. template <>
  5590. std::pair<bool, const char*> consistentProperty(const char* lhs,
  5591. const char* rhs,
  5592. CompatibleType t)
  5593. {
  5594. if (!lhs && !rhs) {
  5595. return { true, lhs };
  5596. }
  5597. if (!lhs) {
  5598. return { true, rhs };
  5599. }
  5600. if (!rhs) {
  5601. return { true, lhs };
  5602. }
  5603. switch (t) {
  5604. case BoolType: {
  5605. bool same = cmIsOn(lhs) == cmIsOn(rhs);
  5606. return { same, same ? lhs : nullptr };
  5607. }
  5608. case StringType:
  5609. return consistentStringProperty(lhs, rhs);
  5610. case NumberMinType:
  5611. case NumberMaxType:
  5612. return consistentNumberProperty(lhs, rhs, t);
  5613. }
  5614. assert(false && "Unreachable!");
  5615. return { false, nullptr };
  5616. }
  5617. static std::pair<bool, std::string> consistentProperty(const std::string& lhs,
  5618. const std::string& rhs,
  5619. CompatibleType t)
  5620. {
  5621. const std::string null_ptr = valueAsString(nullptr);
  5622. if (lhs == null_ptr && rhs == null_ptr) {
  5623. return { true, lhs };
  5624. }
  5625. if (lhs == null_ptr) {
  5626. return { true, rhs };
  5627. }
  5628. if (rhs == null_ptr) {
  5629. return { true, lhs };
  5630. }
  5631. switch (t) {
  5632. case BoolType: {
  5633. bool same = cmIsOn(lhs) == cmIsOn(rhs);
  5634. return { same, same ? lhs : null_ptr };
  5635. }
  5636. case StringType:
  5637. return consistentStringProperty(lhs, rhs);
  5638. case NumberMinType:
  5639. case NumberMaxType: {
  5640. auto value = consistentNumberProperty(lhs.c_str(), rhs.c_str(), t);
  5641. return { value.first,
  5642. value.first ? std::string(value.second) : null_ptr };
  5643. }
  5644. }
  5645. assert(false && "Unreachable!");
  5646. return { false, null_ptr };
  5647. }
  5648. template <typename PropertyType>
  5649. PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt,
  5650. const std::string& p,
  5651. const std::string& config,
  5652. const char* defaultValue,
  5653. CompatibleType t,
  5654. PropertyType* /*unused*/)
  5655. {
  5656. PropertyType propContent = getTypedProperty<PropertyType>(tgt, p);
  5657. std::vector<std::string> headPropKeys = tgt->GetPropertyKeys();
  5658. const bool explicitlySet = cm::contains(headPropKeys, p);
  5659. const bool impliedByUse = tgt->IsNullImpliedByLinkLibraries(p);
  5660. assert((impliedByUse ^ explicitlySet) || (!impliedByUse && !explicitlySet));
  5661. std::vector<cmGeneratorTarget const*> const& deps =
  5662. tgt->GetLinkImplementationClosure(config);
  5663. if (deps.empty()) {
  5664. return propContent;
  5665. }
  5666. bool propInitialized = explicitlySet;
  5667. std::string report = cmStrCat(" * Target \"", tgt->GetName());
  5668. if (explicitlySet) {
  5669. report += "\" has property content \"";
  5670. report += valueAsString<PropertyType>(propContent);
  5671. report += "\"\n";
  5672. } else if (impliedByUse) {
  5673. report += "\" property is implied by use.\n";
  5674. } else {
  5675. report += "\" property not set.\n";
  5676. }
  5677. std::string interfaceProperty = "INTERFACE_" + p;
  5678. std::unique_ptr<cmGeneratorExpressionInterpreter> genexInterpreter;
  5679. if (p == "POSITION_INDEPENDENT_CODE") {
  5680. // Corresponds to EvaluatingPICExpression.
  5681. genexInterpreter = cm::make_unique<cmGeneratorExpressionInterpreter>(
  5682. tgt->GetLocalGenerator(), config, tgt);
  5683. }
  5684. for (cmGeneratorTarget const* theTarget : deps) {
  5685. // An error should be reported if one dependency
  5686. // has INTERFACE_POSITION_INDEPENDENT_CODE ON and the other
  5687. // has INTERFACE_POSITION_INDEPENDENT_CODE OFF, or if the
  5688. // target itself has a POSITION_INDEPENDENT_CODE which disagrees
  5689. // with a dependency.
  5690. std::vector<std::string> propKeys = theTarget->GetPropertyKeys();
  5691. const bool ifaceIsSet = cm::contains(propKeys, interfaceProperty);
  5692. PropertyType ifacePropContent = getTypedProperty<PropertyType>(
  5693. theTarget, interfaceProperty, genexInterpreter.get());
  5694. std::string reportEntry;
  5695. if (ifaceIsSet) {
  5696. reportEntry += " * Target \"";
  5697. reportEntry += theTarget->GetName();
  5698. reportEntry += "\" property value \"";
  5699. reportEntry += valueAsString<PropertyType>(ifacePropContent);
  5700. reportEntry += "\" ";
  5701. }
  5702. if (explicitlySet) {
  5703. if (ifaceIsSet) {
  5704. std::pair<bool, PropertyType> consistent =
  5705. consistentProperty(propContent, ifacePropContent, t);
  5706. report += reportEntry;
  5707. report += compatibilityAgree(t, propContent != consistent.second);
  5708. if (!consistent.first) {
  5709. std::ostringstream e;
  5710. e << "Property " << p << " on target \"" << tgt->GetName()
  5711. << "\" does\nnot match the "
  5712. "INTERFACE_"
  5713. << p
  5714. << " property requirement\nof "
  5715. "dependency \""
  5716. << theTarget->GetName() << "\".\n";
  5717. cmSystemTools::Error(e.str());
  5718. break;
  5719. }
  5720. propContent = consistent.second;
  5721. continue;
  5722. }
  5723. // Explicitly set on target and not set in iface. Can't disagree.
  5724. continue;
  5725. }
  5726. if (impliedByUse) {
  5727. propContent = impliedValue<PropertyType>(propContent);
  5728. if (ifaceIsSet) {
  5729. std::pair<bool, PropertyType> consistent =
  5730. consistentProperty(propContent, ifacePropContent, t);
  5731. report += reportEntry;
  5732. report += compatibilityAgree(t, propContent != consistent.second);
  5733. if (!consistent.first) {
  5734. std::ostringstream e;
  5735. e << "Property " << p << " on target \"" << tgt->GetName()
  5736. << "\" is\nimplied to be " << defaultValue
  5737. << " because it was used to determine the link libraries\n"
  5738. "already. The INTERFACE_"
  5739. << p << " property on\ndependency \"" << theTarget->GetName()
  5740. << "\" is in conflict.\n";
  5741. cmSystemTools::Error(e.str());
  5742. break;
  5743. }
  5744. propContent = consistent.second;
  5745. continue;
  5746. }
  5747. // Implicitly set on target and not set in iface. Can't disagree.
  5748. continue;
  5749. }
  5750. if (ifaceIsSet) {
  5751. if (propInitialized) {
  5752. std::pair<bool, PropertyType> consistent =
  5753. consistentProperty(propContent, ifacePropContent, t);
  5754. report += reportEntry;
  5755. report += compatibilityAgree(t, propContent != consistent.second);
  5756. if (!consistent.first) {
  5757. std::ostringstream e;
  5758. e << "The INTERFACE_" << p << " property of \""
  5759. << theTarget->GetName() << "\" does\nnot agree with the value of "
  5760. << p << " already determined\nfor \"" << tgt->GetName() << "\".\n";
  5761. cmSystemTools::Error(e.str());
  5762. break;
  5763. }
  5764. propContent = consistent.second;
  5765. continue;
  5766. }
  5767. report += reportEntry + "(Interface set)\n";
  5768. propContent = ifacePropContent;
  5769. propInitialized = true;
  5770. } else {
  5771. // Not set. Nothing to agree on.
  5772. continue;
  5773. }
  5774. }
  5775. tgt->ReportPropertyOrigin(p, valueAsString<PropertyType>(propContent),
  5776. report, compatibilityType(t));
  5777. return propContent;
  5778. }
  5779. bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
  5780. {
  5781. bool previous = this->DeviceLink;
  5782. this->DeviceLink = deviceLink;
  5783. return previous;
  5784. }
  5785. bool cmGeneratorTarget::GetLinkInterfaceDependentBoolProperty(
  5786. const std::string& p, const std::string& config) const
  5787. {
  5788. return checkInterfacePropertyCompatibility<bool>(this, p, config, "FALSE",
  5789. BoolType, nullptr);
  5790. }
  5791. std::string cmGeneratorTarget::GetLinkInterfaceDependentStringAsBoolProperty(
  5792. const std::string& p, const std::string& config) const
  5793. {
  5794. return checkInterfacePropertyCompatibility<std::string>(
  5795. this, p, config, "FALSE", BoolType, nullptr);
  5796. }
  5797. const char* cmGeneratorTarget::GetLinkInterfaceDependentStringProperty(
  5798. const std::string& p, const std::string& config) const
  5799. {
  5800. return checkInterfacePropertyCompatibility<const char*>(
  5801. this, p, config, "empty", StringType, nullptr);
  5802. }
  5803. const char* cmGeneratorTarget::GetLinkInterfaceDependentNumberMinProperty(
  5804. const std::string& p, const std::string& config) const
  5805. {
  5806. return checkInterfacePropertyCompatibility<const char*>(
  5807. this, p, config, "empty", NumberMinType, nullptr);
  5808. }
  5809. const char* cmGeneratorTarget::GetLinkInterfaceDependentNumberMaxProperty(
  5810. const std::string& p, const std::string& config) const
  5811. {
  5812. return checkInterfacePropertyCompatibility<const char*>(
  5813. this, p, config, "empty", NumberMaxType, nullptr);
  5814. }
  5815. cmComputeLinkInformation* cmGeneratorTarget::GetLinkInformation(
  5816. const std::string& config) const
  5817. {
  5818. // Lookup any existing information for this configuration.
  5819. std::string key(cmSystemTools::UpperCase(config));
  5820. auto i = this->LinkInformation.find(key);
  5821. if (i == this->LinkInformation.end()) {
  5822. // Compute information for this configuration.
  5823. auto info = cm::make_unique<cmComputeLinkInformation>(this, config);
  5824. if (info && !info->Compute()) {
  5825. info.reset();
  5826. }
  5827. // Store the information for this configuration.
  5828. i = this->LinkInformation.emplace(key, std::move(info)).first;
  5829. if (i->second) {
  5830. this->CheckPropertyCompatibility(*i->second, config);
  5831. }
  5832. }
  5833. return i->second.get();
  5834. }
  5835. void cmGeneratorTarget::CheckLinkLibraries() const
  5836. {
  5837. bool linkLibrariesOnlyTargets =
  5838. this->GetPropertyAsBool("LINK_LIBRARIES_ONLY_TARGETS");
  5839. // Evaluate the link interface of this target if needed for extra checks.
  5840. if (linkLibrariesOnlyTargets) {
  5841. std::vector<std::string> const& configs =
  5842. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  5843. for (std::string const& config : configs) {
  5844. this->GetLinkInterfaceLibraries(config, this, LinkInterfaceFor::Link);
  5845. }
  5846. }
  5847. // Check link the implementation for each generated configuration.
  5848. for (auto const& hmp : this->LinkImplMap) {
  5849. HeadToLinkImplementationMap const& hm = hmp.second;
  5850. // There could be several entries used when computing the pre-CMP0022
  5851. // default link interface. Check only the entry for our own link impl.
  5852. auto const hmi = hm.find(this);
  5853. if (hmi == hm.end() || !hmi->second.LibrariesDone) {
  5854. continue;
  5855. }
  5856. for (cmLinkImplItem const& item : hmi->second.Libraries) {
  5857. if (!this->VerifyLinkItemColons(LinkItemRole::Implementation, item)) {
  5858. return;
  5859. }
  5860. if (linkLibrariesOnlyTargets &&
  5861. !this->VerifyLinkItemIsTarget(LinkItemRole::Implementation, item)) {
  5862. return;
  5863. }
  5864. }
  5865. }
  5866. // Check link the interface for each generated combination of
  5867. // configuration and consuming head target. We should not need to
  5868. // consider LinkInterfaceUsageRequirementsOnlyMap because its entries
  5869. // should be a subset of LinkInterfaceMap (with LINK_ONLY left out).
  5870. for (auto const& hmp : this->LinkInterfaceMap) {
  5871. for (auto const& hmi : hmp.second) {
  5872. if (!hmi.second.LibrariesDone) {
  5873. continue;
  5874. }
  5875. for (cmLinkItem const& item : hmi.second.Libraries) {
  5876. if (!this->VerifyLinkItemColons(LinkItemRole::Interface, item)) {
  5877. return;
  5878. }
  5879. if (linkLibrariesOnlyTargets &&
  5880. !this->VerifyLinkItemIsTarget(LinkItemRole::Interface, item)) {
  5881. return;
  5882. }
  5883. }
  5884. }
  5885. }
  5886. }
  5887. namespace {
  5888. cm::string_view missingTargetPossibleReasons =
  5889. "Possible reasons include:\n"
  5890. " * There is a typo in the target name.\n"
  5891. " * A find_package call is missing for an IMPORTED target.\n"
  5892. " * An ALIAS target is missing.\n"_s;
  5893. }
  5894. bool cmGeneratorTarget::VerifyLinkItemColons(LinkItemRole role,
  5895. cmLinkItem const& item) const
  5896. {
  5897. if (item.Target || cmHasPrefix(item.AsStr(), "<LINK_GROUP:"_s) ||
  5898. item.AsStr().find("::") == std::string::npos) {
  5899. return true;
  5900. }
  5901. MessageType messageType = MessageType::FATAL_ERROR;
  5902. std::string e;
  5903. switch (this->GetLocalGenerator()->GetPolicyStatus(cmPolicies::CMP0028)) {
  5904. case cmPolicies::WARN: {
  5905. e = cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0028), "\n");
  5906. messageType = MessageType::AUTHOR_WARNING;
  5907. } break;
  5908. case cmPolicies::OLD:
  5909. return true;
  5910. case cmPolicies::REQUIRED_IF_USED:
  5911. case cmPolicies::REQUIRED_ALWAYS:
  5912. case cmPolicies::NEW:
  5913. // Issue the fatal message.
  5914. break;
  5915. }
  5916. if (role == LinkItemRole::Implementation) {
  5917. e = cmStrCat(e, "Target \"", this->GetName(), "\" links to");
  5918. } else {
  5919. e = cmStrCat(e, "The link interface of target \"", this->GetName(),
  5920. "\" contains");
  5921. }
  5922. e =
  5923. cmStrCat(e, ":\n ", item.AsStr(), "\n", "but the target was not found. ",
  5924. missingTargetPossibleReasons);
  5925. cmListFileBacktrace backtrace = item.Backtrace;
  5926. if (backtrace.Empty()) {
  5927. backtrace = this->GetBacktrace();
  5928. }
  5929. this->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(messageType, e,
  5930. backtrace);
  5931. return false;
  5932. }
  5933. bool cmGeneratorTarget::VerifyLinkItemIsTarget(LinkItemRole role,
  5934. cmLinkItem const& item) const
  5935. {
  5936. if (item.Target) {
  5937. return true;
  5938. }
  5939. std::string const& str = item.AsStr();
  5940. if (!str.empty() &&
  5941. (str[0] == '-' || str[0] == '$' || str[0] == '`' ||
  5942. str.find_first_of("/\\") != std::string::npos ||
  5943. cmHasPrefix(str, "<LINK_LIBRARY:"_s) ||
  5944. cmHasPrefix(str, "<LINK_GROUP:"_s))) {
  5945. return true;
  5946. }
  5947. std::string e = cmStrCat("Target \"", this->GetName(),
  5948. "\" has LINK_LIBRARIES_ONLY_TARGETS enabled, but ",
  5949. role == LinkItemRole::Implementation
  5950. ? "it links to"
  5951. : "its link interface contains",
  5952. ":\n ", item.AsStr(), "\nwhich is not a target. ",
  5953. missingTargetPossibleReasons);
  5954. cmListFileBacktrace backtrace = item.Backtrace;
  5955. if (backtrace.Empty()) {
  5956. backtrace = this->GetBacktrace();
  5957. }
  5958. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  5959. MessageType::FATAL_ERROR, e, backtrace);
  5960. return false;
  5961. }
  5962. void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
  5963. {
  5964. int patch;
  5965. this->GetTargetVersion("VERSION", major, minor, patch);
  5966. }
  5967. void cmGeneratorTarget::GetTargetVersionFallback(
  5968. const std::string& property, const std::string& fallback_property,
  5969. int& major, int& minor, int& patch) const
  5970. {
  5971. if (this->GetProperty(property)) {
  5972. this->GetTargetVersion(property, major, minor, patch);
  5973. } else {
  5974. this->GetTargetVersion(fallback_property, major, minor, patch);
  5975. }
  5976. }
  5977. void cmGeneratorTarget::GetTargetVersion(const std::string& property,
  5978. int& major, int& minor,
  5979. int& patch) const
  5980. {
  5981. // Set the default values.
  5982. major = 0;
  5983. minor = 0;
  5984. patch = 0;
  5985. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  5986. if (cmValue version = this->GetProperty(property)) {
  5987. // Try to parse the version number and store the results that were
  5988. // successfully parsed.
  5989. int parsed_major;
  5990. int parsed_minor;
  5991. int parsed_patch;
  5992. switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
  5993. &parsed_patch)) {
  5994. case 3:
  5995. patch = parsed_patch;
  5996. CM_FALLTHROUGH;
  5997. case 2:
  5998. minor = parsed_minor;
  5999. CM_FALLTHROUGH;
  6000. case 1:
  6001. major = parsed_major;
  6002. CM_FALLTHROUGH;
  6003. default:
  6004. break;
  6005. }
  6006. }
  6007. }
  6008. std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
  6009. std::string const& lang, std::string const& config) const
  6010. {
  6011. // This is activated by the presence of a default selection whether or
  6012. // not it is overridden by a property.
  6013. cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
  6014. cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
  6015. if (!cmNonempty(runtimeLibraryDefault)) {
  6016. return std::string();
  6017. }
  6018. cmValue runtimeLibraryValue =
  6019. this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
  6020. if (!runtimeLibraryValue) {
  6021. runtimeLibraryValue = runtimeLibraryDefault;
  6022. }
  6023. return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
  6024. *runtimeLibraryValue, this->LocalGenerator, config, this));
  6025. }
  6026. std::string cmGeneratorTarget::GetFortranModuleDirectory(
  6027. std::string const& working_dir) const
  6028. {
  6029. if (!this->FortranModuleDirectoryCreated) {
  6030. this->FortranModuleDirectory =
  6031. this->CreateFortranModuleDirectory(working_dir);
  6032. this->FortranModuleDirectoryCreated = true;
  6033. }
  6034. return this->FortranModuleDirectory;
  6035. }
  6036. bool cmGeneratorTarget::IsFortranBuildingInstrinsicModules() const
  6037. {
  6038. if (cmValue prop =
  6039. this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
  6040. return prop.IsOn();
  6041. }
  6042. return false;
  6043. }
  6044. std::string cmGeneratorTarget::CreateFortranModuleDirectory(
  6045. std::string const& working_dir) const
  6046. {
  6047. std::string mod_dir;
  6048. std::string target_mod_dir;
  6049. if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
  6050. target_mod_dir = *prop;
  6051. } else {
  6052. std::string const& default_mod_dir =
  6053. this->LocalGenerator->GetCurrentBinaryDirectory();
  6054. if (default_mod_dir != working_dir) {
  6055. target_mod_dir = default_mod_dir;
  6056. }
  6057. }
  6058. cmValue moddir_flag =
  6059. this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
  6060. if (!target_mod_dir.empty() && moddir_flag) {
  6061. // Compute the full path to the module directory.
  6062. if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
  6063. // Already a full path.
  6064. mod_dir = target_mod_dir;
  6065. } else {
  6066. // Interpret relative to the current output directory.
  6067. mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  6068. '/', target_mod_dir);
  6069. }
  6070. // Make sure the module output directory exists.
  6071. cmSystemTools::MakeDirectory(mod_dir);
  6072. }
  6073. return mod_dir;
  6074. }
  6075. void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
  6076. std::string const& config)
  6077. {
  6078. std::string config_upper;
  6079. if (!config.empty()) {
  6080. config_upper = cmSystemTools::UpperCase(config);
  6081. }
  6082. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  6083. if (iter == this->ISPCGeneratedHeaders.end()) {
  6084. std::vector<std::string> headers;
  6085. headers.emplace_back(header);
  6086. this->ISPCGeneratedHeaders.insert({ config_upper, headers });
  6087. } else {
  6088. iter->second.emplace_back(header);
  6089. }
  6090. }
  6091. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
  6092. std::string const& config) const
  6093. {
  6094. std::string config_upper;
  6095. if (!config.empty()) {
  6096. config_upper = cmSystemTools::UpperCase(config);
  6097. }
  6098. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  6099. if (iter == this->ISPCGeneratedHeaders.end()) {
  6100. return std::vector<std::string>{};
  6101. }
  6102. return iter->second;
  6103. }
  6104. void cmGeneratorTarget::AddISPCGeneratedObject(std::vector<std::string>&& objs,
  6105. std::string const& config)
  6106. {
  6107. std::string config_upper;
  6108. if (!config.empty()) {
  6109. config_upper = cmSystemTools::UpperCase(config);
  6110. }
  6111. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  6112. if (iter == this->ISPCGeneratedObjects.end()) {
  6113. this->ISPCGeneratedObjects.insert({ config_upper, objs });
  6114. } else {
  6115. iter->second.insert(iter->second.end(), objs.begin(), objs.end());
  6116. }
  6117. }
  6118. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCObjects(
  6119. std::string const& config) const
  6120. {
  6121. std::string config_upper;
  6122. if (!config.empty()) {
  6123. config_upper = cmSystemTools::UpperCase(config);
  6124. }
  6125. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  6126. if (iter == this->ISPCGeneratedObjects.end()) {
  6127. return std::vector<std::string>{};
  6128. }
  6129. return iter->second;
  6130. }
  6131. std::string cmGeneratorTarget::GetFrameworkVersion() const
  6132. {
  6133. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  6134. if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
  6135. return *fversion;
  6136. }
  6137. if (cmValue tversion = this->GetProperty("VERSION")) {
  6138. return *tversion;
  6139. }
  6140. return "A";
  6141. }
  6142. void cmGeneratorTarget::ComputeVersionedName(
  6143. std::string& vName, std::string const& prefix, std::string const& base,
  6144. std::string const& suffix, std::string const& name, cmValue version) const
  6145. {
  6146. vName = this->IsApple() ? (prefix + base) : name;
  6147. if (version) {
  6148. vName += ".";
  6149. vName += *version;
  6150. }
  6151. vName += this->IsApple() ? suffix : std::string();
  6152. }
  6153. std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
  6154. {
  6155. return this->Target->GetProperties().GetKeys();
  6156. }
  6157. void cmGeneratorTarget::ReportPropertyOrigin(
  6158. const std::string& p, const std::string& result, const std::string& report,
  6159. const std::string& compatibilityType) const
  6160. {
  6161. cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
  6162. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  6163. bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
  6164. cm::contains(debugProperties, p);
  6165. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  6166. this->DebugCompatiblePropertiesDone[p] = true;
  6167. }
  6168. if (!debugOrigin) {
  6169. return;
  6170. }
  6171. std::string areport =
  6172. cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
  6173. this->GetName(), "\" (result: \"", result, "\"):\n", report);
  6174. this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
  6175. areport);
  6176. }
  6177. bool cmGeneratorTarget::IsLinkLookupScope(std::string const& n,
  6178. cmLocalGenerator const*& lg) const
  6179. {
  6180. if (cmHasLiteralPrefix(n, CMAKE_DIRECTORY_ID_SEP)) {
  6181. cmDirectoryId const dirId = n.substr(cmStrLen(CMAKE_DIRECTORY_ID_SEP));
  6182. if (dirId.String.empty()) {
  6183. lg = this->LocalGenerator;
  6184. return true;
  6185. }
  6186. if (cmLocalGenerator const* otherLG =
  6187. this->GlobalGenerator->FindLocalGenerator(dirId)) {
  6188. lg = otherLG;
  6189. return true;
  6190. }
  6191. }
  6192. return false;
  6193. }
  6194. cm::optional<cmLinkItem> cmGeneratorTarget::LookupLinkItem(
  6195. std::string const& n, cmListFileBacktrace const& bt,
  6196. std::string const& linkFeature, LookupLinkItemScope* scope,
  6197. LookupSelf lookupSelf) const
  6198. {
  6199. cm::optional<cmLinkItem> maybeItem;
  6200. if (this->IsLinkLookupScope(n, scope->LG)) {
  6201. return maybeItem;
  6202. }
  6203. std::string name = this->CheckCMP0004(n);
  6204. if (name.empty() ||
  6205. (lookupSelf == LookupSelf::No && name == this->GetName())) {
  6206. return maybeItem;
  6207. }
  6208. maybeItem =
  6209. this->ResolveLinkItem(BT<std::string>(name, bt), scope->LG, linkFeature);
  6210. return maybeItem;
  6211. }
  6212. void cmGeneratorTarget::ExpandLinkItems(
  6213. std::string const& prop, cmBTStringRange entries, std::string const& config,
  6214. cmGeneratorTarget const* headTarget, LinkInterfaceFor interfaceFor,
  6215. LinkInterfaceField field, cmLinkInterface& iface) const
  6216. {
  6217. if (entries.empty()) {
  6218. return;
  6219. }
  6220. // Keep this logic in sync with ComputeLinkImplementationLibraries.
  6221. cmGeneratorExpressionDAGChecker dagChecker(this, prop, nullptr, nullptr);
  6222. // The $<LINK_ONLY> expression may be in a link interface to specify
  6223. // private link dependencies that are otherwise excluded from usage
  6224. // requirements.
  6225. if (interfaceFor == LinkInterfaceFor::Usage) {
  6226. dagChecker.SetTransitivePropertiesOnly();
  6227. dagChecker.SetTransitivePropertiesOnlyCMP0131();
  6228. }
  6229. cmMakefile const* mf = this->LocalGenerator->GetMakefile();
  6230. LookupLinkItemScope scope{ this->LocalGenerator };
  6231. for (BT<std::string> const& entry : entries) {
  6232. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance(),
  6233. entry.Backtrace);
  6234. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(entry.Value);
  6235. cge->SetEvaluateForBuildsystem(true);
  6236. cmList libs{ cge->Evaluate(this->LocalGenerator, config, headTarget,
  6237. &dagChecker, this,
  6238. headTarget->LinkerLanguage) };
  6239. auto linkFeature = cmLinkItem::DEFAULT;
  6240. for (auto const& lib : libs) {
  6241. if (auto maybeLinkFeature = ParseLinkFeature(lib)) {
  6242. linkFeature = std::move(*maybeLinkFeature);
  6243. continue;
  6244. }
  6245. if (cm::optional<cmLinkItem> maybeItem = this->LookupLinkItem(
  6246. lib, cge->GetBacktrace(), linkFeature, &scope,
  6247. field == LinkInterfaceField::Libraries ? LookupSelf::No
  6248. : LookupSelf::Yes)) {
  6249. cmLinkItem item = std::move(*maybeItem);
  6250. if (field == LinkInterfaceField::HeadInclude) {
  6251. iface.HeadInclude.emplace_back(std::move(item));
  6252. continue;
  6253. }
  6254. if (field == LinkInterfaceField::HeadExclude) {
  6255. iface.HeadExclude.emplace_back(std::move(item));
  6256. continue;
  6257. }
  6258. if (!item.Target) {
  6259. // Report explicitly linked object files separately.
  6260. std::string const& maybeObj = item.AsStr();
  6261. if (cmSystemTools::FileIsFullPath(maybeObj)) {
  6262. cmSourceFile const* sf =
  6263. mf->GetSource(maybeObj, cmSourceFileLocationKind::Known);
  6264. if (sf && sf->GetPropertyAsBool("EXTERNAL_OBJECT")) {
  6265. item.ObjectSource = sf;
  6266. iface.Objects.emplace_back(std::move(item));
  6267. continue;
  6268. }
  6269. }
  6270. }
  6271. iface.Libraries.emplace_back(std::move(item));
  6272. }
  6273. }
  6274. if (cge->GetHadHeadSensitiveCondition()) {
  6275. iface.HadHeadSensitiveCondition = true;
  6276. }
  6277. if (cge->GetHadContextSensitiveCondition()) {
  6278. iface.HadContextSensitiveCondition = true;
  6279. }
  6280. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  6281. iface.HadLinkLanguageSensitiveCondition = true;
  6282. }
  6283. }
  6284. }
  6285. cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
  6286. const std::string& config, cmGeneratorTarget const* head) const
  6287. {
  6288. return this->GetLinkInterface(config, head, false);
  6289. }
  6290. cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
  6291. const std::string& config, cmGeneratorTarget const* head,
  6292. bool secondPass) const
  6293. {
  6294. // Imported targets have their own link interface.
  6295. if (this->IsImported()) {
  6296. return this->GetImportLinkInterface(config, head, LinkInterfaceFor::Link,
  6297. secondPass);
  6298. }
  6299. // Link interfaces are not supported for executables that do not
  6300. // export symbols.
  6301. if (this->GetType() == cmStateEnums::EXECUTABLE &&
  6302. !this->IsExecutableWithExports()) {
  6303. return nullptr;
  6304. }
  6305. // Lookup any existing link interface for this configuration.
  6306. cmHeadToLinkInterfaceMap& hm = this->GetHeadToLinkInterfaceMap(config);
  6307. // If the link interface does not depend on the head target
  6308. // then reuse the one from the head we computed first.
  6309. if (!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition) {
  6310. head = hm.begin()->first;
  6311. }
  6312. cmOptionalLinkInterface& iface = hm[head];
  6313. if (secondPass) {
  6314. iface = cmOptionalLinkInterface();
  6315. }
  6316. if (!iface.LibrariesDone) {
  6317. iface.LibrariesDone = true;
  6318. this->ComputeLinkInterfaceLibraries(config, iface, head,
  6319. LinkInterfaceFor::Link);
  6320. }
  6321. if (!iface.AllDone) {
  6322. iface.AllDone = true;
  6323. if (iface.Exists) {
  6324. this->ComputeLinkInterface(config, iface, head, secondPass);
  6325. this->ComputeLinkInterfaceRuntimeLibraries(config, iface);
  6326. }
  6327. }
  6328. return iface.Exists ? &iface : nullptr;
  6329. }
  6330. void cmGeneratorTarget::ComputeLinkInterface(
  6331. const std::string& config, cmOptionalLinkInterface& iface,
  6332. cmGeneratorTarget const* headTarget) const
  6333. {
  6334. this->ComputeLinkInterface(config, iface, headTarget, false);
  6335. }
  6336. void cmGeneratorTarget::ComputeLinkInterface(
  6337. const std::string& config, cmOptionalLinkInterface& iface,
  6338. cmGeneratorTarget const* headTarget, bool secondPass) const
  6339. {
  6340. if (iface.Explicit) {
  6341. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  6342. this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  6343. this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  6344. // Shared libraries may have runtime implementation dependencies
  6345. // on other shared libraries that are not in the interface.
  6346. std::set<cmLinkItem> emitted;
  6347. for (cmLinkItem const& lib : iface.Libraries) {
  6348. emitted.insert(lib);
  6349. }
  6350. if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  6351. cmLinkImplementation const* impl = this->GetLinkImplementation(
  6352. config, LinkInterfaceFor::Link, secondPass);
  6353. for (cmLinkImplItem const& lib : impl->Libraries) {
  6354. if (emitted.insert(lib).second) {
  6355. if (lib.Target) {
  6356. // This is a runtime dependency on another shared library.
  6357. if (lib.Target->GetType() == cmStateEnums::SHARED_LIBRARY) {
  6358. iface.SharedDeps.push_back(lib);
  6359. }
  6360. } else {
  6361. // TODO: Recognize shared library file names. Perhaps this
  6362. // should be moved to cmComputeLinkInformation, but that
  6363. // creates a chicken-and-egg problem since this list is needed
  6364. // for its construction.
  6365. }
  6366. }
  6367. }
  6368. }
  6369. }
  6370. } else if (this->GetPolicyStatusCMP0022() == cmPolicies::WARN ||
  6371. this->GetPolicyStatusCMP0022() == cmPolicies::OLD) {
  6372. // The link implementation is the default link interface.
  6373. cmLinkImplementationLibraries const* impl =
  6374. this->GetLinkImplementationLibrariesInternal(config, headTarget,
  6375. LinkInterfaceFor::Link);
  6376. iface.ImplementationIsInterface = true;
  6377. iface.WrongConfigLibraries = impl->WrongConfigLibraries;
  6378. }
  6379. if (this->LinkLanguagePropagatesToDependents()) {
  6380. // Targets using this archive need its language runtime libraries.
  6381. if (cmLinkImplementation const* impl = this->GetLinkImplementation(
  6382. config, LinkInterfaceFor::Link, secondPass)) {
  6383. iface.Languages = impl->Languages;
  6384. }
  6385. }
  6386. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  6387. // Construct the property name suffix for this configuration.
  6388. std::string suffix = "_";
  6389. if (!config.empty()) {
  6390. suffix += cmSystemTools::UpperCase(config);
  6391. } else {
  6392. suffix += "NOCONFIG";
  6393. }
  6394. // How many repetitions are needed if this library has cyclic
  6395. // dependencies?
  6396. std::string propName = cmStrCat("LINK_INTERFACE_MULTIPLICITY", suffix);
  6397. if (cmValue config_reps = this->GetProperty(propName)) {
  6398. sscanf(config_reps->c_str(), "%u", &iface.Multiplicity);
  6399. } else if (cmValue reps =
  6400. this->GetProperty("LINK_INTERFACE_MULTIPLICITY")) {
  6401. sscanf(reps->c_str(), "%u", &iface.Multiplicity);
  6402. }
  6403. }
  6404. }
  6405. const cmLinkInterfaceLibraries* cmGeneratorTarget::GetLinkInterfaceLibraries(
  6406. const std::string& config, cmGeneratorTarget const* head,
  6407. LinkInterfaceFor interfaceFor) const
  6408. {
  6409. // Imported targets have their own link interface.
  6410. if (this->IsImported()) {
  6411. return this->GetImportLinkInterface(config, head, interfaceFor);
  6412. }
  6413. // Link interfaces are not supported for executables that do not
  6414. // export symbols.
  6415. if (this->GetType() == cmStateEnums::EXECUTABLE &&
  6416. !this->IsExecutableWithExports()) {
  6417. return nullptr;
  6418. }
  6419. // Lookup any existing link interface for this configuration.
  6420. cmHeadToLinkInterfaceMap& hm =
  6421. (interfaceFor == LinkInterfaceFor::Usage
  6422. ? this->GetHeadToLinkInterfaceUsageRequirementsMap(config)
  6423. : this->GetHeadToLinkInterfaceMap(config));
  6424. // If the link interface does not depend on the head target
  6425. // then reuse the one from the head we computed first.
  6426. if (!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition) {
  6427. head = hm.begin()->first;
  6428. }
  6429. cmOptionalLinkInterface& iface = hm[head];
  6430. if (!iface.LibrariesDone) {
  6431. iface.LibrariesDone = true;
  6432. this->ComputeLinkInterfaceLibraries(config, iface, head, interfaceFor);
  6433. }
  6434. return iface.Exists ? &iface : nullptr;
  6435. }
  6436. std::string cmGeneratorTarget::GetDirectory(
  6437. const std::string& config, cmStateEnums::ArtifactType artifact) const
  6438. {
  6439. if (this->IsImported()) {
  6440. auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
  6441. if (this->IsFrameworkOnApple()) {
  6442. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  6443. fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
  6444. if (fwDescriptor) {
  6445. return fwDescriptor->Directory;
  6446. }
  6447. }
  6448. // Return the directory from which the target is imported.
  6449. return cmSystemTools::GetFilenamePath(fullPath);
  6450. }
  6451. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  6452. // Return the directory in which the target will be built.
  6453. switch (artifact) {
  6454. case cmStateEnums::RuntimeBinaryArtifact:
  6455. return info->OutDir;
  6456. case cmStateEnums::ImportLibraryArtifact:
  6457. return info->ImpDir;
  6458. }
  6459. }
  6460. return "";
  6461. }
  6462. bool cmGeneratorTarget::UsesDefaultOutputDir(
  6463. const std::string& config, cmStateEnums::ArtifactType artifact) const
  6464. {
  6465. std::string dir;
  6466. return this->ComputeOutputDir(config, artifact, dir);
  6467. }
  6468. cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
  6469. const std::string& config) const
  6470. {
  6471. // There is no output information for imported targets.
  6472. if (this->IsImported()) {
  6473. return nullptr;
  6474. }
  6475. // Synthetic targets don't have output.
  6476. if (this->IsSynthetic()) {
  6477. return nullptr;
  6478. }
  6479. // Only libraries and executables have well-defined output files.
  6480. if (!this->HaveWellDefinedOutputFiles()) {
  6481. std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
  6482. this->GetName(), " which has type ",
  6483. cmState::GetTargetTypeName(this->GetType()));
  6484. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  6485. return nullptr;
  6486. }
  6487. // Lookup/compute/cache the output information for this configuration.
  6488. std::string config_upper;
  6489. if (!config.empty()) {
  6490. config_upper = cmSystemTools::UpperCase(config);
  6491. }
  6492. auto i = this->OutputInfoMap.find(config_upper);
  6493. if (i == this->OutputInfoMap.end()) {
  6494. // Add empty info in map to detect potential recursion.
  6495. OutputInfo info;
  6496. OutputInfoMapType::value_type entry(config_upper, info);
  6497. i = this->OutputInfoMap.insert(entry).first;
  6498. // Compute output directories.
  6499. this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
  6500. info.OutDir);
  6501. this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
  6502. info.ImpDir);
  6503. if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
  6504. info.PdbDir = info.OutDir;
  6505. }
  6506. // Now update the previously-prepared map entry.
  6507. i->second = info;
  6508. } else if (i->second.empty()) {
  6509. // An empty map entry indicates we have been called recursively
  6510. // from the above block.
  6511. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  6512. MessageType::FATAL_ERROR,
  6513. "Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
  6514. this->GetBacktrace());
  6515. return nullptr;
  6516. }
  6517. return &i->second;
  6518. }
  6519. bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
  6520. cmStateEnums::ArtifactType artifact,
  6521. std::string& out) const
  6522. {
  6523. bool usesDefaultOutputDir = false;
  6524. std::string conf = config;
  6525. // Look for a target property defining the target output directory
  6526. // based on the target type.
  6527. std::string targetTypeName = this->GetOutputTargetType(artifact);
  6528. std::string propertyName;
  6529. if (!targetTypeName.empty()) {
  6530. propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
  6531. }
  6532. // Check for a per-configuration output directory target property.
  6533. std::string configUpper = cmSystemTools::UpperCase(conf);
  6534. std::string configProp;
  6535. if (!targetTypeName.empty()) {
  6536. configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
  6537. }
  6538. // Select an output directory.
  6539. if (cmValue config_outdir = this->GetProperty(configProp)) {
  6540. // Use the user-specified per-configuration output directory.
  6541. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  6542. config, this);
  6543. // Skip per-configuration subdirectory.
  6544. conf.clear();
  6545. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  6546. // Use the user-specified output directory.
  6547. out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
  6548. config, this);
  6549. // Skip per-configuration subdirectory if the value contained a
  6550. // generator expression.
  6551. if (out != *outdir) {
  6552. conf.clear();
  6553. }
  6554. } else if (this->GetType() == cmStateEnums::EXECUTABLE) {
  6555. // Lookup the output path for executables.
  6556. out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
  6557. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  6558. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  6559. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  6560. // Lookup the output path for libraries.
  6561. out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
  6562. }
  6563. if (out.empty()) {
  6564. // Default to the current output directory.
  6565. usesDefaultOutputDir = true;
  6566. out = ".";
  6567. }
  6568. // Convert the output path to a full path in case it is
  6569. // specified as a relative path. Treat a relative path as
  6570. // relative to the current output directory for this makefile.
  6571. out = (cmSystemTools::CollapseFullPath(
  6572. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  6573. // The generator may add the configuration's subdirectory.
  6574. if (!conf.empty()) {
  6575. bool useEPN =
  6576. this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
  6577. std::string suffix =
  6578. usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
  6579. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  6580. "/", conf, suffix, out);
  6581. }
  6582. return usesDefaultOutputDir;
  6583. }
  6584. bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
  6585. const std::string& config,
  6586. std::string& out) const
  6587. {
  6588. // Look for a target property defining the target output directory
  6589. // based on the target type.
  6590. std::string propertyName;
  6591. if (!kind.empty()) {
  6592. propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
  6593. }
  6594. std::string conf = config;
  6595. // Check for a per-configuration output directory target property.
  6596. std::string configUpper = cmSystemTools::UpperCase(conf);
  6597. std::string configProp;
  6598. if (!kind.empty()) {
  6599. configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
  6600. }
  6601. // Select an output directory.
  6602. if (cmValue config_outdir = this->GetProperty(configProp)) {
  6603. // Use the user-specified per-configuration output directory.
  6604. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  6605. config);
  6606. // Skip per-configuration subdirectory.
  6607. conf.clear();
  6608. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  6609. // Use the user-specified output directory.
  6610. out =
  6611. cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
  6612. // Skip per-configuration subdirectory if the value contained a
  6613. // generator expression.
  6614. if (out != *outdir) {
  6615. conf.clear();
  6616. }
  6617. }
  6618. if (out.empty()) {
  6619. return false;
  6620. }
  6621. // Convert the output path to a full path in case it is
  6622. // specified as a relative path. Treat a relative path as
  6623. // relative to the current output directory for this makefile.
  6624. out = (cmSystemTools::CollapseFullPath(
  6625. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  6626. // The generator may add the configuration's subdirectory.
  6627. if (!conf.empty()) {
  6628. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  6629. "/", conf, "", out);
  6630. }
  6631. return true;
  6632. }
  6633. bool cmGeneratorTarget::HaveInstallTreeRPATH(const std::string& config) const
  6634. {
  6635. std::string install_rpath;
  6636. this->GetInstallRPATH(config, install_rpath);
  6637. return !install_rpath.empty() &&
  6638. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  6639. }
  6640. bool cmGeneratorTarget::GetBuildRPATH(const std::string& config,
  6641. std::string& rpath) const
  6642. {
  6643. return this->GetRPATH(config, "BUILD_RPATH", rpath);
  6644. }
  6645. bool cmGeneratorTarget::GetInstallRPATH(const std::string& config,
  6646. std::string& rpath) const
  6647. {
  6648. return this->GetRPATH(config, "INSTALL_RPATH", rpath);
  6649. }
  6650. bool cmGeneratorTarget::GetRPATH(const std::string& config,
  6651. const std::string& prop,
  6652. std::string& rpath) const
  6653. {
  6654. cmValue value = this->GetProperty(prop);
  6655. if (!value) {
  6656. return false;
  6657. }
  6658. rpath =
  6659. cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
  6660. return true;
  6661. }
  6662. void cmGeneratorTarget::ComputeLinkInterfaceLibraries(
  6663. const std::string& config, cmOptionalLinkInterface& iface,
  6664. cmGeneratorTarget const* headTarget, LinkInterfaceFor interfaceFor) const
  6665. {
  6666. // Construct the property name suffix for this configuration.
  6667. std::string suffix = "_";
  6668. if (!config.empty()) {
  6669. suffix += cmSystemTools::UpperCase(config);
  6670. } else {
  6671. suffix += "NOCONFIG";
  6672. }
  6673. // An explicit list of interface libraries may be set for shared
  6674. // libraries and executables that export symbols.
  6675. bool haveExplicitLibraries = false;
  6676. cmValue explicitLibrariesCMP0022OLD;
  6677. std::string linkIfacePropCMP0022OLD;
  6678. bool const cmp0022NEW = (this->GetPolicyStatusCMP0022() != cmPolicies::OLD &&
  6679. this->GetPolicyStatusCMP0022() != cmPolicies::WARN);
  6680. if (cmp0022NEW) {
  6681. // CMP0022 NEW behavior is to use INTERFACE_LINK_LIBRARIES.
  6682. haveExplicitLibraries = !this->Target->GetLinkInterfaceEntries().empty() ||
  6683. !this->Target->GetLinkInterfaceDirectEntries().empty() ||
  6684. !this->Target->GetLinkInterfaceDirectExcludeEntries().empty();
  6685. } else {
  6686. // CMP0022 OLD behavior is to use LINK_INTERFACE_LIBRARIES if set on a
  6687. // shared lib or executable.
  6688. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  6689. this->IsExecutableWithExports()) {
  6690. // Lookup the per-configuration property.
  6691. linkIfacePropCMP0022OLD = cmStrCat("LINK_INTERFACE_LIBRARIES", suffix);
  6692. explicitLibrariesCMP0022OLD = this->GetProperty(linkIfacePropCMP0022OLD);
  6693. // If not set, try the generic property.
  6694. if (!explicitLibrariesCMP0022OLD) {
  6695. linkIfacePropCMP0022OLD = "LINK_INTERFACE_LIBRARIES";
  6696. explicitLibrariesCMP0022OLD =
  6697. this->GetProperty(linkIfacePropCMP0022OLD);
  6698. }
  6699. }
  6700. if (explicitLibrariesCMP0022OLD &&
  6701. this->GetPolicyStatusCMP0022() == cmPolicies::WARN &&
  6702. !this->PolicyWarnedCMP0022) {
  6703. // Compare the explicitly set old link interface properties to the
  6704. // preferred new link interface property one and warn if different.
  6705. cmValue newExplicitLibraries =
  6706. this->GetProperty("INTERFACE_LINK_LIBRARIES");
  6707. if (newExplicitLibraries &&
  6708. (*newExplicitLibraries != *explicitLibrariesCMP0022OLD)) {
  6709. std::ostringstream w;
  6710. /* clang-format off */
  6711. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0022) << "\n"
  6712. "Target \"" << this->GetName() << "\" has an "
  6713. "INTERFACE_LINK_LIBRARIES property which differs from its " <<
  6714. linkIfacePropCMP0022OLD << " properties."
  6715. "\n"
  6716. "INTERFACE_LINK_LIBRARIES:\n"
  6717. " " << *newExplicitLibraries << "\n" <<
  6718. linkIfacePropCMP0022OLD << ":\n"
  6719. " " << *explicitLibrariesCMP0022OLD << "\n";
  6720. /* clang-format on */
  6721. this->LocalGenerator->IssueMessage(MessageType::AUTHOR_WARNING,
  6722. w.str());
  6723. this->PolicyWarnedCMP0022 = true;
  6724. }
  6725. }
  6726. haveExplicitLibraries = static_cast<bool>(explicitLibrariesCMP0022OLD);
  6727. }
  6728. // There is no implicit link interface for executables or modules
  6729. // so if none was explicitly set then there is no link interface.
  6730. if (!haveExplicitLibraries &&
  6731. (this->GetType() == cmStateEnums::EXECUTABLE ||
  6732. (this->GetType() == cmStateEnums::MODULE_LIBRARY))) {
  6733. return;
  6734. }
  6735. iface.Exists = true;
  6736. // If CMP0022 is NEW then the plain tll signature sets the
  6737. // INTERFACE_LINK_LIBRARIES property. Even if the project
  6738. // clears it, the link interface is still explicit.
  6739. iface.Explicit = cmp0022NEW || explicitLibrariesCMP0022OLD;
  6740. if (cmp0022NEW) {
  6741. // The interface libraries are specified by INTERFACE_LINK_LIBRARIES.
  6742. // Use its special representation directly to get backtraces.
  6743. this->ExpandLinkItems(
  6744. kINTERFACE_LINK_LIBRARIES, this->Target->GetLinkInterfaceEntries(),
  6745. config, headTarget, interfaceFor, LinkInterfaceField::Libraries, iface);
  6746. this->ExpandLinkItems(kINTERFACE_LINK_LIBRARIES_DIRECT,
  6747. this->Target->GetLinkInterfaceDirectEntries(),
  6748. config, headTarget, interfaceFor,
  6749. LinkInterfaceField::HeadInclude, iface);
  6750. this->ExpandLinkItems(kINTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE,
  6751. this->Target->GetLinkInterfaceDirectExcludeEntries(),
  6752. config, headTarget, interfaceFor,
  6753. LinkInterfaceField::HeadExclude, iface);
  6754. } else if (explicitLibrariesCMP0022OLD) {
  6755. // The interface libraries have been explicitly set in pre-CMP0022 style.
  6756. std::vector<BT<std::string>> entries;
  6757. entries.emplace_back(*explicitLibrariesCMP0022OLD);
  6758. this->ExpandLinkItems(linkIfacePropCMP0022OLD, cmMakeRange(entries),
  6759. config, headTarget, interfaceFor,
  6760. LinkInterfaceField::Libraries, iface);
  6761. }
  6762. // If the link interface is explicit, do not fall back to the link impl.
  6763. if (iface.Explicit) {
  6764. return;
  6765. }
  6766. // The link implementation is the default link interface.
  6767. if (cmLinkImplementationLibraries const* impl =
  6768. this->GetLinkImplementationLibrariesInternal(config, headTarget,
  6769. interfaceFor)) {
  6770. iface.Libraries.insert(iface.Libraries.end(), impl->Libraries.begin(),
  6771. impl->Libraries.end());
  6772. if (this->GetPolicyStatusCMP0022() == cmPolicies::WARN &&
  6773. !this->PolicyWarnedCMP0022 && interfaceFor == LinkInterfaceFor::Link) {
  6774. // Compare the link implementation fallback link interface to the
  6775. // preferred new link interface property and warn if different.
  6776. cmLinkInterface ifaceNew;
  6777. this->ExpandLinkItems(kINTERFACE_LINK_LIBRARIES,
  6778. this->Target->GetLinkInterfaceEntries(), config,
  6779. headTarget, interfaceFor,
  6780. LinkInterfaceField::Libraries, ifaceNew);
  6781. if (ifaceNew.Libraries != iface.Libraries) {
  6782. std::string oldLibraries = cmJoin(impl->Libraries, ";");
  6783. std::string newLibraries = cmJoin(ifaceNew.Libraries, ";");
  6784. if (oldLibraries.empty()) {
  6785. oldLibraries = "(empty)";
  6786. }
  6787. if (newLibraries.empty()) {
  6788. newLibraries = "(empty)";
  6789. }
  6790. std::ostringstream w;
  6791. /* clang-format off */
  6792. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0022) << "\n"
  6793. "Target \"" << this->GetName() << "\" has an "
  6794. "INTERFACE_LINK_LIBRARIES property. "
  6795. "This should be preferred as the source of the link interface "
  6796. "for this library but because CMP0022 is not set CMake is "
  6797. "ignoring the property and using the link implementation "
  6798. "as the link interface instead."
  6799. "\n"
  6800. "INTERFACE_LINK_LIBRARIES:\n"
  6801. " " << newLibraries << "\n"
  6802. "Link implementation:\n"
  6803. " " << oldLibraries << "\n";
  6804. /* clang-format on */
  6805. this->LocalGenerator->IssueMessage(MessageType::AUTHOR_WARNING,
  6806. w.str());
  6807. this->PolicyWarnedCMP0022 = true;
  6808. }
  6809. }
  6810. }
  6811. }
  6812. namespace {
  6813. template <typename ReturnType>
  6814. ReturnType constructItem(cmGeneratorTarget* target,
  6815. cmListFileBacktrace const& bt);
  6816. template <>
  6817. inline cmLinkImplItem constructItem(cmGeneratorTarget* target,
  6818. cmListFileBacktrace const& bt)
  6819. {
  6820. return cmLinkImplItem(cmLinkItem(target, false, bt), false);
  6821. }
  6822. template <>
  6823. inline cmLinkItem constructItem(cmGeneratorTarget* target,
  6824. cmListFileBacktrace const& bt)
  6825. {
  6826. return cmLinkItem(target, false, bt);
  6827. }
  6828. template <typename ValueType>
  6829. std::vector<ValueType> computeImplicitLanguageTargets(
  6830. std::string const& lang, std::string const& config,
  6831. cmGeneratorTarget const* currentTarget)
  6832. {
  6833. cmListFileBacktrace bt;
  6834. std::vector<ValueType> result;
  6835. cmLocalGenerator* lg = currentTarget->GetLocalGenerator();
  6836. std::string const& runtimeLibrary =
  6837. currentTarget->GetRuntimeLinkLibrary(lang, config);
  6838. if (cmValue runtimeLinkOptions = currentTarget->Makefile->GetDefinition(
  6839. "CMAKE_" + lang + "_RUNTIME_LIBRARIES_" + runtimeLibrary)) {
  6840. cmList libsList{ *runtimeLinkOptions };
  6841. result.reserve(libsList.size());
  6842. for (auto const& i : libsList) {
  6843. cmGeneratorTarget::TargetOrString resolved =
  6844. currentTarget->ResolveTargetReference(i, lg);
  6845. if (resolved.Target) {
  6846. result.emplace_back(constructItem<ValueType>(resolved.Target, bt));
  6847. }
  6848. }
  6849. }
  6850. return result;
  6851. }
  6852. }
  6853. void cmGeneratorTarget::ComputeLinkInterfaceRuntimeLibraries(
  6854. const std::string& config, cmOptionalLinkInterface& iface) const
  6855. {
  6856. for (std::string const& lang : iface.Languages) {
  6857. if ((lang == "CUDA" || lang == "HIP") &&
  6858. iface.LanguageRuntimeLibraries.find(lang) ==
  6859. iface.LanguageRuntimeLibraries.end()) {
  6860. auto implicitTargets =
  6861. computeImplicitLanguageTargets<cmLinkItem>(lang, config, this);
  6862. iface.LanguageRuntimeLibraries[lang] = std::move(implicitTargets);
  6863. }
  6864. }
  6865. }
  6866. void cmGeneratorTarget::ComputeLinkImplementationRuntimeLibraries(
  6867. const std::string& config, cmOptionalLinkImplementation& impl) const
  6868. {
  6869. for (std::string const& lang : impl.Languages) {
  6870. if ((lang == "CUDA" || lang == "HIP") &&
  6871. impl.LanguageRuntimeLibraries.find(lang) ==
  6872. impl.LanguageRuntimeLibraries.end()) {
  6873. auto implicitTargets =
  6874. computeImplicitLanguageTargets<cmLinkImplItem>(lang, config, this);
  6875. impl.LanguageRuntimeLibraries[lang] = std::move(implicitTargets);
  6876. }
  6877. }
  6878. }
  6879. const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface(
  6880. const std::string& config, cmGeneratorTarget const* headTarget,
  6881. LinkInterfaceFor interfaceFor, bool secondPass) const
  6882. {
  6883. cmGeneratorTarget::ImportInfo const* info = this->GetImportInfo(config);
  6884. if (!info) {
  6885. return nullptr;
  6886. }
  6887. cmHeadToLinkInterfaceMap& hm =
  6888. (interfaceFor == LinkInterfaceFor::Usage
  6889. ? this->GetHeadToLinkInterfaceUsageRequirementsMap(config)
  6890. : this->GetHeadToLinkInterfaceMap(config));
  6891. // If the link interface does not depend on the head target
  6892. // then reuse the one from the head we computed first.
  6893. if (!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition) {
  6894. headTarget = hm.begin()->first;
  6895. }
  6896. cmOptionalLinkInterface& iface = hm[headTarget];
  6897. if (secondPass) {
  6898. iface = cmOptionalLinkInterface();
  6899. }
  6900. if (!iface.AllDone) {
  6901. iface.AllDone = true;
  6902. iface.LibrariesDone = true;
  6903. iface.Multiplicity = info->Multiplicity;
  6904. cmExpandList(info->Languages, iface.Languages);
  6905. this->ExpandLinkItems(kINTERFACE_LINK_LIBRARIES_DIRECT,
  6906. cmMakeRange(info->LibrariesHeadInclude), config,
  6907. headTarget, interfaceFor,
  6908. LinkInterfaceField::HeadInclude, iface);
  6909. this->ExpandLinkItems(kINTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE,
  6910. cmMakeRange(info->LibrariesHeadExclude), config,
  6911. headTarget, interfaceFor,
  6912. LinkInterfaceField::HeadExclude, iface);
  6913. this->ExpandLinkItems(info->LibrariesProp, cmMakeRange(info->Libraries),
  6914. config, headTarget, interfaceFor,
  6915. LinkInterfaceField::Libraries, iface);
  6916. cmList deps{ info->SharedDeps };
  6917. LookupLinkItemScope scope{ this->LocalGenerator };
  6918. auto linkFeature = cmLinkItem::DEFAULT;
  6919. for (auto const& dep : deps) {
  6920. if (auto maybeLinkFeature = ParseLinkFeature(dep)) {
  6921. linkFeature = std::move(*maybeLinkFeature);
  6922. continue;
  6923. }
  6924. if (cm::optional<cmLinkItem> maybeItem = this->LookupLinkItem(
  6925. dep, cmListFileBacktrace(), linkFeature, &scope, LookupSelf::No)) {
  6926. iface.SharedDeps.emplace_back(std::move(*maybeItem));
  6927. }
  6928. }
  6929. }
  6930. return &iface;
  6931. }
  6932. cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
  6933. const std::string& config) const
  6934. {
  6935. // There is no imported information for non-imported targets.
  6936. if (!this->IsImported()) {
  6937. return nullptr;
  6938. }
  6939. // Lookup/compute/cache the import information for this
  6940. // configuration.
  6941. std::string config_upper;
  6942. if (!config.empty()) {
  6943. config_upper = cmSystemTools::UpperCase(config);
  6944. } else {
  6945. config_upper = "NOCONFIG";
  6946. }
  6947. auto i = this->ImportInfoMap.find(config_upper);
  6948. if (i == this->ImportInfoMap.end()) {
  6949. ImportInfo info;
  6950. this->ComputeImportInfo(config_upper, info);
  6951. ImportInfoMapType::value_type entry(config_upper, info);
  6952. i = this->ImportInfoMap.insert(entry).first;
  6953. }
  6954. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  6955. return &i->second;
  6956. }
  6957. // If the location is empty then the target is not available for
  6958. // this configuration.
  6959. if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
  6960. return nullptr;
  6961. }
  6962. // Return the import information.
  6963. return &i->second;
  6964. }
  6965. void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
  6966. ImportInfo& info) const
  6967. {
  6968. // This method finds information about an imported target from its
  6969. // properties. The "IMPORTED_" namespace is reserved for properties
  6970. // defined by the project exporting the target.
  6971. // Initialize members.
  6972. info.NoSOName = false;
  6973. cmValue loc = nullptr;
  6974. cmValue imp = nullptr;
  6975. std::string suffix;
  6976. if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
  6977. return;
  6978. }
  6979. // Get the link interface.
  6980. {
  6981. // Use the INTERFACE_LINK_LIBRARIES special representation directly
  6982. // to get backtraces.
  6983. cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
  6984. if (!entries.empty()) {
  6985. info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
  6986. for (BT<std::string> const& entry : entries) {
  6987. info.Libraries.emplace_back(entry);
  6988. }
  6989. } else if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  6990. std::string linkProp =
  6991. cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
  6992. cmValue propertyLibs = this->GetProperty(linkProp);
  6993. if (!propertyLibs) {
  6994. linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
  6995. propertyLibs = this->GetProperty(linkProp);
  6996. }
  6997. if (propertyLibs) {
  6998. info.LibrariesProp = linkProp;
  6999. info.Libraries.emplace_back(*propertyLibs);
  7000. }
  7001. }
  7002. }
  7003. for (BT<std::string> const& entry :
  7004. this->Target->GetLinkInterfaceDirectEntries()) {
  7005. info.LibrariesHeadInclude.emplace_back(entry);
  7006. }
  7007. for (BT<std::string> const& entry :
  7008. this->Target->GetLinkInterfaceDirectExcludeEntries()) {
  7009. info.LibrariesHeadExclude.emplace_back(entry);
  7010. }
  7011. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  7012. if (loc) {
  7013. info.LibName = *loc;
  7014. }
  7015. return;
  7016. }
  7017. // A provided configuration has been chosen. Load the
  7018. // configuration's properties.
  7019. // Get the location.
  7020. if (loc) {
  7021. info.Location = *loc;
  7022. } else {
  7023. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  7024. if (cmValue config_location = this->GetProperty(impProp)) {
  7025. info.Location = *config_location;
  7026. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  7027. info.Location = *location;
  7028. }
  7029. }
  7030. // Get the soname.
  7031. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  7032. std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
  7033. if (cmValue config_soname = this->GetProperty(soProp)) {
  7034. info.SOName = *config_soname;
  7035. } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
  7036. info.SOName = *soname;
  7037. }
  7038. }
  7039. // Get the "no-soname" mark.
  7040. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  7041. std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
  7042. if (cmValue config_no_soname = this->GetProperty(soProp)) {
  7043. info.NoSOName = config_no_soname.IsOn();
  7044. } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
  7045. info.NoSOName = no_soname.IsOn();
  7046. }
  7047. }
  7048. // Get the import library.
  7049. if (imp) {
  7050. info.ImportLibrary = *imp;
  7051. } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  7052. this->IsExecutableWithExports()) {
  7053. std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
  7054. if (cmValue config_implib = this->GetProperty(impProp)) {
  7055. info.ImportLibrary = *config_implib;
  7056. } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
  7057. info.ImportLibrary = *implib;
  7058. }
  7059. }
  7060. // Get the link dependencies.
  7061. {
  7062. std::string linkProp =
  7063. cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
  7064. if (cmValue config_libs = this->GetProperty(linkProp)) {
  7065. info.SharedDeps = *config_libs;
  7066. } else if (cmValue libs =
  7067. this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
  7068. info.SharedDeps = *libs;
  7069. }
  7070. }
  7071. // Get the link languages.
  7072. if (this->LinkLanguagePropagatesToDependents()) {
  7073. std::string linkProp =
  7074. cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
  7075. if (cmValue config_libs = this->GetProperty(linkProp)) {
  7076. info.Languages = *config_libs;
  7077. } else if (cmValue libs =
  7078. this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
  7079. info.Languages = *libs;
  7080. }
  7081. }
  7082. // Get information if target is managed assembly.
  7083. {
  7084. std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
  7085. if (cmValue pc = this->GetProperty(linkProp + suffix)) {
  7086. info.Managed = this->CheckManagedType(*pc);
  7087. } else if (cmValue p = this->GetProperty(linkProp)) {
  7088. info.Managed = this->CheckManagedType(*p);
  7089. }
  7090. }
  7091. // Get the cyclic repetition count.
  7092. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  7093. std::string linkProp =
  7094. cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
  7095. if (cmValue config_reps = this->GetProperty(linkProp)) {
  7096. sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
  7097. } else if (cmValue reps =
  7098. this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
  7099. sscanf(reps->c_str(), "%u", &info.Multiplicity);
  7100. }
  7101. }
  7102. }
  7103. cmHeadToLinkInterfaceMap& cmGeneratorTarget::GetHeadToLinkInterfaceMap(
  7104. const std::string& config) const
  7105. {
  7106. return this->LinkInterfaceMap[cmSystemTools::UpperCase(config)];
  7107. }
  7108. cmHeadToLinkInterfaceMap&
  7109. cmGeneratorTarget::GetHeadToLinkInterfaceUsageRequirementsMap(
  7110. const std::string& config) const
  7111. {
  7112. return this
  7113. ->LinkInterfaceUsageRequirementsOnlyMap[cmSystemTools::UpperCase(config)];
  7114. }
  7115. const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation(
  7116. const std::string& config, LinkInterfaceFor implFor) const
  7117. {
  7118. return this->GetLinkImplementation(config, implFor, false);
  7119. }
  7120. const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation(
  7121. const std::string& config, LinkInterfaceFor implFor, bool secondPass) const
  7122. {
  7123. // There is no link implementation for targets that cannot compile sources.
  7124. if (!this->CanCompileSources()) {
  7125. return nullptr;
  7126. }
  7127. HeadToLinkImplementationMap& hm =
  7128. (implFor == LinkInterfaceFor::Usage
  7129. ? this->GetHeadToLinkImplementationUsageRequirementsMap(config)
  7130. : this->GetHeadToLinkImplementationMap(config));
  7131. cmOptionalLinkImplementation& impl = hm[this];
  7132. if (secondPass) {
  7133. impl = cmOptionalLinkImplementation();
  7134. }
  7135. if (!impl.LibrariesDone) {
  7136. impl.LibrariesDone = true;
  7137. this->ComputeLinkImplementationLibraries(config, impl, this, implFor);
  7138. }
  7139. if (!impl.LanguagesDone) {
  7140. impl.LanguagesDone = true;
  7141. this->ComputeLinkImplementationLanguages(config, impl);
  7142. this->ComputeLinkImplementationRuntimeLibraries(config, impl);
  7143. }
  7144. return &impl;
  7145. }
  7146. cmGeneratorTarget::HeadToLinkImplementationMap&
  7147. cmGeneratorTarget::GetHeadToLinkImplementationMap(
  7148. std::string const& config) const
  7149. {
  7150. return this->LinkImplMap[cmSystemTools::UpperCase(config)];
  7151. }
  7152. cmGeneratorTarget::HeadToLinkImplementationMap&
  7153. cmGeneratorTarget::GetHeadToLinkImplementationUsageRequirementsMap(
  7154. std::string const& config) const
  7155. {
  7156. return this
  7157. ->LinkImplUsageRequirementsOnlyMap[cmSystemTools::UpperCase(config)];
  7158. }
  7159. bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
  7160. std::vector<cmSourceFile*>& files) const
  7161. {
  7162. std::vector<std::string> const& configs =
  7163. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  7164. auto it = configs.begin();
  7165. const std::string& firstConfig = *it;
  7166. this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
  7167. for (; it != configs.end(); ++it) {
  7168. std::vector<cmSourceFile*> configFiles;
  7169. this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
  7170. if (configFiles != files) {
  7171. std::string firstConfigFiles;
  7172. const char* sep = "";
  7173. for (cmSourceFile* f : files) {
  7174. firstConfigFiles += sep;
  7175. firstConfigFiles += f->ResolveFullPath();
  7176. sep = "\n ";
  7177. }
  7178. std::string thisConfigFiles;
  7179. sep = "";
  7180. for (cmSourceFile* f : configFiles) {
  7181. thisConfigFiles += sep;
  7182. thisConfigFiles += f->ResolveFullPath();
  7183. sep = "\n ";
  7184. }
  7185. std::ostringstream e;
  7186. /* clang-format off */
  7187. e << "Target \"" << this->GetName()
  7188. << "\" has source files which vary by "
  7189. "configuration. This is not supported by the \""
  7190. << this->GlobalGenerator->GetName()
  7191. << "\" generator.\n"
  7192. "Config \"" << firstConfig << "\":\n"
  7193. " " << firstConfigFiles << "\n"
  7194. "Config \"" << *it << "\":\n"
  7195. " " << thisConfigFiles << "\n";
  7196. /* clang-format on */
  7197. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  7198. return false;
  7199. }
  7200. }
  7201. return true;
  7202. }
  7203. void cmGeneratorTarget::GetObjectLibrariesCMP0026(
  7204. std::vector<cmGeneratorTarget*>& objlibs) const
  7205. {
  7206. // At configure-time, this method can be called as part of getting the
  7207. // LOCATION property or to export() a file to be include()d. However
  7208. // there is no cmGeneratorTarget at configure-time, so search the SOURCES
  7209. // for TARGET_OBJECTS instead for backwards compatibility with OLD
  7210. // behavior of CMP0024 and CMP0026 only.
  7211. cmBTStringRange rng = this->Target->GetSourceEntries();
  7212. for (auto const& entry : rng) {
  7213. cmList files{ entry.Value };
  7214. for (auto const& li : files) {
  7215. if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
  7216. std::string objLibName = li.substr(17, li.size() - 18);
  7217. if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
  7218. continue;
  7219. }
  7220. cmGeneratorTarget* objLib =
  7221. this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
  7222. if (objLib) {
  7223. objlibs.push_back(objLib);
  7224. }
  7225. }
  7226. }
  7227. }
  7228. }
  7229. std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
  7230. {
  7231. // Strip whitespace off the library names because we used to do this
  7232. // in case variables were expanded at generate time. We no longer
  7233. // do the expansion but users link to libraries like " ${VAR} ".
  7234. std::string lib = item;
  7235. std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
  7236. if (pos != std::string::npos) {
  7237. lib = lib.substr(pos);
  7238. }
  7239. pos = lib.find_last_not_of(" \t\r\n");
  7240. if (pos != std::string::npos) {
  7241. lib = lib.substr(0, pos + 1);
  7242. }
  7243. if (lib != item) {
  7244. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  7245. switch (this->GetPolicyStatusCMP0004()) {
  7246. case cmPolicies::WARN: {
  7247. std::ostringstream w;
  7248. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0004) << "\n"
  7249. << "Target \"" << this->GetName() << "\" links to item \"" << item
  7250. << "\" which has leading or trailing whitespace.";
  7251. cm->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  7252. this->GetBacktrace());
  7253. }
  7254. CM_FALLTHROUGH;
  7255. case cmPolicies::OLD:
  7256. break;
  7257. case cmPolicies::NEW: {
  7258. std::ostringstream e;
  7259. e << "Target \"" << this->GetName() << "\" links to item \"" << item
  7260. << "\" which has leading or trailing whitespace. "
  7261. << "This is now an error according to policy CMP0004.";
  7262. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  7263. this->GetBacktrace());
  7264. } break;
  7265. case cmPolicies::REQUIRED_IF_USED:
  7266. case cmPolicies::REQUIRED_ALWAYS: {
  7267. std::ostringstream e;
  7268. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0004) << "\n"
  7269. << "Target \"" << this->GetName() << "\" links to item \"" << item
  7270. << "\" which has leading or trailing whitespace.";
  7271. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  7272. this->GetBacktrace());
  7273. } break;
  7274. }
  7275. }
  7276. return lib;
  7277. }
  7278. bool cmGeneratorTarget::IsDeprecated() const
  7279. {
  7280. cmValue deprecation = this->GetProperty("DEPRECATION");
  7281. return cmNonempty(deprecation);
  7282. }
  7283. std::string cmGeneratorTarget::GetDeprecation() const
  7284. {
  7285. // find DEPRECATION property
  7286. if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
  7287. return *deprecation;
  7288. }
  7289. return std::string();
  7290. }
  7291. void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
  7292. const std::string& config) const
  7293. {
  7294. // Targets that do not compile anything have no languages.
  7295. if (!this->CanCompileSources()) {
  7296. return;
  7297. }
  7298. std::vector<cmSourceFile*> sourceFiles;
  7299. this->GetSourceFiles(sourceFiles, config);
  7300. for (cmSourceFile* src : sourceFiles) {
  7301. const std::string& lang = src->GetOrDetermineLanguage();
  7302. if (!lang.empty()) {
  7303. languages.insert(lang);
  7304. }
  7305. }
  7306. std::set<cmGeneratorTarget const*> objectLibraries;
  7307. if (!this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  7308. std::vector<cmGeneratorTarget*> objectTargets;
  7309. this->GetObjectLibrariesCMP0026(objectTargets);
  7310. for (cmGeneratorTarget* gt : objectTargets) {
  7311. objectLibraries.insert(gt);
  7312. }
  7313. } else {
  7314. objectLibraries = this->GetSourceObjectLibraries(config);
  7315. }
  7316. for (cmGeneratorTarget const* objLib : objectLibraries) {
  7317. objLib->GetLanguages(languages, config);
  7318. }
  7319. }
  7320. std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
  7321. std::string const& config) const
  7322. {
  7323. std::set<cmGeneratorTarget const*> objectLibraries;
  7324. std::vector<cmSourceFile const*> externalObjects;
  7325. this->GetExternalObjects(externalObjects, config);
  7326. for (cmSourceFile const* extObj : externalObjects) {
  7327. std::string objLib = extObj->GetObjectLibrary();
  7328. if (cmGeneratorTarget* tgt =
  7329. this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
  7330. objectLibraries.insert(tgt);
  7331. }
  7332. }
  7333. return objectLibraries;
  7334. }
  7335. bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
  7336. std::string const& config) const
  7337. {
  7338. std::set<std::string> languages;
  7339. this->GetLanguages(languages, config);
  7340. return languages.count(language);
  7341. }
  7342. bool cmGeneratorTarget::IsCSharpOnly() const
  7343. {
  7344. // Only certain target types may compile CSharp.
  7345. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  7346. this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  7347. this->GetType() != cmStateEnums::EXECUTABLE) {
  7348. return false;
  7349. }
  7350. std::set<std::string> languages = this->GetAllConfigCompileLanguages();
  7351. // Consider an explicit linker language property, but *not* the
  7352. // computed linker language that may depend on linked targets.
  7353. cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
  7354. if (cmNonempty(linkLang)) {
  7355. languages.insert(*linkLang);
  7356. }
  7357. return languages.size() == 1 && languages.count("CSharp") > 0;
  7358. }
  7359. bool cmGeneratorTarget::IsDotNetSdkTarget() const
  7360. {
  7361. return !this->GetProperty("DOTNET_SDK").IsEmpty();
  7362. }
  7363. void cmGeneratorTarget::ComputeLinkImplementationLanguages(
  7364. const std::string& config, cmOptionalLinkImplementation& impl) const
  7365. {
  7366. // This target needs runtime libraries for its source languages.
  7367. std::set<std::string> languages;
  7368. // Get languages used in our source files.
  7369. this->GetLanguages(languages, config);
  7370. // Copy the set of languages to the link implementation.
  7371. impl.Languages.insert(impl.Languages.begin(), languages.begin(),
  7372. languages.end());
  7373. }
  7374. bool cmGeneratorTarget::HaveBuildTreeRPATH(const std::string& config) const
  7375. {
  7376. if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
  7377. return false;
  7378. }
  7379. std::string build_rpath;
  7380. if (this->GetBuildRPATH(config, build_rpath)) {
  7381. return true;
  7382. }
  7383. if (cmLinkImplementationLibraries const* impl =
  7384. this->GetLinkImplementationLibraries(config, LinkInterfaceFor::Link)) {
  7385. return !impl->Libraries.empty();
  7386. }
  7387. return false;
  7388. }
  7389. cmLinkImplementationLibraries const*
  7390. cmGeneratorTarget::GetLinkImplementationLibraries(
  7391. const std::string& config, LinkInterfaceFor implFor) const
  7392. {
  7393. return this->GetLinkImplementationLibrariesInternal(config, this, implFor);
  7394. }
  7395. cmLinkImplementationLibraries const*
  7396. cmGeneratorTarget::GetLinkImplementationLibrariesInternal(
  7397. const std::string& config, cmGeneratorTarget const* head,
  7398. LinkInterfaceFor implFor) const
  7399. {
  7400. // There is no link implementation for targets that cannot compile sources.
  7401. if (!this->CanCompileSources()) {
  7402. return nullptr;
  7403. }
  7404. // Populate the link implementation libraries for this configuration.
  7405. HeadToLinkImplementationMap& hm =
  7406. (implFor == LinkInterfaceFor::Usage
  7407. ? this->GetHeadToLinkImplementationUsageRequirementsMap(config)
  7408. : this->GetHeadToLinkImplementationMap(config));
  7409. // If the link implementation does not depend on the head target
  7410. // then reuse the one from the head we computed first.
  7411. if (!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition) {
  7412. head = hm.begin()->first;
  7413. }
  7414. cmOptionalLinkImplementation& impl = hm[head];
  7415. if (!impl.LibrariesDone) {
  7416. impl.LibrariesDone = true;
  7417. this->ComputeLinkImplementationLibraries(config, impl, head, implFor);
  7418. }
  7419. return &impl;
  7420. }
  7421. bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
  7422. const std::string& p) const
  7423. {
  7424. return cm::contains(this->LinkImplicitNullProperties, p);
  7425. }
  7426. namespace {
  7427. class TransitiveLinkImpl
  7428. {
  7429. cmGeneratorTarget const* Self;
  7430. std::string const& Config;
  7431. LinkInterfaceFor ImplFor;
  7432. cmLinkImplementation& Impl;
  7433. std::set<cmLinkItem> Emitted;
  7434. std::set<cmLinkItem> Excluded;
  7435. std::unordered_set<cmGeneratorTarget const*> Followed;
  7436. void Follow(cmGeneratorTarget const* target);
  7437. public:
  7438. TransitiveLinkImpl(cmGeneratorTarget const* self, std::string const& config,
  7439. LinkInterfaceFor implFor, cmLinkImplementation& impl)
  7440. : Self(self)
  7441. , Config(config)
  7442. , ImplFor(implFor)
  7443. , Impl(impl)
  7444. {
  7445. }
  7446. void Compute();
  7447. };
  7448. void TransitiveLinkImpl::Follow(cmGeneratorTarget const* target)
  7449. {
  7450. if (!target || !this->Followed.insert(target).second ||
  7451. target->GetPolicyStatusCMP0022() == cmPolicies::OLD ||
  7452. target->GetPolicyStatusCMP0022() == cmPolicies::WARN) {
  7453. return;
  7454. }
  7455. // Get this target's usage requirements.
  7456. cmLinkInterfaceLibraries const* iface =
  7457. target->GetLinkInterfaceLibraries(this->Config, this->Self, this->ImplFor);
  7458. if (!iface) {
  7459. return;
  7460. }
  7461. if (iface->HadContextSensitiveCondition) {
  7462. this->Impl.HadContextSensitiveCondition = true;
  7463. }
  7464. // Process 'INTERFACE_LINK_LIBRARIES_DIRECT' usage requirements.
  7465. for (cmLinkItem const& item : iface->HeadInclude) {
  7466. // Inject direct dependencies from the item's usage requirements
  7467. // before the item itself.
  7468. this->Follow(item.Target);
  7469. // Add the item itself, but at most once.
  7470. if (this->Emitted.insert(item).second) {
  7471. this->Impl.Libraries.emplace_back(item, /* checkCMP0027= */ false);
  7472. }
  7473. }
  7474. // Follow transitive dependencies.
  7475. for (cmLinkItem const& item : iface->Libraries) {
  7476. this->Follow(item.Target);
  7477. }
  7478. // Record exclusions from 'INTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE'
  7479. // usage requirements.
  7480. for (cmLinkItem const& item : iface->HeadExclude) {
  7481. this->Excluded.insert(item);
  7482. }
  7483. }
  7484. void TransitiveLinkImpl::Compute()
  7485. {
  7486. // Save the original items and start with an empty list.
  7487. std::vector<cmLinkImplItem> original = std::move(this->Impl.Libraries);
  7488. // Avoid injecting any original items as usage requirements.
  7489. // This gives LINK_LIBRARIES final control over the order
  7490. // if it explicitly lists everything.
  7491. this->Emitted.insert(original.cbegin(), original.cend());
  7492. // Process each original item.
  7493. for (cmLinkImplItem& item : original) {
  7494. // Inject direct dependencies listed in 'INTERFACE_LINK_LIBRARIES_DIRECT'
  7495. // usage requirements before the item itself.
  7496. this->Follow(item.Target);
  7497. // Add the item itself.
  7498. this->Impl.Libraries.emplace_back(std::move(item));
  7499. }
  7500. // Remove items listed in 'INTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE'
  7501. // usage requirements found through any dependency above.
  7502. this->Impl.Libraries.erase(
  7503. std::remove_if(this->Impl.Libraries.begin(), this->Impl.Libraries.end(),
  7504. [this](cmLinkImplItem const& item) {
  7505. return this->Excluded.find(item) != this->Excluded.end();
  7506. }),
  7507. this->Impl.Libraries.end());
  7508. }
  7509. void ComputeLinkImplTransitive(cmGeneratorTarget const* self,
  7510. std::string const& config,
  7511. LinkInterfaceFor implFor,
  7512. cmLinkImplementation& impl)
  7513. {
  7514. TransitiveLinkImpl transitiveLinkImpl(self, config, implFor, impl);
  7515. transitiveLinkImpl.Compute();
  7516. }
  7517. }
  7518. bool cmGeneratorTarget::ApplyCXXStdTargets()
  7519. {
  7520. cmStandardLevelResolver standardResolver(this->Makefile);
  7521. cmStandardLevel const cxxStd23 =
  7522. *standardResolver.LanguageStandardLevel("CXX", "23");
  7523. std::vector<std::string> const& configs =
  7524. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  7525. auto std_prop = this->GetProperty("CXX_MODULE_STD");
  7526. if (!std_prop) {
  7527. // TODO(cxxmodules): Add a target policy to flip the default here. Set
  7528. // `std_prop` based on it.
  7529. return true;
  7530. }
  7531. std::string std_prop_value;
  7532. if (std_prop) {
  7533. // Evaluate generator expressions.
  7534. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  7535. auto cge = ge.Parse(*std_prop);
  7536. if (!cge) {
  7537. this->Makefile->IssueMessage(
  7538. MessageType::FATAL_ERROR,
  7539. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  7540. this->GetName(), "\" is not a valid generator expression."));
  7541. return false;
  7542. }
  7543. // But do not allow context-sensitive queries. Whether a target uses
  7544. // `import std` should not depend on configuration or properties of the
  7545. // consumer (head target). The link language also shouldn't matter, so ban
  7546. // it as well.
  7547. if (cge->GetHadHeadSensitiveCondition()) {
  7548. // Not reachable; all target-sensitive genexes actually fail to parse.
  7549. this->Makefile->IssueMessage(
  7550. MessageType::FATAL_ERROR,
  7551. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  7552. this->GetName(),
  7553. "\" contains a condition that queries the "
  7554. "consuming target which is not supported."));
  7555. return false;
  7556. }
  7557. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  7558. // Not reachable; all link language genexes actually fail to parse.
  7559. this->Makefile->IssueMessage(
  7560. MessageType::FATAL_ERROR,
  7561. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  7562. this->GetName(),
  7563. "\" contains a condition that queries the "
  7564. "link language which is not supported."));
  7565. return false;
  7566. }
  7567. std_prop_value = cge->Evaluate(this->LocalGenerator, "");
  7568. if (cge->GetHadContextSensitiveCondition()) {
  7569. this->Makefile->IssueMessage(
  7570. MessageType::FATAL_ERROR,
  7571. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  7572. this->GetName(),
  7573. "\" contains a context-sensitive condition "
  7574. "that is not supported."));
  7575. return false;
  7576. }
  7577. }
  7578. auto use_std = cmIsOn(std_prop_value);
  7579. // If we have a value and it is not true, there's nothing to do.
  7580. if (std_prop && !use_std) {
  7581. return true;
  7582. }
  7583. for (auto const& config : configs) {
  7584. if (this->HaveCxxModuleSupport(config) != Cxx20SupportLevel::Supported) {
  7585. continue;
  7586. }
  7587. cm::optional<cmStandardLevel> explicitLevel =
  7588. this->GetExplicitStandardLevel("CXX", config);
  7589. if (!explicitLevel || *explicitLevel < cxxStd23) {
  7590. continue;
  7591. }
  7592. auto const targetName = cmStrCat(
  7593. "__CMAKE::CXX", standardResolver.GetLevelString("CXX", *explicitLevel));
  7594. if (!this->Makefile->FindTargetToUse(targetName)) {
  7595. this->Makefile->IssueMessage(
  7596. MessageType::FATAL_ERROR,
  7597. cmStrCat(
  7598. R"(The "CXX_MODULE_STD" property on the target ")", this->GetName(),
  7599. "\" requires that the \"", targetName,
  7600. "\" target exist, but it was not provided by the toolchain."));
  7601. break;
  7602. }
  7603. // Check the experimental feature here as well. A toolchain may have
  7604. // provided the target and skipped the check in the toolchain preparation
  7605. // logic.
  7606. if (!cmExperimental::HasSupportEnabled(
  7607. *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
  7608. break;
  7609. }
  7610. this->Target->AppendProperty(
  7611. "LINK_LIBRARIES",
  7612. cmStrCat("$<BUILD_LOCAL_INTERFACE:$<$<CONFIG:", config, ">:", targetName,
  7613. ">>"));
  7614. }
  7615. return true;
  7616. }
  7617. bool cmGeneratorTarget::DiscoverSyntheticTargets(cmSyntheticTargetCache& cache,
  7618. std::string const& config)
  7619. {
  7620. std::vector<std::string> allConfigs =
  7621. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  7622. cmOptionalLinkImplementation impl;
  7623. this->ComputeLinkImplementationLibraries(config, impl, this,
  7624. LinkInterfaceFor::Link);
  7625. cmCxxModuleUsageEffects usage(this);
  7626. auto& SyntheticDeps = this->Configs[config].SyntheticDeps;
  7627. for (auto const& entry : impl.Libraries) {
  7628. auto const* gt = entry.Target;
  7629. if (!gt || !gt->IsImported()) {
  7630. continue;
  7631. }
  7632. if (gt->HaveCxx20ModuleSources()) {
  7633. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  7634. constexpr size_t HASH_TRUNCATION = 12;
  7635. auto dirhash = hasher.HashString(
  7636. gt->GetLocalGenerator()->GetCurrentBinaryDirectory());
  7637. std::string safeName = gt->GetName();
  7638. cmSystemTools::ReplaceString(safeName, ":", "_");
  7639. auto targetIdent =
  7640. hasher.HashString(cmStrCat("@d_", dirhash, "@u_", usage.GetHash()));
  7641. std::string targetName =
  7642. cmStrCat(safeName, "@synth_", targetIdent.substr(0, HASH_TRUNCATION));
  7643. // Check the cache to see if this instance of the imported target has
  7644. // already been created.
  7645. auto cached = cache.CxxModuleTargets.find(targetName);
  7646. cmGeneratorTarget const* synthDep = nullptr;
  7647. if (cached == cache.CxxModuleTargets.end()) {
  7648. auto const* model = gt->Target;
  7649. auto* mf = gt->Makefile;
  7650. auto* lg = gt->GetLocalGenerator();
  7651. auto* tgt = mf->AddSynthesizedTarget(cmStateEnums::INTERFACE_LIBRARY,
  7652. targetName);
  7653. // Copy relevant information from the existing IMPORTED target.
  7654. // Copy policies to the target.
  7655. tgt->CopyPolicyStatuses(model);
  7656. // Copy file sets.
  7657. {
  7658. auto fsNames = model->GetAllFileSetNames();
  7659. for (auto const& fsName : fsNames) {
  7660. auto const* fs = model->GetFileSet(fsName);
  7661. if (!fs) {
  7662. mf->IssueMessage(MessageType::INTERNAL_ERROR,
  7663. cmStrCat("Failed to find file set named '",
  7664. fsName, "' on target '",
  7665. tgt->GetName(), '\''));
  7666. continue;
  7667. }
  7668. auto* newFs = tgt
  7669. ->GetOrCreateFileSet(fs->GetName(), fs->GetType(),
  7670. fs->GetVisibility())
  7671. .first;
  7672. newFs->CopyEntries(fs);
  7673. }
  7674. }
  7675. // Copy imported C++ module properties.
  7676. tgt->CopyImportedCxxModulesEntries(model);
  7677. // Copy other properties which may affect the C++ module BMI
  7678. // generation.
  7679. tgt->CopyImportedCxxModulesProperties(model);
  7680. tgt->AddLinkLibrary(*mf,
  7681. cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
  7682. GENERAL_LibraryType);
  7683. // Apply usage requirements to the target.
  7684. usage.ApplyToTarget(tgt);
  7685. // Create the generator target and attach it to the local generator.
  7686. auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
  7687. synthDep = gtp.get();
  7688. cache.CxxModuleTargets[targetName] = synthDep;
  7689. // See `localGen->ComputeTargetCompileFeatures()` call in
  7690. // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
  7691. // this.
  7692. for (auto const& innerConfig : allConfigs) {
  7693. gtp->ComputeCompileFeatures(innerConfig);
  7694. }
  7695. // See `cmGlobalGenerator::ApplyCXXStdTargets` in
  7696. // `cmGlobalGenerator::Compute` for non-synthetic target resolutions.
  7697. gtp->ApplyCXXStdTargets();
  7698. gtp->DiscoverSyntheticTargets(cache, config);
  7699. lg->AddGeneratorTarget(std::move(gtp));
  7700. } else {
  7701. synthDep = cached->second;
  7702. }
  7703. SyntheticDeps[gt].push_back(synthDep);
  7704. }
  7705. }
  7706. return true;
  7707. }
  7708. void cmGeneratorTarget::ComputeLinkImplementationLibraries(
  7709. const std::string& config, cmOptionalLinkImplementation& impl,
  7710. cmGeneratorTarget const* head, LinkInterfaceFor implFor) const
  7711. {
  7712. cmLocalGenerator const* lg = this->LocalGenerator;
  7713. cmMakefile const* mf = lg->GetMakefile();
  7714. cmBTStringRange entryRange = this->Target->GetLinkImplementationEntries();
  7715. auto const& synthTargetsForConfig = this->Configs[config].SyntheticDeps;
  7716. // Collect libraries directly linked in this configuration.
  7717. for (auto const& entry : entryRange) {
  7718. // Keep this logic in sync with ExpandLinkItems.
  7719. cmGeneratorExpressionDAGChecker dagChecker(this, "LINK_LIBRARIES", nullptr,
  7720. nullptr);
  7721. // The $<LINK_ONLY> expression may be used to specify link dependencies
  7722. // that are otherwise excluded from usage requirements.
  7723. if (implFor == LinkInterfaceFor::Usage) {
  7724. dagChecker.SetTransitivePropertiesOnly();
  7725. switch (this->GetPolicyStatusCMP0131()) {
  7726. case cmPolicies::WARN:
  7727. case cmPolicies::OLD:
  7728. break;
  7729. case cmPolicies::REQUIRED_IF_USED:
  7730. case cmPolicies::REQUIRED_ALWAYS:
  7731. case cmPolicies::NEW:
  7732. dagChecker.SetTransitivePropertiesOnlyCMP0131();
  7733. break;
  7734. }
  7735. }
  7736. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance(),
  7737. entry.Backtrace);
  7738. std::unique_ptr<cmCompiledGeneratorExpression> const cge =
  7739. ge.Parse(entry.Value);
  7740. cge->SetEvaluateForBuildsystem(true);
  7741. std::string const& evaluated =
  7742. cge->Evaluate(this->LocalGenerator, config, head, &dagChecker, nullptr,
  7743. this->LinkerLanguage);
  7744. bool const checkCMP0027 = evaluated != entry.Value;
  7745. cmList llibs(evaluated);
  7746. if (cge->GetHadHeadSensitiveCondition()) {
  7747. impl.HadHeadSensitiveCondition = true;
  7748. }
  7749. if (cge->GetHadContextSensitiveCondition()) {
  7750. impl.HadContextSensitiveCondition = true;
  7751. }
  7752. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  7753. impl.HadLinkLanguageSensitiveCondition = true;
  7754. }
  7755. auto linkFeature = cmLinkItem::DEFAULT;
  7756. for (auto const& lib : llibs) {
  7757. if (auto maybeLinkFeature = ParseLinkFeature(lib)) {
  7758. linkFeature = std::move(*maybeLinkFeature);
  7759. continue;
  7760. }
  7761. if (this->IsLinkLookupScope(lib, lg)) {
  7762. continue;
  7763. }
  7764. // Skip entries that resolve to the target itself or are empty.
  7765. std::string name = this->CheckCMP0004(lib);
  7766. if (this->GetPolicyStatusCMP0108() == cmPolicies::NEW) {
  7767. // resolve alias name
  7768. auto* target = this->Makefile->FindTargetToUse(name);
  7769. if (target) {
  7770. name = target->GetName();
  7771. }
  7772. }
  7773. if (name == this->GetName() || name.empty()) {
  7774. if (name == this->GetName()) {
  7775. bool noMessage = false;
  7776. MessageType messageType = MessageType::FATAL_ERROR;
  7777. std::ostringstream e;
  7778. switch (this->GetPolicyStatusCMP0038()) {
  7779. case cmPolicies::WARN: {
  7780. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0038) << "\n";
  7781. messageType = MessageType::AUTHOR_WARNING;
  7782. } break;
  7783. case cmPolicies::OLD:
  7784. noMessage = true;
  7785. break;
  7786. case cmPolicies::REQUIRED_IF_USED:
  7787. case cmPolicies::REQUIRED_ALWAYS:
  7788. case cmPolicies::NEW:
  7789. // Issue the fatal message.
  7790. break;
  7791. }
  7792. if (!noMessage) {
  7793. e << "Target \"" << this->GetName() << "\" links to itself.";
  7794. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  7795. messageType, e.str(), this->GetBacktrace());
  7796. if (messageType == MessageType::FATAL_ERROR) {
  7797. return;
  7798. }
  7799. }
  7800. }
  7801. continue;
  7802. }
  7803. // The entry is meant for this configuration.
  7804. cmLinkItem item = this->ResolveLinkItem(
  7805. BT<std::string>(name, entry.Backtrace), lg, linkFeature);
  7806. if (item.Target) {
  7807. auto depsForTarget = synthTargetsForConfig.find(item.Target);
  7808. if (depsForTarget != synthTargetsForConfig.end()) {
  7809. for (auto const* depForTarget : depsForTarget->second) {
  7810. cmLinkItem synthItem(depForTarget, item.Cross, item.Backtrace);
  7811. impl.Libraries.emplace_back(std::move(synthItem), false);
  7812. }
  7813. }
  7814. } else {
  7815. // Report explicitly linked object files separately.
  7816. std::string const& maybeObj = item.AsStr();
  7817. if (cmSystemTools::FileIsFullPath(maybeObj)) {
  7818. cmSourceFile const* sf =
  7819. mf->GetSource(maybeObj, cmSourceFileLocationKind::Known);
  7820. if (sf && sf->GetPropertyAsBool("EXTERNAL_OBJECT")) {
  7821. item.ObjectSource = sf;
  7822. impl.Objects.emplace_back(std::move(item));
  7823. continue;
  7824. }
  7825. }
  7826. }
  7827. impl.Libraries.emplace_back(std::move(item), checkCMP0027);
  7828. }
  7829. std::set<std::string> const& seenProps = cge->GetSeenTargetProperties();
  7830. for (std::string const& sp : seenProps) {
  7831. if (!this->GetProperty(sp)) {
  7832. this->LinkImplicitNullProperties.insert(sp);
  7833. }
  7834. }
  7835. cge->GetMaxLanguageStandard(this, this->MaxLanguageStandards);
  7836. }
  7837. // Update the list of direct link dependencies from usage requirements.
  7838. if (head == this) {
  7839. ComputeLinkImplTransitive(this, config, implFor, impl);
  7840. }
  7841. // Get the list of configurations considered to be DEBUG.
  7842. std::vector<std::string> debugConfigs =
  7843. this->Makefile->GetCMakeInstance()->GetDebugConfigs();
  7844. cmTargetLinkLibraryType linkType =
  7845. CMP0003_ComputeLinkType(config, debugConfigs);
  7846. cmTarget::LinkLibraryVectorType const& oldllibs =
  7847. this->Target->GetOriginalLinkLibraries();
  7848. auto linkFeature = cmLinkItem::DEFAULT;
  7849. for (cmTarget::LibraryID const& oldllib : oldllibs) {
  7850. if (auto maybeLinkFeature = ParseLinkFeature(oldllib.first)) {
  7851. linkFeature = std::move(*maybeLinkFeature);
  7852. continue;
  7853. }
  7854. if (oldllib.second != GENERAL_LibraryType && oldllib.second != linkType) {
  7855. std::string name = this->CheckCMP0004(oldllib.first);
  7856. if (name == this->GetName() || name.empty()) {
  7857. continue;
  7858. }
  7859. // Support OLD behavior for CMP0003.
  7860. impl.WrongConfigLibraries.push_back(
  7861. this->ResolveLinkItem(BT<std::string>(name), linkFeature));
  7862. }
  7863. }
  7864. }
  7865. cmGeneratorTarget::TargetOrString cmGeneratorTarget::ResolveTargetReference(
  7866. std::string const& name) const
  7867. {
  7868. return this->ResolveTargetReference(name, this->LocalGenerator);
  7869. }
  7870. cmGeneratorTarget::TargetOrString cmGeneratorTarget::ResolveTargetReference(
  7871. std::string const& name, cmLocalGenerator const* lg) const
  7872. {
  7873. TargetOrString resolved;
  7874. if (cmGeneratorTarget* tgt = lg->FindGeneratorTargetToUse(name)) {
  7875. resolved.Target = tgt;
  7876. } else {
  7877. resolved.String = name;
  7878. }
  7879. return resolved;
  7880. }
  7881. cmLinkItem cmGeneratorTarget::ResolveLinkItem(
  7882. BT<std::string> const& name, std::string const& linkFeature) const
  7883. {
  7884. return this->ResolveLinkItem(name, this->LocalGenerator, linkFeature);
  7885. }
  7886. cmLinkItem cmGeneratorTarget::ResolveLinkItem(
  7887. BT<std::string> const& name, cmLocalGenerator const* lg,
  7888. std::string const& linkFeature) const
  7889. {
  7890. auto bt = name.Backtrace;
  7891. TargetOrString resolved = this->ResolveTargetReference(name.Value, lg);
  7892. if (!resolved.Target) {
  7893. return cmLinkItem(resolved.String, false, bt, linkFeature);
  7894. }
  7895. // Check deprecation, issue message with `bt` backtrace.
  7896. if (resolved.Target->IsDeprecated()) {
  7897. std::ostringstream w;
  7898. /* clang-format off */
  7899. w <<
  7900. "The library that is being linked to, " << resolved.Target->GetName() <<
  7901. ", is marked as being deprecated by the owner. The message provided by "
  7902. "the developer is: \n" << resolved.Target->GetDeprecation() << "\n";
  7903. /* clang-format on */
  7904. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  7905. MessageType::AUTHOR_WARNING, w.str(), bt);
  7906. }
  7907. // Skip targets that will not really be linked. This is probably a
  7908. // name conflict between an external library and an executable
  7909. // within the project.
  7910. if (resolved.Target->GetType() == cmStateEnums::EXECUTABLE &&
  7911. !resolved.Target->IsExecutableWithExports()) {
  7912. return cmLinkItem(resolved.Target->GetName(), false, bt, linkFeature);
  7913. }
  7914. return cmLinkItem(resolved.Target, false, bt, linkFeature);
  7915. }
  7916. bool cmGeneratorTarget::HasPackageReferences() const
  7917. {
  7918. return this->IsInBuildSystem() &&
  7919. !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
  7920. }
  7921. std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
  7922. {
  7923. cmList packageReferences;
  7924. if (this->IsInBuildSystem()) {
  7925. if (cmValue vsPackageReferences =
  7926. this->GetProperty("VS_PACKAGE_REFERENCES")) {
  7927. packageReferences.assign(*vsPackageReferences);
  7928. }
  7929. }
  7930. return std::move(packageReferences.data());
  7931. }
  7932. std::string cmGeneratorTarget::GetPDBDirectory(const std::string& config) const
  7933. {
  7934. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  7935. // Return the directory in which the target will be built.
  7936. return info->PdbDir;
  7937. }
  7938. return "";
  7939. }
  7940. bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
  7941. {
  7942. return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
  7943. }
  7944. bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
  7945. std::string const& gnuName,
  7946. std::string& out,
  7947. const char* newExt) const
  7948. {
  7949. if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
  7950. gnuName.substr(gnuName.size() - 6) == ".dll.a") {
  7951. out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
  7952. newExt ? newExt : ".lib");
  7953. return true;
  7954. }
  7955. return false;
  7956. }
  7957. bool cmGeneratorTarget::HasContextDependentSources() const
  7958. {
  7959. return this->SourcesAreContextDependent == Tribool::True;
  7960. }
  7961. bool cmGeneratorTarget::IsExecutableWithExports() const
  7962. {
  7963. return this->Target->IsExecutableWithExports();
  7964. }
  7965. bool cmGeneratorTarget::IsSharedLibraryWithExports() const
  7966. {
  7967. return this->Target->IsSharedLibraryWithExports();
  7968. }
  7969. bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
  7970. {
  7971. bool generate_Stubs = true;
  7972. if (this->GetGlobalGenerator()->IsXcode()) {
  7973. // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
  7974. // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
  7975. if (cmValue propGenStubs =
  7976. this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  7977. generate_Stubs = propGenStubs == "YES";
  7978. } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
  7979. "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  7980. generate_Stubs = varGenStubs == "YES";
  7981. }
  7982. }
  7983. return (this->IsDLLPlatform() &&
  7984. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  7985. this->IsExecutableWithExports()) &&
  7986. // Assemblies which have only managed code do not have
  7987. // import libraries.
  7988. this->GetManagedType(config) != ManagedType::Managed) ||
  7989. (this->IsAIX() && this->IsExecutableWithExports()) ||
  7990. (this->Makefile->PlatformSupportsAppleTextStubs() &&
  7991. this->IsSharedLibraryWithExports() && generate_Stubs);
  7992. }
  7993. bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
  7994. {
  7995. return this->HasImportLibrary(config) ||
  7996. // On DLL platforms we always generate the import library name
  7997. // just in case the sources have export markup.
  7998. (this->IsDLLPlatform() &&
  7999. (this->GetType() == cmStateEnums::EXECUTABLE ||
  8000. this->GetType() == cmStateEnums::MODULE_LIBRARY));
  8001. }
  8002. std::string cmGeneratorTarget::GetSupportDirectory() const
  8003. {
  8004. std::string dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  8005. "/CMakeFiles/", this->GetName());
  8006. #if defined(__VMS)
  8007. dir += "_dir";
  8008. #else
  8009. dir += ".dir";
  8010. #endif
  8011. return dir;
  8012. }
  8013. bool cmGeneratorTarget::IsLinkable() const
  8014. {
  8015. return (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  8016. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  8017. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  8018. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY ||
  8019. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  8020. this->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  8021. this->IsExecutableWithExports());
  8022. }
  8023. bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
  8024. {
  8025. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  8026. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  8027. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  8028. return false;
  8029. }
  8030. if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
  8031. // Do not use the linker dependency file because it includes shared
  8032. // libraries as well
  8033. return false;
  8034. }
  8035. const std::string depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
  8036. auto linkLanguage = this->GetLinkerLanguage(config);
  8037. const std::string langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
  8038. "_LINK_DEPENDS_USE_LINKER") };
  8039. return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
  8040. this->Makefile->IsOn(depsUseLinker)) &&
  8041. this->Makefile->IsOn(langDepsUseLinker);
  8042. }
  8043. bool cmGeneratorTarget::IsFrameworkOnApple() const
  8044. {
  8045. return this->Target->IsFrameworkOnApple();
  8046. }
  8047. bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
  8048. const std::string& config) const
  8049. {
  8050. if (this->IsApple() && this->IsImported() &&
  8051. (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  8052. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  8053. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) {
  8054. std::string cfg = config;
  8055. if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
  8056. // FIXME(#25515): Remove the need for this workaround.
  8057. // The Xcode generator queries include directories without any
  8058. // specific configuration. Pick one in case this target does
  8059. // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
  8060. cfg =
  8061. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
  8062. }
  8063. return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
  8064. }
  8065. return false;
  8066. }
  8067. bool cmGeneratorTarget::IsAppBundleOnApple() const
  8068. {
  8069. return this->Target->IsAppBundleOnApple();
  8070. }
  8071. bool cmGeneratorTarget::IsXCTestOnApple() const
  8072. {
  8073. return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
  8074. }
  8075. bool cmGeneratorTarget::IsCFBundleOnApple() const
  8076. {
  8077. return (this->GetType() == cmStateEnums::MODULE_LIBRARY && this->IsApple() &&
  8078. this->GetPropertyAsBool("BUNDLE"));
  8079. }
  8080. cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
  8081. std::string const& propval) const
  8082. {
  8083. // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
  8084. // or only C++/CLI) does only depend on whether the property is an empty
  8085. // string or contains any value at all. In Visual Studio generators
  8086. // this propval is prepended with /clr[:] which results in:
  8087. //
  8088. // 1. propval does not exist: no /clr flag, unmanaged target, has import
  8089. // lib
  8090. // 2. empty propval: add /clr as flag, mixed unmanaged/managed
  8091. // target, has import lib
  8092. // 3. netcore propval: add /clr:netcore as flag, mixed
  8093. // unmanaged/managed target, has import lib.
  8094. // 4. any value (safe,pure): add /clr:[propval] as flag, target with
  8095. // managed code only, no import lib
  8096. if (propval.empty() || propval == "netcore") {
  8097. return ManagedType::Mixed;
  8098. }
  8099. return ManagedType::Managed;
  8100. }
  8101. cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
  8102. const std::string& config) const
  8103. {
  8104. // Only libraries and executables can be managed targets.
  8105. if (this->GetType() > cmStateEnums::SHARED_LIBRARY) {
  8106. return ManagedType::Undefined;
  8107. }
  8108. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  8109. return ManagedType::Native;
  8110. }
  8111. // Check imported target.
  8112. if (this->IsImported()) {
  8113. if (cmGeneratorTarget::ImportInfo const* info =
  8114. this->GetImportInfo(config)) {
  8115. return info->Managed;
  8116. }
  8117. return ManagedType::Undefined;
  8118. }
  8119. // Check for explicitly set clr target property.
  8120. if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  8121. return this->CheckManagedType(*clr);
  8122. }
  8123. // C# targets are always managed. This language specific check
  8124. // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
  8125. // has to be set manually for C# targets.
  8126. return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
  8127. }
  8128. bool cmGeneratorTarget::AddHeaderSetVerification()
  8129. {
  8130. if (!this->GetPropertyAsBool("VERIFY_INTERFACE_HEADER_SETS")) {
  8131. return true;
  8132. }
  8133. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  8134. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  8135. this->GetType() != cmStateEnums::UNKNOWN_LIBRARY &&
  8136. this->GetType() != cmStateEnums::OBJECT_LIBRARY &&
  8137. this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  8138. !this->IsExecutableWithExports()) {
  8139. return true;
  8140. }
  8141. auto verifyValue = this->GetProperty("INTERFACE_HEADER_SETS_TO_VERIFY");
  8142. const bool all = verifyValue.IsEmpty();
  8143. std::set<std::string> verifySet;
  8144. if (!all) {
  8145. cmList verifyList{ verifyValue };
  8146. verifySet.insert(verifyList.begin(), verifyList.end());
  8147. }
  8148. cmTarget* verifyTarget = nullptr;
  8149. cmTarget* allVerifyTarget =
  8150. this->GlobalGenerator->GetMakefiles().front()->FindTargetToUse(
  8151. "all_verify_interface_header_sets", true);
  8152. auto interfaceFileSetEntries = this->Target->GetInterfaceHeaderSetsEntries();
  8153. std::set<cmFileSet*> fileSets;
  8154. for (auto const& entry : interfaceFileSetEntries) {
  8155. for (auto const& name : cmList{ entry.Value }) {
  8156. if (all || verifySet.count(name)) {
  8157. fileSets.insert(this->Target->GetFileSet(name));
  8158. verifySet.erase(name);
  8159. }
  8160. }
  8161. }
  8162. if (!verifySet.empty()) {
  8163. this->Makefile->IssueMessage(
  8164. MessageType::FATAL_ERROR,
  8165. cmStrCat("Property INTERFACE_HEADER_SETS_TO_VERIFY of target \"",
  8166. this->GetName(),
  8167. "\" contained the following header sets that are nonexistent "
  8168. "or not INTERFACE:\n ",
  8169. cmJoin(verifySet, "\n ")));
  8170. return false;
  8171. }
  8172. cm::optional<std::set<std::string>> languages;
  8173. for (auto* fileSet : fileSets) {
  8174. auto dirCges = fileSet->CompileDirectoryEntries();
  8175. auto fileCges = fileSet->CompileFileEntries();
  8176. static auto const contextSensitive =
  8177. [](const std::unique_ptr<cmCompiledGeneratorExpression>& cge) {
  8178. return cge->GetHadContextSensitiveCondition();
  8179. };
  8180. bool dirCgesContextSensitive = false;
  8181. bool fileCgesContextSensitive = false;
  8182. std::vector<std::string> dirs;
  8183. std::map<std::string, std::vector<std::string>> filesPerDir;
  8184. bool first = true;
  8185. for (auto const& config : this->Makefile->GetGeneratorConfigs(
  8186. cmMakefile::GeneratorConfigQuery::IncludeEmptyConfig)) {
  8187. if (first || dirCgesContextSensitive) {
  8188. dirs = fileSet->EvaluateDirectoryEntries(dirCges, this->LocalGenerator,
  8189. config, this);
  8190. dirCgesContextSensitive =
  8191. std::any_of(dirCges.begin(), dirCges.end(), contextSensitive);
  8192. }
  8193. if (first || fileCgesContextSensitive) {
  8194. filesPerDir.clear();
  8195. for (auto const& fileCge : fileCges) {
  8196. fileSet->EvaluateFileEntry(dirs, filesPerDir, fileCge,
  8197. this->LocalGenerator, config, this);
  8198. if (fileCge->GetHadContextSensitiveCondition()) {
  8199. fileCgesContextSensitive = true;
  8200. }
  8201. }
  8202. }
  8203. for (auto const& files : filesPerDir) {
  8204. for (auto const& file : files.second) {
  8205. std::string filename = this->GenerateHeaderSetVerificationFile(
  8206. *this->Makefile->GetOrCreateSource(file), files.first, languages);
  8207. if (filename.empty()) {
  8208. continue;
  8209. }
  8210. if (!verifyTarget) {
  8211. {
  8212. cmMakefile::PolicyPushPop polScope(this->Makefile);
  8213. this->Makefile->SetPolicy(cmPolicies::CMP0119, cmPolicies::NEW);
  8214. verifyTarget = this->Makefile->AddLibrary(
  8215. cmStrCat(this->GetName(), "_verify_interface_header_sets"),
  8216. cmStateEnums::OBJECT_LIBRARY, {}, true);
  8217. }
  8218. verifyTarget->AddLinkLibrary(
  8219. *this->Makefile, this->GetName(),
  8220. cmTargetLinkLibraryType::GENERAL_LibraryType);
  8221. verifyTarget->SetProperty("AUTOMOC", "OFF");
  8222. verifyTarget->SetProperty("AUTORCC", "OFF");
  8223. verifyTarget->SetProperty("AUTOUIC", "OFF");
  8224. verifyTarget->SetProperty("DISABLE_PRECOMPILE_HEADERS", "ON");
  8225. verifyTarget->SetProperty("UNITY_BUILD", "OFF");
  8226. verifyTarget->SetProperty("CXX_SCAN_FOR_MODULES", "OFF");
  8227. cm::optional<std::map<std::string, cmValue>>
  8228. perConfigCompileDefinitions;
  8229. verifyTarget->FinalizeTargetConfiguration(
  8230. this->Makefile->GetCompileDefinitionsEntries(),
  8231. perConfigCompileDefinitions);
  8232. if (!allVerifyTarget) {
  8233. allVerifyTarget = this->GlobalGenerator->GetMakefiles()
  8234. .front()
  8235. ->AddNewUtilityTarget(
  8236. "all_verify_interface_header_sets", true);
  8237. }
  8238. allVerifyTarget->AddUtility(verifyTarget->GetName(), false);
  8239. }
  8240. if (fileCgesContextSensitive) {
  8241. filename = cmStrCat("$<$<CONFIG:", config, ">:", filename, ">");
  8242. }
  8243. verifyTarget->AddSource(filename);
  8244. }
  8245. }
  8246. if (!dirCgesContextSensitive && !fileCgesContextSensitive) {
  8247. break;
  8248. }
  8249. first = false;
  8250. }
  8251. }
  8252. if (verifyTarget) {
  8253. this->LocalGenerator->AddGeneratorTarget(
  8254. cm::make_unique<cmGeneratorTarget>(verifyTarget, this->LocalGenerator));
  8255. }
  8256. return true;
  8257. }
  8258. std::string cmGeneratorTarget::GenerateHeaderSetVerificationFile(
  8259. cmSourceFile& source, const std::string& dir,
  8260. cm::optional<std::set<std::string>>& languages) const
  8261. {
  8262. std::string extension;
  8263. std::string language = source.GetOrDetermineLanguage();
  8264. if (source.GetPropertyAsBool("SKIP_LINTING")) {
  8265. return std::string{};
  8266. }
  8267. if (language.empty()) {
  8268. if (!languages) {
  8269. languages.emplace();
  8270. for (auto const& tgtSource : this->GetAllConfigSources()) {
  8271. auto const& tgtSourceLanguage =
  8272. tgtSource.Source->GetOrDetermineLanguage();
  8273. if (tgtSourceLanguage == "CXX") {
  8274. languages->insert("CXX");
  8275. break; // C++ overrides everything else, so we don't need to keep
  8276. // checking.
  8277. }
  8278. if (tgtSourceLanguage == "C") {
  8279. languages->insert("C");
  8280. }
  8281. }
  8282. if (languages->empty()) {
  8283. std::vector<std::string> languagesVector;
  8284. this->GlobalGenerator->GetEnabledLanguages(languagesVector);
  8285. languages->insert(languagesVector.begin(), languagesVector.end());
  8286. }
  8287. }
  8288. if (languages->count("CXX")) {
  8289. language = "CXX";
  8290. } else if (languages->count("C")) {
  8291. language = "C";
  8292. }
  8293. }
  8294. if (language == "C") {
  8295. extension = ".c";
  8296. } else if (language == "CXX") {
  8297. extension = ".cxx";
  8298. } else {
  8299. return "";
  8300. }
  8301. std::string headerFilename = dir;
  8302. if (!headerFilename.empty()) {
  8303. headerFilename += '/';
  8304. }
  8305. headerFilename += source.GetLocation().GetName();
  8306. auto filename = cmStrCat(
  8307. this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->GetName(),
  8308. "_verify_interface_header_sets/", headerFilename, extension);
  8309. auto* verificationSource = this->Makefile->GetOrCreateSource(filename);
  8310. verificationSource->SetProperty("LANGUAGE", language);
  8311. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(filename));
  8312. cmGeneratedFileStream fout(filename);
  8313. fout.SetCopyIfDifferent(true);
  8314. // The IWYU "associated" pragma tells include-what-you-use to
  8315. // consider the headerFile as part of the entire language
  8316. // unit within include-what-you-use and as a result allows
  8317. // one to get IWYU advice for headers.
  8318. // Also suppress clang-tidy include checks in generated code.
  8319. fout
  8320. << "/* NOLINTNEXTLINE(misc-header-include-cycle,misc-include-cleaner) */\n"
  8321. << "#include <" << headerFilename << "> /* IWYU pragma: associated */\n";
  8322. fout.close();
  8323. return filename;
  8324. }
  8325. std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
  8326. const std::string& config) const
  8327. {
  8328. if (!(this->IsApple() && this->IsImported() &&
  8329. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  8330. this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  8331. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY))) {
  8332. return {};
  8333. }
  8334. std::string desiredConfig = config;
  8335. if (config.empty()) {
  8336. desiredConfig = "NOCONFIG";
  8337. }
  8338. std::string result;
  8339. cmValue loc = nullptr;
  8340. cmValue imp = nullptr;
  8341. std::string suffix;
  8342. if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
  8343. if (loc) {
  8344. result = *loc;
  8345. } else {
  8346. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  8347. if (cmValue configLocation = this->GetProperty(impProp)) {
  8348. result = *configLocation;
  8349. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  8350. result = *location;
  8351. }
  8352. }
  8353. if (cmSystemTools::IsPathToXcFramework(result)) {
  8354. return result;
  8355. }
  8356. }
  8357. return {};
  8358. }
  8359. bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
  8360. {
  8361. auto sources = this->GetSourceFiles(config);
  8362. bool const have_direct = std::any_of(
  8363. sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
  8364. return sf.Value->GetLanguage() == "Fortran"_s;
  8365. });
  8366. bool have_via_target_objects = false;
  8367. if (!have_direct) {
  8368. auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
  8369. have_via_target_objects =
  8370. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  8371. [&config](cmGeneratorTarget const* tgt) -> bool {
  8372. return tgt->HaveFortranSources(config);
  8373. });
  8374. }
  8375. return have_direct || have_via_target_objects;
  8376. }
  8377. bool cmGeneratorTarget::HaveFortranSources() const
  8378. {
  8379. auto sources = this->GetAllConfigSources();
  8380. bool const have_direct = std::any_of(
  8381. sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
  8382. return sf.Source->GetLanguage() == "Fortran"_s;
  8383. });
  8384. bool have_via_target_objects = false;
  8385. if (!have_direct) {
  8386. std::vector<std::string> configs =
  8387. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  8388. for (auto const& config : configs) {
  8389. auto const sourceObjectLibraries =
  8390. this->GetSourceObjectLibraries(config);
  8391. have_via_target_objects =
  8392. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  8393. [&config](cmGeneratorTarget const* tgt) -> bool {
  8394. return tgt->HaveFortranSources(config);
  8395. });
  8396. if (have_via_target_objects) {
  8397. break;
  8398. }
  8399. }
  8400. }
  8401. return have_direct || have_via_target_objects;
  8402. }
  8403. bool cmGeneratorTarget::HaveCxx20ModuleSources(std::string* errorMessage) const
  8404. {
  8405. auto const& fs_names = this->Target->GetAllFileSetNames();
  8406. return std::any_of(
  8407. fs_names.begin(), fs_names.end(),
  8408. [this, errorMessage](std::string const& name) -> bool {
  8409. auto const* file_set = this->Target->GetFileSet(name);
  8410. if (!file_set) {
  8411. auto message = cmStrCat("Target \"", this->Target->GetName(),
  8412. "\" is tracked to have file set \"", name,
  8413. "\", but it was not found.");
  8414. if (errorMessage) {
  8415. *errorMessage = std::move(message);
  8416. } else {
  8417. this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
  8418. }
  8419. return false;
  8420. }
  8421. auto const& fs_type = file_set->GetType();
  8422. return fs_type == "CXX_MODULES"_s;
  8423. });
  8424. }
  8425. cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
  8426. std::string const& config) const
  8427. {
  8428. auto const* state = this->Makefile->GetState();
  8429. if (!state->GetLanguageEnabled("CXX")) {
  8430. return Cxx20SupportLevel::MissingCxx;
  8431. }
  8432. cmValue standardDefault =
  8433. this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  8434. if (!standardDefault || standardDefault->empty()) {
  8435. // We do not know any meaningful C++ standard levels for this compiler.
  8436. return Cxx20SupportLevel::NoCxx20;
  8437. }
  8438. cmStandardLevelResolver standardResolver(this->Makefile);
  8439. cmStandardLevel const cxxStd20 =
  8440. *standardResolver.LanguageStandardLevel("CXX", "20");
  8441. cm::optional<cmStandardLevel> explicitLevel =
  8442. this->GetExplicitStandardLevel("CXX", config);
  8443. if (!explicitLevel || *explicitLevel < cxxStd20) {
  8444. return Cxx20SupportLevel::NoCxx20;
  8445. }
  8446. cmValue scandepRule =
  8447. this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
  8448. if (!scandepRule) {
  8449. return Cxx20SupportLevel::MissingRule;
  8450. }
  8451. return Cxx20SupportLevel::Supported;
  8452. }
  8453. void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
  8454. {
  8455. bool haveScannableSources = false;
  8456. // Check for `CXX_MODULE*` file sets and a lack of support.
  8457. if (this->HaveCxx20ModuleSources()) {
  8458. haveScannableSources = true;
  8459. }
  8460. if (!haveScannableSources) {
  8461. // Check to see if there are regular sources that have requested scanning.
  8462. auto sources = this->GetSourceFiles(config);
  8463. for (auto const& source : sources) {
  8464. auto const* sf = source.Value;
  8465. auto const& lang = sf->GetLanguage();
  8466. if (lang != "CXX"_s) {
  8467. continue;
  8468. }
  8469. // Ignore sources which do not need dyndep.
  8470. if (this->NeedDyndepForSource(lang, config, sf)) {
  8471. haveScannableSources = true;
  8472. }
  8473. }
  8474. }
  8475. // If there isn't anything scannable, ignore it.
  8476. if (!haveScannableSources) {
  8477. return;
  8478. }
  8479. // If the generator doesn't support modules at all, error that we have
  8480. // sources that require the support.
  8481. if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
  8482. cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
  8483. this->Makefile->IssueMessage(
  8484. MessageType::FATAL_ERROR,
  8485. cmStrCat("The target named \"", this->GetName(),
  8486. "\" has C++ sources that may use modules, but modules are not "
  8487. "supported by this generator:\n ",
  8488. this->GetGlobalGenerator()->GetName(), '\n',
  8489. "Modules are supported only by Ninja, Ninja Multi-Config, "
  8490. "and Visual Studio generators for VS 17.4 and newer. "
  8491. "See the cmake-cxxmodules(7) manual for details. "
  8492. "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
  8493. "disable scanning."));
  8494. return;
  8495. }
  8496. switch (this->HaveCxxModuleSupport(config)) {
  8497. case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
  8498. this->Makefile->IssueMessage(
  8499. MessageType::FATAL_ERROR,
  8500. cmStrCat("The target named \"", this->GetName(),
  8501. "\" has C++ sources that use modules, but the \"CXX\" "
  8502. "language has not been enabled."));
  8503. break;
  8504. case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
  8505. cmStandardLevelResolver standardResolver(this->Makefile);
  8506. auto effStandard =
  8507. standardResolver.GetEffectiveStandard(this, "CXX", config);
  8508. if (effStandard.empty()) {
  8509. effStandard = "; no C++ standard found";
  8510. } else {
  8511. effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
  8512. }
  8513. this->Makefile->IssueMessage(
  8514. MessageType::FATAL_ERROR,
  8515. cmStrCat(
  8516. "The target named \"", this->GetName(),
  8517. "\" has C++ sources that use modules, but does not include "
  8518. "\"cxx_std_20\" (or newer) among its `target_compile_features`",
  8519. effStandard, '.'));
  8520. } break;
  8521. case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
  8522. this->Makefile->IssueMessage(
  8523. MessageType::FATAL_ERROR,
  8524. cmStrCat("The target named \"", this->GetName(),
  8525. "\" has C++ sources that may use modules, but the compiler "
  8526. "does not provide a way to discover the import graph "
  8527. "dependencies. See the cmake-cxxmodules(7) manual for "
  8528. "details. Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
  8529. "enable or disable scanning."));
  8530. } break;
  8531. case cmGeneratorTarget::Cxx20SupportLevel::Supported:
  8532. // All is well.
  8533. break;
  8534. }
  8535. }
  8536. bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
  8537. std::string const& config) const
  8538. {
  8539. if (lang != "CXX"_s) {
  8540. return false;
  8541. }
  8542. return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
  8543. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  8544. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  8545. }
  8546. bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
  8547. std::string const& config) const
  8548. {
  8549. return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
  8550. }
  8551. cmFileSet const* cmGeneratorTarget::GetFileSetForSource(
  8552. std::string const& config, cmSourceFile const* sf) const
  8553. {
  8554. this->BuildFileSetInfoCache(config);
  8555. auto const& path = sf->GetFullPath();
  8556. auto const& per_config = this->Configs[config];
  8557. auto const fsit = per_config.FileSetCache.find(path);
  8558. if (fsit == per_config.FileSetCache.end()) {
  8559. return nullptr;
  8560. }
  8561. return fsit->second;
  8562. }
  8563. bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
  8564. std::string const& config,
  8565. cmSourceFile const* sf) const
  8566. {
  8567. // Fortran always needs to be scanned.
  8568. if (lang == "Fortran"_s) {
  8569. return true;
  8570. }
  8571. // Only C++ code needs scanned otherwise.
  8572. if (lang != "CXX"_s) {
  8573. return false;
  8574. }
  8575. // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
  8576. // enforced elsewhere).
  8577. auto const* fs = this->GetFileSetForSource(config, sf);
  8578. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  8579. return true;
  8580. }
  8581. bool haveRule = false;
  8582. switch (this->HaveCxxModuleSupport(config)) {
  8583. case Cxx20SupportLevel::MissingCxx:
  8584. case Cxx20SupportLevel::NoCxx20:
  8585. return false;
  8586. case Cxx20SupportLevel::MissingRule:
  8587. break;
  8588. case Cxx20SupportLevel::Supported:
  8589. haveRule = true;
  8590. break;
  8591. }
  8592. bool haveGeneratorSupport =
  8593. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  8594. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  8595. auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
  8596. if (sfProp.IsSet()) {
  8597. return sfProp.IsOn();
  8598. }
  8599. auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
  8600. if (tgtProp.IsSet()) {
  8601. return tgtProp.IsOn();
  8602. }
  8603. bool policyAnswer = false;
  8604. switch (this->GetPolicyStatusCMP0155()) {
  8605. case cmPolicies::WARN:
  8606. case cmPolicies::OLD:
  8607. // The OLD behavior is to not scan the source.
  8608. policyAnswer = false;
  8609. break;
  8610. case cmPolicies::REQUIRED_ALWAYS:
  8611. case cmPolicies::REQUIRED_IF_USED:
  8612. case cmPolicies::NEW:
  8613. // The NEW behavior is to scan the source if the compiler supports
  8614. // scanning and the generator supports it.
  8615. policyAnswer = haveRule && haveGeneratorSupport;
  8616. break;
  8617. }
  8618. return policyAnswer;
  8619. }
  8620. void cmGeneratorTarget::BuildFileSetInfoCache(std::string const& config) const
  8621. {
  8622. auto& per_config = this->Configs[config];
  8623. if (per_config.BuiltFileSetCache) {
  8624. return;
  8625. }
  8626. auto const* tgt = this->Target;
  8627. for (auto const& name : tgt->GetAllFileSetNames()) {
  8628. auto const* file_set = tgt->GetFileSet(name);
  8629. if (!file_set) {
  8630. tgt->GetMakefile()->IssueMessage(
  8631. MessageType::INTERNAL_ERROR,
  8632. cmStrCat("Target \"", tgt->GetName(),
  8633. "\" is tracked to have file set \"", name,
  8634. "\", but it was not found."));
  8635. continue;
  8636. }
  8637. auto fileEntries = file_set->CompileFileEntries();
  8638. auto directoryEntries = file_set->CompileDirectoryEntries();
  8639. auto directories = file_set->EvaluateDirectoryEntries(
  8640. directoryEntries, this->LocalGenerator, config, this);
  8641. std::map<std::string, std::vector<std::string>> files;
  8642. for (auto const& entry : fileEntries) {
  8643. file_set->EvaluateFileEntry(directories, files, entry,
  8644. this->LocalGenerator, config, this);
  8645. }
  8646. for (auto const& it : files) {
  8647. for (auto const& filename : it.second) {
  8648. auto collapsedFile = cmSystemTools::CollapseFullPath(filename);
  8649. per_config.FileSetCache[collapsedFile] = file_set;
  8650. }
  8651. }
  8652. }
  8653. per_config.BuiltFileSetCache = true;
  8654. }