cmLocalGenerator.cxx 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmLocalGenerator.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <initializer_list>
  11. #include <iterator>
  12. #include <sstream>
  13. #include <type_traits>
  14. #include <unordered_set>
  15. #include <utility>
  16. #include <vector>
  17. #include <cm/memory>
  18. #include <cm/optional>
  19. #include <cm/string_view>
  20. #include <cmext/algorithm>
  21. #include <cmext/string_view>
  22. #include "cmsys/RegularExpression.hxx"
  23. #include "cmAlgorithms.h"
  24. #include "cmCMakePath.h"
  25. #include "cmComputeLinkInformation.h"
  26. #include "cmCryptoHash.h"
  27. #include "cmCustomCommand.h"
  28. #include "cmCustomCommandGenerator.h"
  29. #include "cmCustomCommandLines.h"
  30. #include "cmCustomCommandTypes.h"
  31. #include "cmGeneratedFileStream.h"
  32. #include "cmGeneratorExpression.h"
  33. #include "cmGeneratorExpressionEvaluationFile.h"
  34. #include "cmGeneratorTarget.h"
  35. #include "cmGlobalGenerator.h"
  36. #include "cmInstallGenerator.h"
  37. #include "cmInstallScriptGenerator.h"
  38. #include "cmInstallTargetGenerator.h"
  39. #include "cmLinkLineComputer.h"
  40. #include "cmLinkLineDeviceComputer.h"
  41. #include "cmList.h"
  42. #include "cmMakefile.h"
  43. #include "cmMessageType.h"
  44. #include "cmObjectLocation.h"
  45. #include "cmRange.h"
  46. #include "cmRulePlaceholderExpander.h"
  47. #include "cmSourceFile.h"
  48. #include "cmSourceFileLocation.h"
  49. #include "cmSourceFileLocationKind.h"
  50. #include "cmStandardLevelResolver.h"
  51. #include "cmState.h"
  52. #include "cmStateDirectory.h"
  53. #include "cmStateTypes.h"
  54. #include "cmStringAlgorithms.h"
  55. #include "cmSystemTools.h"
  56. #include "cmTarget.h"
  57. #include "cmTestGenerator.h"
  58. #include "cmValue.h"
  59. #include "cmake.h"
  60. #if defined(__HAIKU__)
  61. # include <FindDirectory.h>
  62. # include <StorageDefs.h>
  63. #endif
  64. namespace {
  65. // List of variables that are replaced when
  66. // rules are expanded. These variables are
  67. // replaced in the form <var> with GetSafeDefinition(var).
  68. // ${LANG} is replaced in the variable first with all enabled
  69. // languages.
  70. auto ruleReplaceVars = {
  71. "CMAKE_${LANG}_COMPILER",
  72. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  73. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  74. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  75. "CMAKE_${LANG}_ARCHIVE",
  76. "CMAKE_AR",
  77. "CMAKE_SOURCE_DIR",
  78. "CMAKE_BINARY_DIR",
  79. "CMAKE_CURRENT_SOURCE_DIR",
  80. "CMAKE_CURRENT_BINARY_DIR",
  81. "CMAKE_RANLIB",
  82. "CMAKE_MT",
  83. "CMAKE_TAPI",
  84. "CMAKE_CUDA_HOST_COMPILER",
  85. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  86. "CMAKE_HIP_HOST_COMPILER",
  87. "CMAKE_HIP_HOST_LINK_LAUNCHER",
  88. "CMAKE_CL_SHOWINCLUDES_PREFIX",
  89. };
  90. // Variables whose placeholders now map to an empty string.
  91. // Our platform modules no longer use these, but third-party code might.
  92. auto ruleReplaceEmptyVars = {
  93. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  94. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  95. "CMAKE_${LANG}_LINK_FLAGS",
  96. };
  97. }
  98. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  99. : cmOutputConverter(makefile->GetStateSnapshot())
  100. , DirectoryBacktrace(makefile->GetBacktrace())
  101. {
  102. this->GlobalGenerator = gg;
  103. this->Makefile = makefile;
  104. this->AliasTargets = makefile->GetAliasTargets();
  105. this->EmitUniversalBinaryFlags = true;
  106. this->ComputeObjectMaxPath();
  107. // Canonicalize entries of the CPATH environment variable the same
  108. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  109. {
  110. std::vector<std::string> cpath;
  111. cmSystemTools::GetPath(cpath, "CPATH");
  112. for (std::string const& cp : cpath) {
  113. if (cmSystemTools::FileIsFullPath(cp)) {
  114. this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
  115. }
  116. }
  117. }
  118. std::vector<std::string> enabledLanguages =
  119. this->GetState()->GetEnabledLanguages();
  120. if (cmValue sysrootCompile =
  121. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  122. this->CompilerSysroot = *sysrootCompile;
  123. } else {
  124. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  125. }
  126. if (cmValue sysrootLink =
  127. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  128. this->LinkerSysroot = *sysrootLink;
  129. } else {
  130. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  131. }
  132. // OSX SYSROOT can be required by some tools, like tapi
  133. {
  134. cmValue osxSysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  135. this->VariableMappings["CMAKE_OSX_SYSROOT"] =
  136. osxSysroot.IsEmpty() ? "/" : this->EscapeForShell(*osxSysroot, true);
  137. }
  138. if (cmValue appleArchSysroots =
  139. this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
  140. std::string const& appleArchs =
  141. this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  142. cmList archs(appleArchs);
  143. cmList sysroots{ appleArchSysroots, cmList::EmptyElements::Yes };
  144. if (archs.size() == sysroots.size()) {
  145. for (cmList::size_type i = 0; i < archs.size(); ++i) {
  146. this->AppleArchSysroots[archs[i]] = sysroots[i];
  147. }
  148. } else {
  149. std::string const e =
  150. cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n ", *appleArchSysroots,
  151. "\n"
  152. "is not the same length as CMAKE_OSX_ARCHITECTURES:\n ",
  153. appleArchs);
  154. this->IssueMessage(MessageType::FATAL_ERROR, e);
  155. }
  156. }
  157. for (std::string const& lang : enabledLanguages) {
  158. if (lang == "NONE") {
  159. continue;
  160. }
  161. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  162. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  163. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  164. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  165. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  166. std::string const& compilerOptionTarget =
  167. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  168. std::string const& compilerExternalToolchain =
  169. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  170. std::string const& compilerOptionExternalToolchain =
  171. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  172. std::string const& compilerOptionSysroot =
  173. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  174. this->VariableMappings[compilerArg1] =
  175. this->Makefile->GetSafeDefinition(compilerArg1);
  176. this->VariableMappings[compilerTarget] =
  177. this->Makefile->GetSafeDefinition(compilerTarget);
  178. this->VariableMappings[compilerOptionTarget] =
  179. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  180. this->VariableMappings[compilerExternalToolchain] =
  181. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  182. this->VariableMappings[compilerOptionExternalToolchain] =
  183. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  184. this->VariableMappings[compilerOptionSysroot] =
  185. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  186. for (std::string replaceVar : ruleReplaceVars) {
  187. if (replaceVar.find("${LANG}") != std::string::npos) {
  188. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  189. }
  190. this->VariableMappings[replaceVar] =
  191. this->Makefile->GetSafeDefinition(replaceVar);
  192. }
  193. for (std::string replaceVar : ruleReplaceEmptyVars) {
  194. if (replaceVar.find("${LANG}") != std::string::npos) {
  195. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  196. }
  197. this->VariableMappings[replaceVar] = std::string();
  198. }
  199. }
  200. }
  201. std::unique_ptr<cmRulePlaceholderExpander>
  202. cmLocalGenerator::CreateRulePlaceholderExpander(cmBuildStep buildStep) const
  203. {
  204. return cm::make_unique<cmRulePlaceholderExpander>(
  205. buildStep, this->Compilers, this->VariableMappings, this->CompilerSysroot,
  206. this->LinkerSysroot);
  207. }
  208. cmLocalGenerator::~cmLocalGenerator() = default;
  209. void cmLocalGenerator::IssueMessage(MessageType t,
  210. std::string const& text) const
  211. {
  212. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  213. }
  214. void cmLocalGenerator::ComputeObjectMaxPath()
  215. {
  216. // Choose a maximum object file name length.
  217. #if defined(_WIN32) || defined(__CYGWIN__)
  218. this->ObjectPathMax = 250;
  219. #else
  220. this->ObjectPathMax = 1000;
  221. #endif
  222. cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  223. if (cmNonempty(plen)) {
  224. unsigned int pmax;
  225. if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
  226. if (pmax >= 128) {
  227. this->ObjectPathMax = pmax;
  228. } else {
  229. std::ostringstream w;
  230. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  231. << ", which is less than the minimum of 128. "
  232. "The value will be ignored.";
  233. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  234. }
  235. } else {
  236. std::ostringstream w;
  237. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
  238. << "\", which fails to parse as a positive integer. "
  239. "The value will be ignored.";
  240. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  241. }
  242. }
  243. this->ObjectMaxPathViolations.clear();
  244. }
  245. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  246. std::string const& config,
  247. std::string const& lang,
  248. cmGeneratorTarget const* target)
  249. {
  250. if (!target) {
  251. return;
  252. }
  253. std::stable_sort(
  254. includeDirs.begin(), includeDirs.end(),
  255. [&target, &config, &lang](std::string const& a, std::string const& b) {
  256. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  257. target->IsSystemIncludeDirectory(b, config, lang);
  258. });
  259. }
  260. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  261. std::string const& config,
  262. std::string const& lang,
  263. cmGeneratorTarget const* target)
  264. {
  265. if (!target) {
  266. return;
  267. }
  268. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  269. [target, &config, &lang](BT<std::string> const& a,
  270. BT<std::string> const& b) {
  271. return !target->IsSystemIncludeDirectory(a.Value, config,
  272. lang) &&
  273. target->IsSystemIncludeDirectory(b.Value, config, lang);
  274. });
  275. }
  276. void cmLocalGenerator::TraceDependencies() const
  277. {
  278. // Generate the rule files for each target.
  279. auto const& targets = this->GetGeneratorTargets();
  280. for (auto const& target : targets) {
  281. if (!target->IsInBuildSystem()) {
  282. continue;
  283. }
  284. target->TraceDependencies();
  285. }
  286. }
  287. void cmLocalGenerator::GenerateTestFiles()
  288. {
  289. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  290. return;
  291. }
  292. // Compute the set of configurations.
  293. std::vector<std::string> configurationTypes =
  294. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  295. std::string config = this->Makefile->GetDefaultConfiguration();
  296. std::string file =
  297. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  298. "/CTestTestfile.cmake");
  299. this->GlobalGenerator->AddTestFile(file);
  300. cmGeneratedFileStream fout(file);
  301. fout << "# CMake generated Testfile for \n"
  302. "# Source directory: "
  303. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  304. << "\n"
  305. "# Build directory: "
  306. << this->StateSnapshot.GetDirectory().GetCurrentBinary()
  307. << "\n"
  308. "# \n"
  309. "# This file includes the relevant testing commands "
  310. "required for \n"
  311. "# testing this directory and lists subdirectories to "
  312. "be tested as well.\n";
  313. std::string resourceSpecFile =
  314. this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
  315. if (!resourceSpecFile.empty()) {
  316. fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
  317. }
  318. cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  319. if (testIncludeFile) {
  320. fout << "include(\"" << *testIncludeFile << "\")\n";
  321. }
  322. cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  323. if (testIncludeFiles) {
  324. cmList includesList{ *testIncludeFiles };
  325. for (std::string const& i : includesList) {
  326. fout << "include(\"" << i << "\")\n";
  327. }
  328. }
  329. // Ask each test generator to write its code.
  330. for (auto const& tester : this->Makefile->GetTestGenerators()) {
  331. tester->Compute(this);
  332. tester->Generate(fout, config, configurationTypes);
  333. }
  334. using vec_t = std::vector<cmStateSnapshot>;
  335. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  336. for (cmStateSnapshot const& i : children) {
  337. // TODO: Use add_subdirectory instead?
  338. std::string outP = i.GetDirectory().GetCurrentBinary();
  339. outP = this->MaybeRelativeToCurBinDir(outP);
  340. outP = cmOutputConverter::EscapeForCMake(outP);
  341. fout << "subdirs(" << outP << ")\n";
  342. }
  343. // Add directory labels property
  344. cmValue directoryLabels =
  345. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  346. cmValue labels = this->Makefile->GetProperty("LABELS");
  347. if (labels || directoryLabels) {
  348. fout << "set_directory_properties(PROPERTIES LABELS ";
  349. if (labels) {
  350. fout << cmOutputConverter::EscapeForCMake(*labels);
  351. }
  352. if (labels && directoryLabels) {
  353. fout << ";";
  354. }
  355. if (directoryLabels) {
  356. fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
  357. }
  358. fout << ")\n";
  359. }
  360. }
  361. void cmLocalGenerator::CreateEvaluationFileOutputs()
  362. {
  363. std::vector<std::string> const& configs =
  364. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  365. for (std::string const& c : configs) {
  366. this->CreateEvaluationFileOutputs(c);
  367. }
  368. }
  369. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  370. {
  371. for (auto const& geef : this->Makefile->GetEvaluationFiles()) {
  372. geef->CreateOutputFile(this, config);
  373. }
  374. }
  375. void cmLocalGenerator::ProcessEvaluationFiles(
  376. std::vector<std::string>& generatedFiles)
  377. {
  378. for (auto const& geef : this->Makefile->GetEvaluationFiles()) {
  379. geef->Generate(this);
  380. if (cmSystemTools::GetFatalErrorOccurred()) {
  381. return;
  382. }
  383. std::vector<std::string> files = geef->GetFiles();
  384. std::sort(files.begin(), files.end());
  385. std::vector<std::string> intersection;
  386. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  387. generatedFiles.end(),
  388. std::back_inserter(intersection));
  389. if (!intersection.empty()) {
  390. cmSystemTools::Error("Files to be generated by multiple different "
  391. "commands: " +
  392. cmWrap('"', intersection, '"', " "));
  393. return;
  394. }
  395. cm::append(generatedFiles, files);
  396. std::inplace_merge(generatedFiles.begin(),
  397. generatedFiles.end() - files.size(),
  398. generatedFiles.end());
  399. }
  400. }
  401. void cmLocalGenerator::GenerateInstallRules()
  402. {
  403. // Compute the install prefix.
  404. cmValue installPrefix =
  405. this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  406. std::string prefix = *installPrefix;
  407. #if defined(_WIN32) && !defined(__CYGWIN__)
  408. if (!installPrefix) {
  409. if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
  410. prefix = "C:";
  411. }
  412. cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  413. if (cmNonempty(project_name)) {
  414. prefix += "/Program Files/";
  415. prefix += *project_name;
  416. } else {
  417. prefix += "/InstalledCMakeProject";
  418. }
  419. }
  420. #elif defined(__HAIKU__)
  421. char dir[B_PATH_NAME_LENGTH];
  422. if (!installPrefix) {
  423. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  424. B_OK) {
  425. prefix = dir;
  426. } else {
  427. prefix = "/boot/system";
  428. }
  429. }
  430. #else
  431. if (!installPrefix) {
  432. prefix = "/usr/local";
  433. }
  434. #endif
  435. if (cmValue stagingPrefix =
  436. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  437. prefix = *stagingPrefix;
  438. }
  439. // Compute the set of configurations.
  440. std::vector<std::string> configurationTypes =
  441. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  442. std::string config = this->Makefile->GetDefaultConfiguration();
  443. // Choose a default install configuration.
  444. std::string default_config = config;
  445. char const* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  446. "DEBUG", nullptr };
  447. for (char const** c = default_order; *c && default_config.empty(); ++c) {
  448. for (std::string const& configurationType : configurationTypes) {
  449. if (cmSystemTools::UpperCase(configurationType) == *c) {
  450. default_config = configurationType;
  451. }
  452. }
  453. }
  454. if (default_config.empty() && !configurationTypes.empty()) {
  455. default_config = configurationTypes[0];
  456. }
  457. // Create the install script file.
  458. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  459. std::string homedir = this->GetState()->GetBinaryDirectory();
  460. int toplevel_install = 0;
  461. if (file == homedir) {
  462. toplevel_install = 1;
  463. }
  464. file += "/cmake_install.cmake";
  465. this->GetGlobalGenerator()->AddInstallScript(file);
  466. cmGeneratedFileStream fout(file);
  467. // Write the header.
  468. /* clang-format off */
  469. fout << "# Install script for directory: "
  470. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  471. << "\n\n"
  472. "# Set the install prefix\n"
  473. "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
  474. " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
  475. "endif()\n"
  476. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  477. << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
  478. /* clang-format on */
  479. // Write support code for generating per-configuration install rules.
  480. /* clang-format off */
  481. fout <<
  482. "# Set the install configuration name.\n"
  483. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  484. " if(BUILD_TYPE)\n"
  485. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  486. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  487. " else()\n"
  488. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  489. " endif()\n"
  490. " message(STATUS \"Install configuration: "
  491. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  492. "endif()\n"
  493. "\n";
  494. /* clang-format on */
  495. // Write support code for dealing with component-specific installs.
  496. /* clang-format off */
  497. fout <<
  498. "# Set the component getting installed.\n"
  499. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  500. " if(COMPONENT)\n"
  501. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  502. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  503. " else()\n"
  504. " set(CMAKE_INSTALL_COMPONENT)\n"
  505. " endif()\n"
  506. "endif()\n"
  507. "\n";
  508. /* clang-format on */
  509. // Copy user-specified install options to the install code.
  510. if (cmValue so_no_exe =
  511. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  512. /* clang-format off */
  513. fout <<
  514. "# Install shared libraries without execute permission?\n"
  515. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  516. " set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
  517. "endif()\n"
  518. "\n";
  519. /* clang-format on */
  520. }
  521. // Copy cmake cross compile state to install code.
  522. if (cmValue crosscompiling =
  523. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  524. /* clang-format off */
  525. fout <<
  526. "# Is this installation the result of a crosscompile?\n"
  527. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  528. " set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
  529. "endif()\n"
  530. "\n";
  531. /* clang-format on */
  532. }
  533. // Write default directory permissions.
  534. if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
  535. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  536. /* clang-format off */
  537. fout <<
  538. "# Set default install directory permissions.\n"
  539. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  540. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  541. << *defaultDirPermissions << "\")\n"
  542. "endif()\n"
  543. "\n";
  544. /* clang-format on */
  545. }
  546. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
  547. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  548. // has same platform variable as when running cmake
  549. if (cmValue platform = this->Makefile->GetDefinition(
  550. "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
  551. /* clang-format off */
  552. fout <<
  553. "# Set OS and executable format for runtime-dependencies.\n"
  554. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
  555. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
  556. << *platform << "\")\n"
  557. "endif()\n"
  558. "\n";
  559. /* clang-format on */
  560. }
  561. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
  562. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  563. // has same tool selected as when running cmake
  564. if (cmValue command =
  565. this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
  566. /* clang-format off */
  567. fout <<
  568. "# Set tool for dependency-resolution of runtime-dependencies.\n"
  569. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
  570. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
  571. << *command << "\")\n"
  572. "endif()\n"
  573. "\n";
  574. /* clang-format on */
  575. }
  576. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
  577. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  578. // has same path to the tool as when running cmake
  579. if (cmValue command = this->Makefile->GetDefinition(
  580. "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
  581. /* clang-format off */
  582. fout <<
  583. "# Set path to tool for dependency-resolution of runtime-dependencies.\n"
  584. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
  585. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
  586. << *command << "\")\n"
  587. "endif()\n"
  588. "\n";
  589. /* clang-format on */
  590. }
  591. // Write out CMAKE_OBJDUMP so that installed code that uses
  592. // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
  593. // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
  594. // logic to fallback to CMAKE_OBJDUMP when `objdump` is
  595. // not on the path
  596. if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
  597. /* clang-format off */
  598. fout <<
  599. "# Set path to fallback-tool for dependency-resolution.\n"
  600. "if(NOT DEFINED CMAKE_OBJDUMP)\n"
  601. " set(CMAKE_OBJDUMP \""
  602. << *command << "\")\n"
  603. "endif()\n"
  604. "\n";
  605. /* clang-format on */
  606. }
  607. this->AddGeneratorSpecificInstallSetup(fout);
  608. // Ask each install generator to write its code.
  609. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  610. auto const& installers = this->Makefile->GetInstallGenerators();
  611. bool haveSubdirectoryInstall = false;
  612. bool haveInstallAfterSubdirectory = false;
  613. if (status == cmPolicies::WARN) {
  614. for (auto const& installer : installers) {
  615. installer->CheckCMP0082(haveSubdirectoryInstall,
  616. haveInstallAfterSubdirectory);
  617. installer->Generate(fout, config, configurationTypes);
  618. }
  619. } else {
  620. for (auto const& installer : installers) {
  621. installer->Generate(fout, config, configurationTypes);
  622. }
  623. }
  624. // Write rules from old-style specification stored in targets.
  625. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  626. // Include install scripts from subdirectories.
  627. switch (status) {
  628. case cmPolicies::WARN:
  629. if (haveInstallAfterSubdirectory &&
  630. this->Makefile->PolicyOptionalWarningEnabled(
  631. "CMAKE_POLICY_WARNING_CMP0082")) {
  632. std::ostringstream e;
  633. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  634. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  635. }
  636. CM_FALLTHROUGH;
  637. case cmPolicies::OLD: {
  638. std::vector<cmStateSnapshot> children =
  639. this->Makefile->GetStateSnapshot().GetChildren();
  640. if (!children.empty()) {
  641. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  642. fout << " # Include the install script for each subdirectory.\n";
  643. for (cmStateSnapshot const& c : children) {
  644. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  645. std::string odir = c.GetDirectory().GetCurrentBinary();
  646. cmSystemTools::ConvertToUnixSlashes(odir);
  647. fout << " include(\"" << odir << "/cmake_install.cmake\")\n";
  648. }
  649. }
  650. fout << "\n";
  651. fout << "endif()\n\n";
  652. }
  653. } break;
  654. case cmPolicies::NEW:
  655. // NEW behavior is handled in
  656. // cmInstallSubdirectoryGenerator::GenerateScript()
  657. break;
  658. }
  659. /* clang-format off */
  660. fout <<
  661. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  662. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  663. "if(CMAKE_INSTALL_LOCAL_ONLY)\n"
  664. " file(WRITE \"" <<
  665. this->StateSnapshot.GetDirectory().GetCurrentBinary() <<
  666. "/install_local_manifest.txt\"\n"
  667. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
  668. "endif()\n";
  669. if (toplevel_install) {
  670. fout <<
  671. "if(CMAKE_INSTALL_COMPONENT)\n"
  672. " if(CMAKE_INSTALL_COMPONENT MATCHES \"^[a-zA-Z0-9_.+-]+$\")\n"
  673. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  674. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  675. " else()\n"
  676. " string(MD5 CMAKE_INST_COMP_HASH \"${CMAKE_INSTALL_COMPONENT}\")\n"
  677. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  678. "${CMAKE_INST_COMP_HASH}.txt\")\n"
  679. " unset(CMAKE_INST_COMP_HASH)\n"
  680. " endif()\n"
  681. "else()\n"
  682. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  683. "endif()\n"
  684. "\n"
  685. "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n"
  686. " file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  687. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
  688. "endif()\n";
  689. }
  690. /* clang-format on */
  691. }
  692. void cmLocalGenerator::AddGeneratorTarget(
  693. std::unique_ptr<cmGeneratorTarget> gt)
  694. {
  695. cmGeneratorTarget* gt_ptr = gt.get();
  696. this->GeneratorTargets.push_back(std::move(gt));
  697. this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
  698. this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
  699. }
  700. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  701. {
  702. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  703. this->GlobalGenerator->IndexGeneratorTarget(gt);
  704. }
  705. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
  706. std::unique_ptr<cmGeneratorTarget> gt)
  707. {
  708. this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
  709. }
  710. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  711. std::string const& name) const
  712. {
  713. auto ti = this->GeneratorTargetSearchIndex.find(name);
  714. if (ti != this->GeneratorTargetSearchIndex.end()) {
  715. return ti->second;
  716. }
  717. return nullptr;
  718. }
  719. void cmLocalGenerator::ComputeTargetManifest()
  720. {
  721. // Collect the set of configuration types.
  722. std::vector<std::string> configNames =
  723. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  724. // Add our targets to the manifest for each configuration.
  725. auto const& targets = this->GetGeneratorTargets();
  726. for (auto const& target : targets) {
  727. if (!target->IsInBuildSystem()) {
  728. continue;
  729. }
  730. for (std::string const& c : configNames) {
  731. target->ComputeTargetManifest(c);
  732. }
  733. }
  734. }
  735. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  736. {
  737. // Collect the set of configuration types.
  738. std::vector<std::string> configNames =
  739. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  740. using LanguagePair = std::pair<std::string, std::string>;
  741. std::vector<LanguagePair> pairedLanguages{
  742. { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
  743. };
  744. std::set<LanguagePair> inferredEnabledLanguages;
  745. for (auto const& lang : pairedLanguages) {
  746. if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
  747. inferredEnabledLanguages.insert(lang);
  748. }
  749. }
  750. // Process compile features of all targets.
  751. auto const& targets = this->GetGeneratorTargets();
  752. for (auto const& target : targets) {
  753. for (std::string const& c : configNames) {
  754. if (!target->ComputeCompileFeatures(c)) {
  755. return false;
  756. }
  757. }
  758. // Now that C/C++ _STANDARD values have been computed
  759. // set the values to ObjC/ObjCXX _STANDARD variables
  760. if (target->CanCompileSources()) {
  761. for (std::string const& c : configNames) {
  762. target->ComputeCompileFeatures(c, inferredEnabledLanguages);
  763. }
  764. }
  765. }
  766. return true;
  767. }
  768. bool cmLocalGenerator::IsRootMakefile() const
  769. {
  770. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  771. }
  772. cmState* cmLocalGenerator::GetState() const
  773. {
  774. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  775. }
  776. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  777. {
  778. return this->Makefile->GetStateSnapshot();
  779. }
  780. std::string cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  781. std::string const& prop,
  782. std::string const& config)
  783. {
  784. cmValue value = this->Makefile->GetProperty(prop);
  785. if (target) {
  786. value = target->GetProperty(prop);
  787. }
  788. if (value) {
  789. return cmGeneratorExpression::Evaluate(*value, this, config, target);
  790. }
  791. return "";
  792. }
  793. std::string cmLocalGenerator::ConvertToIncludeReference(
  794. std::string const& path, OutputFormat format)
  795. {
  796. return this->ConvertToOutputForExisting(path, format);
  797. }
  798. std::string cmLocalGenerator::GetIncludeFlags(
  799. std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
  800. std::string const& lang, std::string const& config, bool forResponseFile)
  801. {
  802. if (lang.empty()) {
  803. return "";
  804. }
  805. std::vector<std::string> includes = includeDirs;
  806. MoveSystemIncludesToEnd(includes, config, lang, target);
  807. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  808. std::ostringstream includeFlags;
  809. std::string const& includeFlag =
  810. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  811. bool quotePaths = false;
  812. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  813. quotePaths = true;
  814. }
  815. std::string sep = " ";
  816. bool repeatFlag = true;
  817. // should the include flag be repeated like ie. -IA -IB
  818. if (cmValue incSep = this->Makefile->GetDefinition(
  819. cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
  820. // if there is a separator then the flag is not repeated but is only
  821. // given once i.e. -classpath a:b:c
  822. sep = *incSep;
  823. repeatFlag = false;
  824. }
  825. // Support special system include flag if it is available and the
  826. // normal flag is repeated for each directory.
  827. cmValue sysIncludeFlag = nullptr;
  828. cmValue sysIncludeFlagWarning = nullptr;
  829. if (repeatFlag) {
  830. sysIncludeFlag = this->Makefile->GetDefinition(
  831. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  832. sysIncludeFlagWarning = this->Makefile->GetDefinition(
  833. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
  834. }
  835. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  836. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  837. cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
  838. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  839. bool flagUsed = false;
  840. bool sysIncludeFlagUsed = false;
  841. std::set<std::string> emitted;
  842. #ifdef __APPLE__
  843. emitted.insert("/System/Library/Frameworks");
  844. #endif
  845. for (std::string const& i : includes) {
  846. if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
  847. cmSystemTools::IsPathToFramework(i)) {
  848. std::string const frameworkDir = cmSystemTools::GetFilenamePath(i);
  849. if (emitted.insert(frameworkDir).second) {
  850. if (sysFwSearchFlag && target &&
  851. target->IsSystemIncludeDirectory(frameworkDir, config, lang)) {
  852. includeFlags << *sysFwSearchFlag;
  853. } else {
  854. includeFlags << *fwSearchFlag;
  855. }
  856. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  857. << " ";
  858. }
  859. continue;
  860. }
  861. if (!flagUsed || repeatFlag) {
  862. if (sysIncludeFlag && target &&
  863. target->IsSystemIncludeDirectory(i, config, lang)) {
  864. includeFlags << *sysIncludeFlag;
  865. sysIncludeFlagUsed = true;
  866. } else {
  867. includeFlags << includeFlag;
  868. }
  869. flagUsed = true;
  870. }
  871. std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
  872. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  873. includeFlags << "\"";
  874. }
  875. includeFlags << includePath;
  876. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  877. includeFlags << "\"";
  878. }
  879. includeFlags << sep;
  880. }
  881. if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
  882. includeFlags << *sysIncludeFlagWarning;
  883. }
  884. std::string flags = includeFlags.str();
  885. // remove trailing separators
  886. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  887. flags.back() = ' ';
  888. }
  889. return cmTrimWhitespace(flags);
  890. }
  891. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  892. cmGeneratorTarget* target,
  893. std::string const& lang,
  894. std::string const& config)
  895. {
  896. std::vector<BT<std::string>> tmpFlags;
  897. this->AddCompileOptions(tmpFlags, target, lang, config);
  898. this->AppendFlags(flags, tmpFlags);
  899. }
  900. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  901. cmGeneratorTarget* target,
  902. std::string const& lang,
  903. std::string const& config)
  904. {
  905. std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
  906. if (cmValue langFlagRegexStr =
  907. this->Makefile->GetDefinition(langFlagRegexVar)) {
  908. // Filter flags acceptable to this language.
  909. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  910. std::vector<std::string> opts;
  911. cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
  912. // Re-escape these flags since COMPILE_FLAGS were already parsed
  913. // as a command line above.
  914. std::string compileOpts;
  915. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
  916. if (!compileOpts.empty()) {
  917. flags.emplace_back(std::move(compileOpts));
  918. }
  919. }
  920. std::vector<BT<std::string>> targetCompileOpts =
  921. target->GetCompileOptions(config, lang);
  922. // COMPILE_OPTIONS are escaped.
  923. this->AppendCompileOptions(flags, targetCompileOpts,
  924. langFlagRegexStr->c_str());
  925. } else {
  926. // Use all flags.
  927. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  928. // COMPILE_FLAGS are not escaped for historical reasons.
  929. std::string compileFlags;
  930. this->AppendFlags(compileFlags, *targetFlags);
  931. if (!compileFlags.empty()) {
  932. flags.emplace_back(std::move(compileFlags));
  933. }
  934. }
  935. std::vector<BT<std::string>> targetCompileOpts =
  936. target->GetCompileOptions(config, lang);
  937. // COMPILE_OPTIONS are escaped.
  938. this->AppendCompileOptions(flags, targetCompileOpts);
  939. }
  940. cmStandardLevelResolver standardResolver(this->Makefile);
  941. for (auto const& it : target->GetMaxLanguageStandards()) {
  942. cmValue standard = target->GetLanguageStandard(it.first, config);
  943. if (!standard) {
  944. continue;
  945. }
  946. if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
  947. std::ostringstream e;
  948. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  949. << "\" was evaluated when computing the link "
  950. "implementation, and the \""
  951. << it.first << "_STANDARD\" was \"" << it.second
  952. << "\" for that computation. Computing the "
  953. "COMPILE_FEATURES based on the link implementation resulted in a "
  954. "higher \""
  955. << it.first << "_STANDARD\" \"" << *standard
  956. << "\". "
  957. "This is not permitted. The COMPILE_FEATURES may not both depend "
  958. "on "
  959. "and be depended on by the link implementation.\n";
  960. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  961. return;
  962. }
  963. }
  964. // Add Warning as errors flags
  965. if (!this->GetCMakeInstance()->GetIgnoreCompileWarningAsError()) {
  966. cmValue const wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
  967. cmValue const wErrorOpts = this->Makefile->GetDefinition(
  968. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
  969. if (wError.IsOn() && wErrorOpts.IsSet()) {
  970. std::string wErrorFlags;
  971. this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
  972. if (!wErrorFlags.empty()) {
  973. flags.emplace_back(std::move(wErrorFlags));
  974. }
  975. }
  976. }
  977. // Add compile flag for the MSVC compiler only.
  978. cmMakefile* mf = this->GetMakefile();
  979. if (cmValue jmc =
  980. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  981. // Handle Just My Code debugging flags, /JMC.
  982. // If the target is a Managed C++ one, /JMC is not compatible.
  983. if (target->GetManagedType(config) !=
  984. cmGeneratorTarget::ManagedType::Managed) {
  985. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  986. // to ON
  987. if (cmValue jmcExprGen =
  988. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  989. std::string isJMCEnabled =
  990. cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
  991. if (cmIsOn(isJMCEnabled)) {
  992. cmList optList{ *jmc };
  993. std::string jmcFlags;
  994. this->AppendCompileOptions(jmcFlags, optList);
  995. if (!jmcFlags.empty()) {
  996. flags.emplace_back(std::move(jmcFlags));
  997. }
  998. }
  999. }
  1000. }
  1001. }
  1002. }
  1003. cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
  1004. std::string const& target, cmCustomCommandType type,
  1005. std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
  1006. {
  1007. cmTarget* t = this->Makefile->GetCustomCommandTarget(
  1008. target, objLibCommands, this->DirectoryBacktrace);
  1009. if (!t) {
  1010. return nullptr;
  1011. }
  1012. cc->SetBacktrace(this->DirectoryBacktrace);
  1013. detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
  1014. std::move(cc));
  1015. return t;
  1016. }
  1017. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  1018. std::unique_ptr<cmCustomCommand> cc, bool replace)
  1019. {
  1020. // Make sure there is at least one output.
  1021. if (cc->GetOutputs().empty()) {
  1022. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  1023. return nullptr;
  1024. }
  1025. cc->SetBacktrace(this->DirectoryBacktrace);
  1026. return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
  1027. std::move(cc), replace);
  1028. }
  1029. cmTarget* cmLocalGenerator::AddUtilityCommand(
  1030. std::string const& utilityName, bool excludeFromAll,
  1031. std::unique_ptr<cmCustomCommand> cc)
  1032. {
  1033. cmTarget* target =
  1034. this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
  1035. target->SetIsGeneratorProvided(true);
  1036. if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
  1037. return target;
  1038. }
  1039. cc->SetBacktrace(this->DirectoryBacktrace);
  1040. detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
  1041. std::move(cc));
  1042. return target;
  1043. }
  1044. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1045. cmGeneratorTarget const* target, std::string const& lang,
  1046. std::string const& config, bool stripImplicitDirs,
  1047. bool appendAllImplicitDirs) const
  1048. {
  1049. std::vector<BT<std::string>> result;
  1050. // Do not repeat an include path.
  1051. std::set<std::string> emitted;
  1052. auto emitDir = [&result, &emitted](std::string const& dir) {
  1053. if (emitted.insert(dir).second) {
  1054. result.emplace_back(dir);
  1055. }
  1056. };
  1057. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  1058. if (emitted.insert(dir.Value).second) {
  1059. result.emplace_back(dir);
  1060. }
  1061. };
  1062. // When automatic include directories are requested for a build then
  1063. // include the source and binary directories at the beginning of the
  1064. // include path to approximate include file behavior for an
  1065. // in-source build. This does not account for the case of a source
  1066. // file in a subdirectory of the current source directory but we
  1067. // cannot fix this because not all native build tools support
  1068. // per-source-file include paths.
  1069. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  1070. // Current binary directory
  1071. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  1072. // Current source directory
  1073. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  1074. }
  1075. if (!target) {
  1076. return result;
  1077. }
  1078. // Standard include directories to be added unconditionally at the end.
  1079. // These are intended to simulate additional implicit include directories.
  1080. cmList userStandardDirs;
  1081. {
  1082. std::string const value = this->Makefile->GetSafeDefinition(
  1083. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  1084. userStandardDirs.assign(value);
  1085. for (std::string& usd : userStandardDirs) {
  1086. cmSystemTools::ConvertToUnixSlashes(usd);
  1087. }
  1088. }
  1089. // Implicit include directories
  1090. std::vector<std::string> implicitDirs;
  1091. std::set<std::string> implicitSet;
  1092. // Include directories to be excluded as if they were implicit.
  1093. std::set<std::string> implicitExclude;
  1094. {
  1095. // Raw list of implicit include directories
  1096. // Start with "standard" directories that we unconditionally add below.
  1097. std::vector<std::string> impDirVec = userStandardDirs;
  1098. // Load implicit include directories for this language.
  1099. // We ignore this for Fortran because:
  1100. // * There are no standard library headers to avoid overriding.
  1101. // * Compilers like gfortran do not search their own implicit include
  1102. // directories for modules ('.mod' files).
  1103. if (lang != "Fortran") {
  1104. size_t const impDirVecOldSize = impDirVec.size();
  1105. cmList::append(impDirVec,
  1106. this->Makefile->GetDefinition(cmStrCat(
  1107. "CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES")));
  1108. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  1109. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  1110. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  1111. }
  1112. // The CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES are computed using
  1113. // try_compile in CMAKE_DETERMINE_COMPILER_ABI, but the implicit include
  1114. // directories are not known during that try_compile. This can be a
  1115. // problem when the HIP runtime include path is /usr/include because the
  1116. // runtime include path is always added to the userDirs and the compiler
  1117. // includes standard library headers via "__clang_hip_runtime_wrapper.h".
  1118. if (lang == "HIP" && impDirVec.size() == impDirVecOldSize &&
  1119. !cm::contains(impDirVec, "/usr/include")) {
  1120. implicitExclude.emplace("/usr/include");
  1121. }
  1122. }
  1123. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  1124. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  1125. // variables are now computed. On macOS the /usr/include directory is
  1126. // inside the platform SDK so the computed value does not contain it
  1127. // directly. In this case adding -I/usr/include can hide SDK headers so we
  1128. // must still exclude it.
  1129. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  1130. !cm::contains(impDirVec, "/usr/include") &&
  1131. std::find_if(impDirVec.begin(), impDirVec.end(),
  1132. [](std::string const& d) {
  1133. return cmHasLiteralSuffix(d, "/usr/include");
  1134. }) != impDirVec.end()) {
  1135. // Only exclude this hard coded path for backwards compatibility.
  1136. implicitExclude.emplace("/usr/include");
  1137. }
  1138. for (std::string const& i : impDirVec) {
  1139. if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
  1140. implicitDirs.emplace_back(i);
  1141. }
  1142. }
  1143. }
  1144. bool const isCorCxx = (lang == "C" || lang == "CXX");
  1145. // Resolve symlinks in CPATH for comparison with resolved include paths.
  1146. // We do this here instead of when EnvCPATH is populated in case symlinks
  1147. // on disk have changed in the meantime.
  1148. std::set<std::string> resolvedEnvCPATH;
  1149. if (isCorCxx) {
  1150. for (std::string const& i : this->EnvCPATH) {
  1151. resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
  1152. }
  1153. }
  1154. // Checks if this is not an excluded (implicit) include directory.
  1155. auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
  1156. isCorCxx](std::string const& dir) -> bool {
  1157. std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
  1158. return
  1159. // Do not exclude directories that are not in any excluded set.
  1160. !(cm::contains(implicitSet, real_dir) ||
  1161. cm::contains(implicitExclude, dir))
  1162. // Do not exclude entries of the CPATH environment variable even though
  1163. // they are implicitly searched by the compiler. They are meant to be
  1164. // user-specified directories that can be re-ordered or converted to
  1165. // -isystem without breaking real compiler builtin headers.
  1166. || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
  1167. };
  1168. // Get the target-specific include directories.
  1169. std::vector<BT<std::string>> userDirs =
  1170. target->GetIncludeDirectories(config, lang);
  1171. // Support putting all the in-project include directories first if
  1172. // it is requested by the project.
  1173. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  1174. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  1175. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  1176. for (BT<std::string> const& udr : userDirs) {
  1177. // Emit this directory only if it is a subdirectory of the
  1178. // top-level source or binary tree.
  1179. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  1180. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  1181. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  1182. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  1183. if (notExcluded(udr.Value)) {
  1184. emitBT(udr);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. // Emit remaining non implicit user directories.
  1190. for (BT<std::string> const& udr : userDirs) {
  1191. if (notExcluded(udr.Value)) {
  1192. emitBT(udr);
  1193. }
  1194. }
  1195. // Sort result
  1196. MoveSystemIncludesToEnd(result, config, lang, target);
  1197. // Append standard include directories for this language.
  1198. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  1199. for (std::string& usd : userStandardDirs) {
  1200. emitDir(usd);
  1201. userDirs.emplace_back(std::move(usd));
  1202. }
  1203. // Append compiler implicit include directories
  1204. if (!stripImplicitDirs) {
  1205. // Append implicit directories that were requested by the user only
  1206. for (BT<std::string> const& udr : userDirs) {
  1207. if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  1208. emitBT(udr);
  1209. }
  1210. }
  1211. // Append remaining implicit directories (on demand)
  1212. if (appendAllImplicitDirs) {
  1213. for (std::string& imd : implicitDirs) {
  1214. emitDir(imd);
  1215. }
  1216. }
  1217. }
  1218. return result;
  1219. }
  1220. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1221. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1222. std::string const& lang, std::string const& config, bool stripImplicitDirs,
  1223. bool appendAllImplicitDirs) const
  1224. {
  1225. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1226. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1227. dirs.reserve(dirs.size() + tmp.size());
  1228. for (BT<std::string>& v : tmp) {
  1229. dirs.emplace_back(std::move(v.Value));
  1230. }
  1231. }
  1232. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1233. cmGeneratorTarget const* target, std::string const& lang,
  1234. std::string const& config) const
  1235. {
  1236. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1237. }
  1238. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1239. cmGeneratorTarget const* target,
  1240. std::string const& lang,
  1241. std::string const& config) const
  1242. {
  1243. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1244. }
  1245. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1246. std::string const& config,
  1247. std::string const& linkLanguage,
  1248. cmGeneratorTarget* target)
  1249. {
  1250. std::vector<BT<std::string>> tmpFlags =
  1251. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1252. this->AppendFlags(flags, tmpFlags);
  1253. }
  1254. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1255. std::string const& config, std::string const& linkLanguage,
  1256. cmGeneratorTarget* target)
  1257. {
  1258. std::string const configUpper = cmSystemTools::UpperCase(config);
  1259. std::vector<BT<std::string>> flags;
  1260. if (linkLanguage != "Swift" && !this->IsSplitSwiftBuild()) {
  1261. std::string staticLibFlags;
  1262. this->AppendFlags(
  1263. staticLibFlags,
  1264. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1265. if (!configUpper.empty()) {
  1266. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
  1267. this->AppendFlags(staticLibFlags,
  1268. this->Makefile->GetSafeDefinition(name));
  1269. }
  1270. if (!staticLibFlags.empty()) {
  1271. flags.emplace_back(std::move(staticLibFlags));
  1272. }
  1273. }
  1274. std::string staticLibFlags;
  1275. this->AppendFlags(staticLibFlags,
  1276. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1277. if (!configUpper.empty()) {
  1278. std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
  1279. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1280. }
  1281. if (!staticLibFlags.empty()) {
  1282. flags.emplace_back(std::move(staticLibFlags));
  1283. }
  1284. std::vector<BT<std::string>> staticLibOpts =
  1285. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1286. // STATIC_LIBRARY_OPTIONS are escaped.
  1287. this->AppendCompileOptions(flags, staticLibOpts);
  1288. return flags;
  1289. }
  1290. void cmLocalGenerator::GetDeviceLinkFlags(
  1291. cmLinkLineDeviceComputer& linkLineComputer, std::string const& config,
  1292. std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
  1293. std::string& linkPath, cmGeneratorTarget* target)
  1294. {
  1295. cmGeneratorTarget::DeviceLinkSetter setter(*target);
  1296. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1297. auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
  1298. auto ipoEnabled = target->IsIPOEnabled(linklang, config);
  1299. if (!ipoEnabled && pcli) {
  1300. ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
  1301. }
  1302. if (ipoEnabled) {
  1303. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  1304. "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
  1305. linkFlags += *cudaIPOFlags;
  1306. }
  1307. }
  1308. if (pcli) {
  1309. // Compute the required device link libraries when
  1310. // resolving gpu lang device symbols
  1311. this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
  1312. linkPath);
  1313. }
  1314. this->AddVisibilityPresetFlags(linkFlags, target, "CUDA");
  1315. this->GetGlobalGenerator()->EncodeLiteral(linkFlags);
  1316. std::vector<std::string> linkOpts;
  1317. target->GetLinkOptions(linkOpts, config, "CUDA");
  1318. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1319. // LINK_OPTIONS are escaped.
  1320. this->AppendCompileOptions(linkFlags, linkOpts);
  1321. this->SetLinkScriptShell(false);
  1322. }
  1323. void cmLocalGenerator::GetTargetFlags(
  1324. cmLinkLineComputer* linkLineComputer, std::string const& config,
  1325. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1326. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1327. {
  1328. std::vector<BT<std::string>> linkFlagsList;
  1329. std::vector<BT<std::string>> linkPathList;
  1330. std::vector<BT<std::string>> linkLibsList;
  1331. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1332. linkFlagsList, frameworkPath, linkPathList, target);
  1333. this->AppendFlags(linkFlags, linkFlagsList);
  1334. this->AppendFlags(linkPath, linkPathList);
  1335. this->AppendFlags(linkLibs, linkLibsList);
  1336. }
  1337. void cmLocalGenerator::GetTargetFlags(
  1338. cmLinkLineComputer* linkLineComputer, std::string const& config,
  1339. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1340. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1341. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1342. {
  1343. std::string const configUpper = cmSystemTools::UpperCase(config);
  1344. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1345. char const* libraryLinkVariable =
  1346. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1347. std::string const linkLanguage =
  1348. linkLineComputer->GetLinkerLanguage(target, config);
  1349. {
  1350. std::string createFlags;
  1351. this->AppendTargetCreationLinkFlags(createFlags, target, linkLanguage);
  1352. if (!createFlags.empty()) {
  1353. linkFlags.emplace_back(std::move(createFlags));
  1354. }
  1355. }
  1356. switch (target->GetType()) {
  1357. case cmStateEnums::STATIC_LIBRARY:
  1358. linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
  1359. break;
  1360. case cmStateEnums::MODULE_LIBRARY:
  1361. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1362. CM_FALLTHROUGH;
  1363. case cmStateEnums::SHARED_LIBRARY: {
  1364. if (this->IsSplitSwiftBuild() || linkLanguage != "Swift") {
  1365. std::string libFlags;
  1366. this->AddConfigVariableFlags(libFlags, libraryLinkVariable, target,
  1367. cmBuildStep::Link, linkLanguage, config);
  1368. if (!libFlags.empty()) {
  1369. linkFlags.emplace_back(std::move(libFlags));
  1370. }
  1371. }
  1372. std::string sharedLibFlags;
  1373. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1374. if (targetLinkFlags) {
  1375. sharedLibFlags += *targetLinkFlags;
  1376. sharedLibFlags += " ";
  1377. }
  1378. if (!configUpper.empty()) {
  1379. targetLinkFlags =
  1380. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1381. if (targetLinkFlags) {
  1382. sharedLibFlags += *targetLinkFlags;
  1383. sharedLibFlags += " ";
  1384. }
  1385. }
  1386. if (!sharedLibFlags.empty()) {
  1387. this->GetGlobalGenerator()->EncodeLiteral(sharedLibFlags);
  1388. linkFlags.emplace_back(std::move(sharedLibFlags));
  1389. }
  1390. std::vector<BT<std::string>> linkOpts =
  1391. target->GetLinkOptions(config, linkLanguage);
  1392. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1393. // LINK_OPTIONS are escaped.
  1394. this->AppendCompileOptions(linkFlags, linkOpts);
  1395. this->SetLinkScriptShell(false);
  1396. if (pcli) {
  1397. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1398. frameworkPath, linkPath);
  1399. }
  1400. } break;
  1401. case cmStateEnums::EXECUTABLE: {
  1402. if (linkLanguage.empty()) {
  1403. cmSystemTools::Error(
  1404. "CMake can not determine linker language for target: " +
  1405. target->GetName());
  1406. return;
  1407. }
  1408. if (linkLanguage != "Swift") {
  1409. std::string exeFlags;
  1410. this->AddConfigVariableFlags(exeFlags, "CMAKE_EXE_LINKER_FLAGS",
  1411. target, cmBuildStep::Link, linkLanguage,
  1412. config);
  1413. if (!exeFlags.empty()) {
  1414. linkFlags.emplace_back(std::move(exeFlags));
  1415. }
  1416. }
  1417. {
  1418. auto exeType = cmStrCat(
  1419. "CMAKE_", linkLanguage, "_CREATE_",
  1420. (target->IsWin32Executable(config) ? "WIN32" : "CONSOLE"), "_EXE");
  1421. std::string exeFlags;
  1422. this->AppendFlags(exeFlags, this->Makefile->GetDefinition(exeType),
  1423. exeType, target, cmBuildStep::Link, linkLanguage);
  1424. if (!exeFlags.empty()) {
  1425. linkFlags.emplace_back(std::move(exeFlags));
  1426. }
  1427. }
  1428. std::string exeFlags;
  1429. if (target->IsExecutableWithExports()) {
  1430. exeFlags += this->Makefile->GetSafeDefinition(
  1431. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1432. exeFlags += " ";
  1433. }
  1434. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
  1435. if (pcli) {
  1436. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1437. frameworkPath, linkPath);
  1438. }
  1439. if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
  1440. std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
  1441. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1442. exeFlags += " ";
  1443. }
  1444. std::string exeExportFlags =
  1445. this->GetExeExportFlags(linkLanguage, *target);
  1446. if (!exeExportFlags.empty()) {
  1447. exeFlags += exeExportFlags;
  1448. exeFlags += " ";
  1449. }
  1450. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1451. if (targetLinkFlags) {
  1452. exeFlags += *targetLinkFlags;
  1453. exeFlags += " ";
  1454. }
  1455. if (!configUpper.empty()) {
  1456. targetLinkFlags =
  1457. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1458. if (targetLinkFlags) {
  1459. exeFlags += *targetLinkFlags;
  1460. exeFlags += " ";
  1461. }
  1462. }
  1463. if (!exeFlags.empty()) {
  1464. this->GetGlobalGenerator()->EncodeLiteral(exeFlags);
  1465. linkFlags.emplace_back(std::move(exeFlags));
  1466. }
  1467. std::vector<BT<std::string>> linkOpts =
  1468. target->GetLinkOptions(config, linkLanguage);
  1469. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1470. // LINK_OPTIONS are escaped.
  1471. this->AppendCompileOptions(linkFlags, linkOpts);
  1472. this->SetLinkScriptShell(false);
  1473. } break;
  1474. default:
  1475. break;
  1476. }
  1477. std::string extraLinkFlags;
  1478. this->AppendLinkerTypeFlags(extraLinkFlags, target, config, linkLanguage);
  1479. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1480. linkLanguage);
  1481. this->AppendWarningAsErrorLinkerFlags(extraLinkFlags, target, linkLanguage);
  1482. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1483. this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
  1484. config, linkLanguage);
  1485. if (!extraLinkFlags.empty()) {
  1486. this->GetGlobalGenerator()->EncodeLiteral(extraLinkFlags);
  1487. linkFlags.emplace_back(std::move(extraLinkFlags));
  1488. }
  1489. }
  1490. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1491. std::string const& config,
  1492. std::string const& lang,
  1493. std::string& flags,
  1494. std::string const& arch)
  1495. {
  1496. std::vector<BT<std::string>> tmpFlags =
  1497. this->GetTargetCompileFlags(target, config, lang, arch);
  1498. this->AppendFlags(flags, tmpFlags);
  1499. }
  1500. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1501. cmGeneratorTarget* target, std::string const& config,
  1502. std::string const& lang, std::string const& arch)
  1503. {
  1504. std::vector<BT<std::string>> flags;
  1505. std::string compileFlags;
  1506. cmMakefile* mf = this->GetMakefile();
  1507. // Add language-specific flags.
  1508. this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
  1509. config);
  1510. if (target->IsIPOEnabled(lang, config)) {
  1511. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1512. }
  1513. this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
  1514. if (lang == "Fortran") {
  1515. this->AppendFlags(compileFlags,
  1516. this->GetTargetFortranFlags(target, config));
  1517. } else if (lang == "Swift") {
  1518. // Only set the compile mode if CMP0157 is set
  1519. if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
  1520. this->GetSwiftCompileMode(target, config)) {
  1521. std::string swiftCompileModeFlag;
  1522. switch (*swiftCompileMode) {
  1523. case cmSwiftCompileMode::Incremental: {
  1524. swiftCompileModeFlag = "-incremental";
  1525. if (cmValue flag =
  1526. mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_INCREMENTAL")) {
  1527. swiftCompileModeFlag = *flag;
  1528. }
  1529. break;
  1530. }
  1531. case cmSwiftCompileMode::Wholemodule: {
  1532. swiftCompileModeFlag = "-wmo";
  1533. if (cmValue flag =
  1534. mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_WMO")) {
  1535. swiftCompileModeFlag = *flag;
  1536. }
  1537. break;
  1538. }
  1539. case cmSwiftCompileMode::Singlefile:
  1540. break;
  1541. case cmSwiftCompileMode::Unknown: {
  1542. this->IssueMessage(
  1543. MessageType::AUTHOR_WARNING,
  1544. cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
  1545. target->GetName(), '\''));
  1546. }
  1547. }
  1548. this->AppendFlags(compileFlags, swiftCompileModeFlag);
  1549. }
  1550. }
  1551. this->AddFeatureFlags(compileFlags, target, lang, config);
  1552. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1553. this->AddColorDiagnosticsFlags(compileFlags, lang);
  1554. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1555. this->AppendFlags(compileFlags,
  1556. this->GetFrameworkFlags(lang, config, target));
  1557. this->AppendFlags(compileFlags,
  1558. this->GetXcFrameworkFlags(lang, config, target));
  1559. if (!compileFlags.empty()) {
  1560. flags.emplace_back(std::move(compileFlags));
  1561. }
  1562. this->AddCompileOptions(flags, target, lang, config);
  1563. return flags;
  1564. }
  1565. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& lang,
  1566. std::string const& config,
  1567. cmGeneratorTarget* target)
  1568. {
  1569. cmLocalGenerator* lg = target->GetLocalGenerator();
  1570. cmMakefile* mf = lg->GetMakefile();
  1571. if (!target->IsApple()) {
  1572. return std::string();
  1573. }
  1574. cmValue fwSearchFlag =
  1575. mf->GetDefinition(cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  1576. cmValue sysFwSearchFlag = mf->GetDefinition(
  1577. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  1578. if (!fwSearchFlag && !sysFwSearchFlag) {
  1579. return std::string{};
  1580. }
  1581. std::set<std::string> emitted;
  1582. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1583. emitted.insert("/System/Library/Frameworks");
  1584. #endif
  1585. std::vector<std::string> includes;
  1586. lg->GetIncludeDirectories(includes, target, "C", config);
  1587. // check all include directories for frameworks as this
  1588. // will already have added a -F for the framework
  1589. for (std::string const& include : includes) {
  1590. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1591. std::string frameworkDir = cmStrCat(include, "/../");
  1592. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1593. emitted.insert(frameworkDir);
  1594. }
  1595. }
  1596. std::string flags;
  1597. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1598. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1599. for (std::string const& framework : frameworks) {
  1600. if (emitted.insert(framework).second) {
  1601. if (sysFwSearchFlag &&
  1602. target->IsSystemIncludeDirectory(framework, config, lang)) {
  1603. flags += *sysFwSearchFlag;
  1604. } else {
  1605. flags += *fwSearchFlag;
  1606. }
  1607. flags +=
  1608. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1609. flags += " ";
  1610. }
  1611. }
  1612. }
  1613. return flags;
  1614. }
  1615. std::string cmLocalGenerator::GetXcFrameworkFlags(std::string const& lang,
  1616. std::string const& config,
  1617. cmGeneratorTarget* target)
  1618. {
  1619. cmLocalGenerator* lg = target->GetLocalGenerator();
  1620. cmMakefile* mf = lg->GetMakefile();
  1621. if (!target->IsApple()) {
  1622. return std::string();
  1623. }
  1624. cmValue includeSearchFlag =
  1625. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  1626. cmValue sysIncludeSearchFlag =
  1627. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  1628. if (!includeSearchFlag && !sysIncludeSearchFlag) {
  1629. return std::string{};
  1630. }
  1631. std::string flags;
  1632. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1633. std::vector<std::string> const& paths = cli->GetXcFrameworkHeaderPaths();
  1634. for (std::string const& path : paths) {
  1635. if (sysIncludeSearchFlag &&
  1636. target->IsSystemIncludeDirectory(path, config, lang)) {
  1637. flags += *sysIncludeSearchFlag;
  1638. } else {
  1639. flags += *includeSearchFlag;
  1640. }
  1641. flags += lg->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
  1642. flags += " ";
  1643. }
  1644. }
  1645. return flags;
  1646. }
  1647. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1648. std::string const& config,
  1649. std::string const& lang,
  1650. std::set<std::string>& defines) const
  1651. {
  1652. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1653. for (BT<std::string> const& v : tmp) {
  1654. defines.emplace(v.Value);
  1655. }
  1656. }
  1657. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1658. cmGeneratorTarget const* target, std::string const& config,
  1659. std::string const& lang) const
  1660. {
  1661. std::set<BT<std::string>> defines;
  1662. // Add the export symbol definition for shared library objects.
  1663. if (std::string const* exportMacro = target->GetExportMacro()) {
  1664. this->AppendDefines(defines, *exportMacro);
  1665. }
  1666. // Add preprocessor definitions for this target and configuration.
  1667. std::vector<BT<std::string>> targetDefines =
  1668. target->GetCompileDefinitions(config, lang);
  1669. this->AppendDefines(defines, targetDefines);
  1670. return defines;
  1671. }
  1672. std::string cmLocalGenerator::GetTargetFortranFlags(
  1673. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1674. {
  1675. // Implemented by specific generators that override this.
  1676. return std::string();
  1677. }
  1678. /**
  1679. * Output the linking rules on a command line. For executables,
  1680. * targetLibrary should be a NULL pointer. For libraries, it should point
  1681. * to the name of the library. This will not link a library against itself.
  1682. */
  1683. void cmLocalGenerator::OutputLinkLibraries(
  1684. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1685. std::string& linkLibraries, std::string& frameworkPath,
  1686. std::string& linkPath)
  1687. {
  1688. std::vector<BT<std::string>> linkLibrariesList;
  1689. std::vector<BT<std::string>> linkPathList;
  1690. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1691. frameworkPath, linkPathList);
  1692. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1693. pcli->AppendValues(linkPath, linkPathList);
  1694. }
  1695. void cmLocalGenerator::OutputLinkLibraries(
  1696. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1697. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1698. std::vector<BT<std::string>>& linkPath)
  1699. {
  1700. cmComputeLinkInformation& cli = *pcli;
  1701. std::string linkLanguage = cli.GetLinkLanguage();
  1702. std::string libPathFlag;
  1703. if (cmValue value = this->Makefile->GetDefinition(
  1704. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1705. libPathFlag = *value;
  1706. } else {
  1707. libPathFlag =
  1708. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1709. }
  1710. std::string libPathTerminator;
  1711. if (cmValue value = this->Makefile->GetDefinition(
  1712. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1713. libPathTerminator = *value;
  1714. } else {
  1715. libPathTerminator =
  1716. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1717. }
  1718. // Add standard link directories for this language
  1719. std::string stdLinkDirString = this->Makefile->GetSafeDefinition(
  1720. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LINK_DIRECTORIES"));
  1721. // Add standard libraries for this language.
  1722. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1723. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1724. // Append the framework search path flags.
  1725. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  1726. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1727. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1728. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1729. stdLinkDirString, linkPath);
  1730. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1731. }
  1732. std::string cmLocalGenerator::GetExeExportFlags(
  1733. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1734. {
  1735. std::string linkFlags;
  1736. // Flags to export symbols from an executable.
  1737. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1738. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1739. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1740. // Only add the flags if ENABLE_EXPORTS is on,
  1741. // except on AIX where we compute symbol exports.
  1742. if (!tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS")) {
  1743. linkFlags = this->Makefile->GetSafeDefinition(
  1744. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1745. }
  1746. }
  1747. return linkFlags;
  1748. }
  1749. bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
  1750. std::vector<std::string> const& archs, cmValue sysroot)
  1751. {
  1752. if (!sysroot) {
  1753. return false;
  1754. }
  1755. return std::all_of(archs.begin(), archs.end(),
  1756. [this, sysroot](std::string const& arch) -> bool {
  1757. std::string const& archSysroot =
  1758. this->AppleArchSysroots[arch];
  1759. return cmIsOff(archSysroot) || *sysroot == archSysroot;
  1760. });
  1761. }
  1762. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1763. cmGeneratorTarget const* target,
  1764. std::string const& lang,
  1765. std::string const& config,
  1766. std::string const& filterArch)
  1767. {
  1768. // Only add Apple specific flags on Apple platforms
  1769. if (target->IsApple() && this->EmitUniversalBinaryFlags) {
  1770. std::vector<std::string> archs = target->GetAppleArchs(config, lang);
  1771. if (!archs.empty() &&
  1772. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
  1773. lang == "ASM")) {
  1774. for (std::string const& arch : archs) {
  1775. if (filterArch.empty() || filterArch == arch) {
  1776. flags += " -arch ";
  1777. flags += arch;
  1778. }
  1779. }
  1780. }
  1781. cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1782. if (sysroot.IsEmpty() &&
  1783. this->Makefile->IsOn(
  1784. cmStrCat("CMAKE_", lang, "_COMPILER_APPLE_SYSROOT_REQUIRED"))) {
  1785. sysroot = this->Makefile->GetDefinition("_CMAKE_OSX_SYSROOT_PATH");
  1786. }
  1787. if (sysroot && *sysroot == "/") {
  1788. sysroot = nullptr;
  1789. }
  1790. std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
  1791. cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1792. if (cmNonempty(sysrootFlag)) {
  1793. if (!this->AppleArchSysroots.empty() &&
  1794. !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
  1795. for (std::string const& arch : archs) {
  1796. std::string const& archSysroot = this->AppleArchSysroots[arch];
  1797. if (cmIsOff(archSysroot)) {
  1798. continue;
  1799. }
  1800. if (filterArch.empty() || filterArch == arch) {
  1801. flags += " -Xarch_" + arch + " ";
  1802. // Combine sysroot flag and path to work with -Xarch
  1803. std::string arch_sysroot = *sysrootFlag + archSysroot;
  1804. flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
  1805. }
  1806. }
  1807. } else if (cmNonempty(sysroot)) {
  1808. flags += " ";
  1809. flags += *sysrootFlag;
  1810. flags += " ";
  1811. flags += this->ConvertToOutputFormat(*sysroot, SHELL);
  1812. }
  1813. }
  1814. cmValue deploymentTarget =
  1815. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1816. if (cmNonempty(deploymentTarget)) {
  1817. std::string deploymentTargetFlagVar =
  1818. "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1819. cmValue deploymentTargetFlag =
  1820. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1821. if (cmNonempty(deploymentTargetFlag) &&
  1822. // CMAKE_<LANG>_COMPILER_TARGET overrides a --target= for
  1823. // CMAKE_OSX_DEPLOYMENT_TARGET, e.g., for visionOS.
  1824. (!cmHasLiteralPrefix(*deploymentTarget, "--target=") ||
  1825. this->Makefile
  1826. ->GetDefinition(cmStrCat("CMAKE_", lang, "_COMPILER_TARGET"))
  1827. .IsEmpty())) {
  1828. std::string flag = *deploymentTargetFlag;
  1829. // Add the deployment target architecture to the flag, if needed.
  1830. static std::string const kARCH = "<ARCH>";
  1831. std::string::size_type archPos = flag.find(kARCH);
  1832. if (archPos != std::string::npos) {
  1833. // This placeholder is meant for visionOS, so default to arm64
  1834. // unless only non-arm64 archs are given.
  1835. std::string const arch =
  1836. (archs.empty() || cm::contains(archs, "arm64")) ? "arm64"
  1837. : archs[0];
  1838. // Replace the placeholder with its value.
  1839. flag = cmStrCat(flag.substr(0, archPos), arch,
  1840. flag.substr(archPos + kARCH.size()));
  1841. }
  1842. // Add the deployment target version to the flag.
  1843. static std::string const kVERSION_MIN = "<VERSION_MIN>";
  1844. std::string::size_type verPos = flag.find(kVERSION_MIN);
  1845. if (verPos != std::string::npos) {
  1846. // Replace the placeholder with its value.
  1847. flag = cmStrCat(flag.substr(0, verPos), *deploymentTarget,
  1848. flag.substr(verPos + kVERSION_MIN.size()));
  1849. } else {
  1850. // There is no placeholder, so append the value.
  1851. flag = cmStrCat(flag, *deploymentTarget);
  1852. }
  1853. flags += " ";
  1854. flags += flag;
  1855. }
  1856. }
  1857. }
  1858. }
  1859. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1860. cmGeneratorTarget const* target,
  1861. cmBuildStep compileOrLink,
  1862. std::string const& lang,
  1863. std::string const& config)
  1864. {
  1865. // Add language-specific flags.
  1866. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1867. config);
  1868. // Add the language standard flag for compiling, and sometimes linking.
  1869. if (compileOrLink == cmBuildStep::Compile ||
  1870. (compileOrLink == cmBuildStep::Link &&
  1871. // Some toolchains require use of the language standard flag
  1872. // when linking in order to use the matching standard library.
  1873. // FIXME: If CMake gains an abstraction for standard library
  1874. // selection, this will have to be reconciled with it.
  1875. this->Makefile->IsOn(
  1876. cmStrCat("CMAKE_", lang, "_LINK_WITH_STANDARD_COMPILE_OPTION")))) {
  1877. cmStandardLevelResolver standardResolver(this->Makefile);
  1878. std::string const& optionFlagDef =
  1879. standardResolver.GetCompileOptionDef(target, lang, config);
  1880. if (!optionFlagDef.empty()) {
  1881. cmValue opt =
  1882. target->Target->GetMakefile()->GetDefinition(optionFlagDef);
  1883. if (opt) {
  1884. cmList optList{ *opt };
  1885. for (std::string const& i : optList) {
  1886. this->AppendFlagEscape(flags, i);
  1887. }
  1888. }
  1889. }
  1890. }
  1891. std::string compilerId = this->Makefile->GetSafeDefinition(
  1892. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1893. std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
  1894. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1895. bool const compilerTargetsMsvcABI =
  1896. (compilerId == "MSVC" || compilerSimulateId == "MSVC");
  1897. bool const compilerTargetsWatcomABI =
  1898. (compilerId == "OpenWatcom" || compilerSimulateId == "OpenWatcom");
  1899. if (lang == "Swift") {
  1900. if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1901. if (cmSystemTools::VersionCompare(
  1902. cmSystemTools::OP_GREATER_EQUAL,
  1903. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1904. "4.2")) {
  1905. this->AppendFlags(flags, "-swift-version " + *v);
  1906. }
  1907. }
  1908. } else if (lang == "CUDA") {
  1909. target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
  1910. target->AddCUDAToolkitFlags(flags);
  1911. } else if (lang == "ISPC") {
  1912. target->AddISPCTargetFlags(flags);
  1913. } else if (lang == "RC" &&
  1914. this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
  1915. .find("llvm-rc") != std::string::npos) {
  1916. compilerId = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
  1917. if (!compilerId.empty()) {
  1918. compilerSimulateId =
  1919. this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
  1920. } else {
  1921. compilerId = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
  1922. compilerSimulateId =
  1923. this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
  1924. }
  1925. } else if (lang == "HIP") {
  1926. target->AddHIPArchitectureFlags(compileOrLink, config, flags);
  1927. }
  1928. // Add VFS Overlay for Clang compilers
  1929. if (compilerId == "Clang") {
  1930. if (cmValue vfsOverlay =
  1931. this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
  1932. if (compilerSimulateId == "MSVC") {
  1933. this->AppendCompileOptions(
  1934. flags,
  1935. std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
  1936. *vfsOverlay });
  1937. } else {
  1938. this->AppendCompileOptions(
  1939. flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
  1940. }
  1941. }
  1942. }
  1943. // Add MSVC runtime library flags. This is activated by the presence
  1944. // of a default selection whether or not it is overridden by a property.
  1945. cmValue msvcRuntimeLibraryDefault =
  1946. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1947. if (cmNonempty(msvcRuntimeLibraryDefault)) {
  1948. cmValue msvcRuntimeLibraryValue =
  1949. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1950. if (!msvcRuntimeLibraryValue) {
  1951. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1952. }
  1953. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1954. *msvcRuntimeLibraryValue, this, config, target);
  1955. if (!msvcRuntimeLibrary.empty()) {
  1956. if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1957. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1958. msvcRuntimeLibrary)) {
  1959. this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
  1960. } else if (compilerTargetsMsvcABI &&
  1961. !cmSystemTools::GetErrorOccurredFlag()) {
  1962. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1963. this->IssueMessage(MessageType::FATAL_ERROR,
  1964. "MSVC_RUNTIME_LIBRARY value '" +
  1965. msvcRuntimeLibrary + "' not known for this " +
  1966. lang + " compiler.");
  1967. }
  1968. }
  1969. }
  1970. // Add Watcom runtime library flags. This is activated by the presence
  1971. // of a default selection whether or not it is overridden by a property.
  1972. cmValue watcomRuntimeLibraryDefault =
  1973. this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
  1974. if (cmNonempty(watcomRuntimeLibraryDefault)) {
  1975. cmValue watcomRuntimeLibraryValue =
  1976. target->GetProperty("WATCOM_RUNTIME_LIBRARY");
  1977. if (!watcomRuntimeLibraryValue) {
  1978. watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
  1979. }
  1980. std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1981. *watcomRuntimeLibraryValue, this, config, target);
  1982. if (!watcomRuntimeLibrary.empty()) {
  1983. if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1984. "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
  1985. watcomRuntimeLibrary)) {
  1986. this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
  1987. } else if (compilerTargetsWatcomABI &&
  1988. !cmSystemTools::GetErrorOccurredFlag()) {
  1989. // The compiler uses the Watcom ABI so it needs a known runtime
  1990. // library.
  1991. this->IssueMessage(MessageType::FATAL_ERROR,
  1992. "WATCOM_RUNTIME_LIBRARY value '" +
  1993. watcomRuntimeLibrary + "' not known for this " +
  1994. lang + " compiler.");
  1995. }
  1996. }
  1997. }
  1998. // Add MSVC runtime checks flags. This is activated by the presence
  1999. // of a default selection whether or not it is overridden by a property.
  2000. cmValue msvcRuntimeChecksDefault =
  2001. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_CHECKS_DEFAULT");
  2002. if (cmNonempty(msvcRuntimeChecksDefault)) {
  2003. cmValue msvcRuntimeChecksValue =
  2004. target->GetProperty("MSVC_RUNTIME_CHECKS");
  2005. if (!msvcRuntimeChecksValue) {
  2006. msvcRuntimeChecksValue = msvcRuntimeChecksDefault;
  2007. }
  2008. cmList msvcRuntimeChecksList = cmGeneratorExpression::Evaluate(
  2009. *msvcRuntimeChecksValue, this, config, target);
  2010. msvcRuntimeChecksList.remove_duplicates();
  2011. // RTC1/RTCsu VS GUI workaround
  2012. std::string const stackFrameErrorCheck = "StackFrameErrorCheck";
  2013. std::string const unitinitializedVariable = "UninitializedVariable";
  2014. std::string const rtcSU = "RTCsu";
  2015. if ((cm::contains(msvcRuntimeChecksList, stackFrameErrorCheck) &&
  2016. cm::contains(msvcRuntimeChecksList, unitinitializedVariable)) ||
  2017. cm::contains(msvcRuntimeChecksList, rtcSU)) {
  2018. msvcRuntimeChecksList.remove_items(
  2019. { stackFrameErrorCheck, unitinitializedVariable, rtcSU });
  2020. msvcRuntimeChecksList.append(rtcSU);
  2021. }
  2022. for (std::string const& msvcRuntimeChecks : msvcRuntimeChecksList) {
  2023. if (cmValue msvcRuntimeChecksOptions =
  2024. this->Makefile->GetDefinition(cmStrCat(
  2025. "CMAKE_", lang,
  2026. "_COMPILE_OPTIONS_MSVC_RUNTIME_CHECKS_" + msvcRuntimeChecks))) {
  2027. this->AppendCompileOptions(flags, *msvcRuntimeChecksOptions);
  2028. } else if (compilerTargetsMsvcABI &&
  2029. !cmSystemTools::GetErrorOccurredFlag()) {
  2030. // The compiler uses the MSVC ABI so it needs a known runtime checks.
  2031. this->IssueMessage(MessageType::FATAL_ERROR,
  2032. cmStrCat("MSVC_RUNTIME_CHECKS value '",
  2033. msvcRuntimeChecks, "' not known for this ",
  2034. lang, " compiler."));
  2035. }
  2036. }
  2037. }
  2038. // Add MSVC debug information format flags if CMP0141 is NEW.
  2039. if (cm::optional<std::string> msvcDebugInformationFormat =
  2040. this->GetMSVCDebugFormatName(config, target)) {
  2041. if (!msvcDebugInformationFormat->empty()) {
  2042. if (cmValue msvcDebugInformationFormatOptions =
  2043. this->Makefile->GetDefinition(
  2044. cmStrCat("CMAKE_", lang,
  2045. "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
  2046. *msvcDebugInformationFormat))) {
  2047. this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
  2048. } else if (compilerTargetsMsvcABI &&
  2049. !cmSystemTools::GetErrorOccurredFlag()) {
  2050. // The compiler uses the MSVC ABI so it needs a known runtime library.
  2051. this->IssueMessage(MessageType::FATAL_ERROR,
  2052. cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
  2053. *msvcDebugInformationFormat,
  2054. "' not known for this ", lang,
  2055. " compiler."));
  2056. }
  2057. }
  2058. }
  2059. }
  2060. void cmLocalGenerator::AddLanguageFlagsForLinking(
  2061. std::string& flags, cmGeneratorTarget const* target, std::string const& lang,
  2062. std::string const& config)
  2063. {
  2064. this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
  2065. if (target->IsIPOEnabled(lang, config)) {
  2066. this->AppendFeatureOptions(flags, lang, "IPO");
  2067. }
  2068. }
  2069. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  2070. std::string const& name) const
  2071. {
  2072. auto imported = this->ImportedGeneratorTargets.find(name);
  2073. if (imported != this->ImportedGeneratorTargets.end()) {
  2074. return imported->second;
  2075. }
  2076. // find local alias to imported target
  2077. auto aliased = this->AliasTargets.find(name);
  2078. if (aliased != this->AliasTargets.end()) {
  2079. imported = this->ImportedGeneratorTargets.find(aliased->second);
  2080. if (imported != this->ImportedGeneratorTargets.end()) {
  2081. return imported->second;
  2082. }
  2083. }
  2084. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  2085. return t;
  2086. }
  2087. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  2088. }
  2089. bool cmLocalGenerator::GetRealDependency(std::string const& inName,
  2090. std::string const& config,
  2091. std::string& dep)
  2092. {
  2093. // Older CMake code may specify the dependency using the target
  2094. // output file rather than the target name. Such code would have
  2095. // been written before there was support for target properties that
  2096. // modify the name so stripping down to just the file name should
  2097. // produce the target name in this case.
  2098. std::string name = cmSystemTools::GetFilenameName(inName);
  2099. // If the input name is the empty string, there is no real
  2100. // dependency. Short-circuit the other checks:
  2101. if (name.empty()) {
  2102. return false;
  2103. }
  2104. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  2105. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  2106. }
  2107. // Look for a CMake target with the given name.
  2108. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  2109. // make sure it is not just a coincidence that the target name
  2110. // found is part of the inName
  2111. if (cmSystemTools::FileIsFullPath(inName)) {
  2112. std::string tLocation;
  2113. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  2114. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  2115. tLocation = target->GetLocation(config);
  2116. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  2117. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  2118. }
  2119. std::string depLocation =
  2120. cmSystemTools::GetFilenamePath(std::string(inName));
  2121. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  2122. if (depLocation != tLocation) {
  2123. // it is a full path to a depend that has the same name
  2124. // as a target but is in a different location so do not use
  2125. // the target as the depend
  2126. dep = inName;
  2127. return true;
  2128. }
  2129. }
  2130. switch (target->GetType()) {
  2131. case cmStateEnums::EXECUTABLE:
  2132. case cmStateEnums::STATIC_LIBRARY:
  2133. case cmStateEnums::SHARED_LIBRARY:
  2134. case cmStateEnums::MODULE_LIBRARY:
  2135. case cmStateEnums::UNKNOWN_LIBRARY:
  2136. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  2137. /*realname=*/true);
  2138. return true;
  2139. case cmStateEnums::OBJECT_LIBRARY:
  2140. // An object library has no single file on which to depend.
  2141. // This was listed to get the target-level dependency.
  2142. case cmStateEnums::INTERFACE_LIBRARY:
  2143. // An interface library has no file on which to depend.
  2144. // This was listed to get the target-level dependency.
  2145. case cmStateEnums::UTILITY:
  2146. case cmStateEnums::GLOBAL_TARGET:
  2147. // A utility target has no file on which to depend. This was listed
  2148. // only to get the target-level dependency.
  2149. return false;
  2150. }
  2151. }
  2152. // The name was not that of a CMake target. It must name a file.
  2153. if (cmSystemTools::FileIsFullPath(inName)) {
  2154. // This is a full path. Return it as given.
  2155. dep = inName;
  2156. return true;
  2157. }
  2158. // Check for a source file in this directory that matches the
  2159. // dependency.
  2160. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  2161. dep = sf->ResolveFullPath();
  2162. return true;
  2163. }
  2164. // Treat the name as relative to the source directory in which it
  2165. // was given.
  2166. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  2167. // If the in-source path does not exist, assume it instead lives in the
  2168. // binary directory.
  2169. if (!cmSystemTools::FileExists(dep)) {
  2170. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  2171. }
  2172. dep = cmSystemTools::CollapseFullPath(dep);
  2173. return true;
  2174. }
  2175. static void AddVisibilityCompileOption(std::string& flags,
  2176. cmGeneratorTarget const* target,
  2177. cmLocalGenerator* lg,
  2178. std::string const& lang)
  2179. {
  2180. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2181. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2182. if (!opt) {
  2183. return;
  2184. }
  2185. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2186. cmValue prop = target->GetProperty(flagDefine);
  2187. if (!prop) {
  2188. return;
  2189. }
  2190. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2191. (*prop != "internal")) {
  2192. std::ostringstream e;
  2193. e << "Target " << target->GetName() << " uses unsupported value \""
  2194. << *prop << "\" for " << flagDefine << "."
  2195. << " The supported values are: default, hidden, protected, and "
  2196. "internal.";
  2197. cmSystemTools::Error(e.str());
  2198. return;
  2199. }
  2200. std::string option = *opt + *prop;
  2201. lg->AppendFlags(flags, option);
  2202. }
  2203. static void AddInlineVisibilityCompileOption(std::string& flags,
  2204. cmGeneratorTarget const* target,
  2205. cmLocalGenerator* lg,
  2206. std::string const& lang)
  2207. {
  2208. std::string compileOption =
  2209. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2210. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2211. if (!opt) {
  2212. return;
  2213. }
  2214. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2215. if (!prop) {
  2216. return;
  2217. }
  2218. lg->AppendFlags(flags, *opt);
  2219. }
  2220. void cmLocalGenerator::AddVisibilityPresetFlags(
  2221. std::string& flags, cmGeneratorTarget const* target, std::string const& lang)
  2222. {
  2223. if (lang.empty()) {
  2224. return;
  2225. }
  2226. AddVisibilityCompileOption(flags, target, this, lang);
  2227. if (lang == "CXX" || lang == "OBJCXX") {
  2228. AddInlineVisibilityCompileOption(flags, target, this, lang);
  2229. }
  2230. }
  2231. void cmLocalGenerator::AddFeatureFlags(std::string& flags,
  2232. cmGeneratorTarget const* target,
  2233. std::string const& lang,
  2234. std::string const& config)
  2235. {
  2236. int targetType = target->GetType();
  2237. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2238. (targetType == cmStateEnums::MODULE_LIBRARY));
  2239. if (target->GetLinkInterfaceDependentBoolProperty(
  2240. "POSITION_INDEPENDENT_CODE", config)) {
  2241. this->AddPositionIndependentFlags(flags, lang, targetType);
  2242. }
  2243. if (shared) {
  2244. this->AppendFeatureOptions(flags, lang, "DLL");
  2245. }
  2246. }
  2247. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2248. std::string const& lang,
  2249. int targetType)
  2250. {
  2251. std::string picFlags;
  2252. if (targetType == cmStateEnums::EXECUTABLE) {
  2253. picFlags = this->Makefile->GetSafeDefinition(
  2254. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2255. }
  2256. if (picFlags.empty()) {
  2257. picFlags = this->Makefile->GetSafeDefinition(
  2258. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2259. }
  2260. if (!picFlags.empty()) {
  2261. cmList options{ picFlags };
  2262. for (std::string const& o : options) {
  2263. this->AppendFlagEscape(flags, o);
  2264. }
  2265. }
  2266. }
  2267. void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
  2268. std::string const& lang)
  2269. {
  2270. cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
  2271. if (diag.IsSet()) {
  2272. std::string colorFlagName;
  2273. if (diag.IsOn()) {
  2274. colorFlagName =
  2275. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
  2276. } else {
  2277. colorFlagName =
  2278. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
  2279. }
  2280. cmList options{ this->Makefile->GetDefinition(colorFlagName) };
  2281. for (auto const& option : options) {
  2282. this->AppendFlagEscape(flags, option);
  2283. }
  2284. }
  2285. }
  2286. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2287. std::string const& var,
  2288. std::string const& config)
  2289. {
  2290. // Add the flags from the variable itself.
  2291. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2292. // Add the flags from the build-type specific variable.
  2293. if (!config.empty()) {
  2294. std::string const flagsVar =
  2295. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2296. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2297. }
  2298. }
  2299. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2300. std::string const& var,
  2301. cmGeneratorTarget const* target,
  2302. cmBuildStep compileOrLink,
  2303. std::string const& lang,
  2304. std::string const& config)
  2305. {
  2306. std::string newFlags;
  2307. this->AddConfigVariableFlags(newFlags, var, config);
  2308. if (!newFlags.empty()) {
  2309. this->AppendFlags(flags, newFlags, var, target, compileOrLink, lang);
  2310. }
  2311. }
  2312. void cmLocalGenerator::AppendFlags(std::string& flags,
  2313. std::string const& newFlags) const
  2314. {
  2315. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2316. if (!newFlags.empty() && !allSpaces) {
  2317. if (!flags.empty()) {
  2318. flags += " ";
  2319. }
  2320. flags += newFlags;
  2321. }
  2322. }
  2323. void cmLocalGenerator::AppendFlags(
  2324. std::string& flags, std::vector<BT<std::string>> const& newFlags) const
  2325. {
  2326. for (BT<std::string> const& flag : newFlags) {
  2327. this->AppendFlags(flags, flag.Value);
  2328. }
  2329. }
  2330. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2331. std::string const& rawFlag) const
  2332. {
  2333. this->AppendFlags(
  2334. flags,
  2335. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2336. }
  2337. void cmLocalGenerator::AppendFlags(std::string& flags,
  2338. std::string const& newFlags,
  2339. std::string const& name,
  2340. cmGeneratorTarget const* target,
  2341. cmBuildStep compileOrLink,
  2342. std::string const& language)
  2343. {
  2344. switch (target->GetPolicyStatusCMP0181()) {
  2345. case cmPolicies::WARN:
  2346. if (!this->Makefile->GetCMakeInstance()->GetIsInTryCompile() &&
  2347. this->Makefile->PolicyOptionalWarningEnabled(
  2348. "CMAKE_POLICY_WARNING_CMP0181")) {
  2349. this->Makefile->GetCMakeInstance()->IssueMessage(
  2350. MessageType::AUTHOR_WARNING,
  2351. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0181),
  2352. "\nSince the policy is not set, the contents of variable '",
  2353. name,
  2354. "' will "
  2355. "be used as is."),
  2356. target->GetBacktrace());
  2357. }
  2358. CM_FALLTHROUGH;
  2359. case cmPolicies::OLD:
  2360. this->AppendFlags(
  2361. flags, this->GetGlobalGenerator()->GetEncodedLiteral(newFlags));
  2362. break;
  2363. case cmPolicies::NEW:
  2364. if (compileOrLink == cmBuildStep::Link) {
  2365. std::vector<std::string> options;
  2366. cmSystemTools::ParseUnixCommandLine(newFlags.c_str(), options);
  2367. this->SetLinkScriptShell(this->GlobalGenerator->GetUseLinkScript());
  2368. std::vector<BT<std::string>> optionsWithBT{ options.size() };
  2369. std::transform(options.cbegin(), options.cend(), optionsWithBT.begin(),
  2370. [](std::string const& item) -> BT<std::string> {
  2371. return BT<std::string>{ item };
  2372. });
  2373. target->ResolveLinkerWrapper(optionsWithBT, language);
  2374. for (auto const& item : optionsWithBT) {
  2375. this->AppendFlagEscape(flags, item.Value);
  2376. }
  2377. this->SetLinkScriptShell(false);
  2378. } else {
  2379. this->AppendFlags(flags, newFlags);
  2380. }
  2381. }
  2382. }
  2383. void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
  2384. {
  2385. std::vector<std::string> enabledLanguages =
  2386. this->GetState()->GetEnabledLanguages();
  2387. if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
  2388. enabledLanguages.end()) {
  2389. return;
  2390. }
  2391. cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
  2392. assert(ispcHeaderSuffixProp);
  2393. std::vector<std::string> ispcArchSuffixes =
  2394. detail::ComputeISPCObjectSuffixes(target);
  2395. bool const extra_objects = (ispcArchSuffixes.size() > 1);
  2396. std::vector<std::string> configsList =
  2397. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2398. for (std::string const& config : configsList) {
  2399. std::string rootObjectDir = target->GetObjectDirectory(config);
  2400. std::string headerDir = rootObjectDir;
  2401. if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
  2402. headerDir = cmSystemTools::CollapseFullPath(
  2403. cmStrCat(this->GetBinaryDirectory(), '/', *prop));
  2404. }
  2405. std::vector<cmSourceFile*> sources;
  2406. target->GetSourceFiles(sources, config);
  2407. // build up the list of ispc headers and extra objects that this target is
  2408. // generating
  2409. for (cmSourceFile const* sf : sources) {
  2410. // Generate this object file's rule file.
  2411. std::string const& lang = sf->GetLanguage();
  2412. if (lang == "ISPC") {
  2413. std::string const& objectName = target->GetObjectName(sf);
  2414. // Drop both ".obj" and the source file extension
  2415. std::string ispcSource =
  2416. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  2417. ispcSource =
  2418. cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  2419. auto headerPath =
  2420. cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
  2421. target->AddISPCGeneratedHeader(headerPath, config);
  2422. if (extra_objects) {
  2423. std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
  2424. objectName, rootObjectDir, ispcArchSuffixes);
  2425. target->AddISPCGeneratedObject(std::move(objs), config);
  2426. }
  2427. }
  2428. }
  2429. }
  2430. }
  2431. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2432. {
  2433. std::vector<std::string> configsList =
  2434. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2435. for (std::string const& config : configsList) {
  2436. // FIXME: Refactor collection of sources to not evaluate object
  2437. // libraries.
  2438. std::vector<cmSourceFile*> sources;
  2439. target->GetSourceFiles(sources, config);
  2440. std::string const configUpper = cmSystemTools::UpperCase(config);
  2441. static std::array<std::string, 4> const langs = { { "C", "CXX", "OBJC",
  2442. "OBJCXX" } };
  2443. std::set<std::string> pchLangSet;
  2444. if (this->GetGlobalGenerator()->IsXcode()) {
  2445. for (std::string const& lang : langs) {
  2446. std::string const pchHeader = target->GetPchHeader(config, lang, "");
  2447. if (!pchHeader.empty()) {
  2448. pchLangSet.emplace(lang);
  2449. }
  2450. }
  2451. }
  2452. for (std::string const& lang : langs) {
  2453. auto langSources = std::count_if(
  2454. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2455. return lang == sf->GetLanguage() &&
  2456. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2457. });
  2458. if (langSources == 0) {
  2459. continue;
  2460. }
  2461. std::vector<std::string> pchArchs = target->GetPchArchs(config, lang);
  2462. if (pchArchs.size() > 1) {
  2463. std::string useMultiArchPch;
  2464. for (std::string const& arch : pchArchs) {
  2465. std::string const pchHeader =
  2466. target->GetPchHeader(config, lang, arch);
  2467. if (!pchHeader.empty()) {
  2468. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2469. ";-include", pchHeader);
  2470. }
  2471. }
  2472. if (!useMultiArchPch.empty()) {
  2473. target->Target->AppendProperty(
  2474. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
  2475. cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, '>'));
  2476. }
  2477. }
  2478. for (std::string const& arch : pchArchs) {
  2479. std::string const pchSource = target->GetPchSource(config, lang, arch);
  2480. std::string const pchHeader = target->GetPchHeader(config, lang, arch);
  2481. if (pchSource.empty() || pchHeader.empty()) {
  2482. if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
  2483. for (auto* sf : sources) {
  2484. auto const sourceLanguage = sf->GetLanguage();
  2485. if (!sourceLanguage.empty() &&
  2486. pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
  2487. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2488. }
  2489. }
  2490. }
  2491. continue;
  2492. }
  2493. cmValue pchExtension =
  2494. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  2495. if (pchExtension.IsEmpty()) {
  2496. continue;
  2497. }
  2498. auto* reuseTarget = target->GetPchReuseTarget();
  2499. bool const haveReuseTarget = reuseTarget && reuseTarget != target;
  2500. auto* pch_sf = this->Makefile->GetOrCreateSource(
  2501. pchSource, false, cmSourceFileLocationKind::Known);
  2502. pch_sf->SetSpecialSourceType(
  2503. cmSourceFile::SpecialSourceType::PchSource);
  2504. // PCH sources should never be scanned as they cannot contain C++
  2505. // module references.
  2506. pch_sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2507. if (!this->GetGlobalGenerator()->IsXcode()) {
  2508. if (!haveReuseTarget) {
  2509. target->AddSource(pchSource, true);
  2510. }
  2511. std::string const pchFile = target->GetPchFile(config, lang, arch);
  2512. // Exclude the pch files from linking
  2513. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2514. if (!haveReuseTarget) {
  2515. pch_sf->AppendProperty(
  2516. "OBJECT_OUTPUTS",
  2517. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, '>'));
  2518. } else {
  2519. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2520. std::string const compilerId =
  2521. this->Makefile->GetSafeDefinition(
  2522. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2523. std::string const compilerVersion =
  2524. this->Makefile->GetSafeDefinition(
  2525. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2526. std::string const langFlags =
  2527. this->Makefile->GetSafeDefinition(
  2528. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2529. bool editAndContinueDebugInfo = false;
  2530. bool programDatabaseDebugInfo = false;
  2531. cm::optional<std::string> msvcDebugInformationFormat =
  2532. this->GetMSVCDebugFormatName(config, target);
  2533. if (msvcDebugInformationFormat &&
  2534. !msvcDebugInformationFormat->empty()) {
  2535. editAndContinueDebugInfo =
  2536. *msvcDebugInformationFormat == "EditAndContinue";
  2537. programDatabaseDebugInfo =
  2538. *msvcDebugInformationFormat == "ProgramDatabase";
  2539. } else {
  2540. editAndContinueDebugInfo =
  2541. langFlags.find("/ZI") != std::string::npos ||
  2542. langFlags.find("-ZI") != std::string::npos;
  2543. programDatabaseDebugInfo =
  2544. langFlags.find("/Zi") != std::string::npos ||
  2545. langFlags.find("-Zi") != std::string::npos;
  2546. }
  2547. if (editAndContinueDebugInfo) {
  2548. this->CopyPchCompilePdb(config, lang, target, reuseTarget,
  2549. { ".pdb", ".idb" });
  2550. } else if (programDatabaseDebugInfo) {
  2551. this->CopyPchCompilePdb(config, lang, target, reuseTarget,
  2552. { ".pdb" });
  2553. }
  2554. }
  2555. // Link to the pch object file
  2556. std::string pchSourceObj;
  2557. // Fastbuild will propagate pch.obj for us, no need to link to it
  2558. // explicitly.
  2559. if (!this->GetGlobalGenerator()->IsFastbuild()) {
  2560. pchSourceObj =
  2561. reuseTarget->GetPchFileObject(config, lang, arch);
  2562. }
  2563. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2564. std::string linkerProperty = "LINK_FLAGS_";
  2565. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2566. linkerProperty = "STATIC_LIBRARY_FLAGS_";
  2567. }
  2568. target->Target->AppendProperty(
  2569. cmStrCat(linkerProperty, configUpper),
  2570. cmStrCat(' ',
  2571. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2572. cm::nullopt, true);
  2573. } else if (reuseTarget->GetType() ==
  2574. cmStateEnums::OBJECT_LIBRARY) {
  2575. target->Target->AppendProperty(
  2576. "INTERFACE_LINK_LIBRARIES",
  2577. cmStrCat("$<$<CONFIG:", config,
  2578. ">:$<LINK_ONLY:", pchSourceObj, ">>"));
  2579. }
  2580. }
  2581. } else {
  2582. pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
  2583. }
  2584. // Add pchHeader to source files, which will
  2585. // be grouped as "Precompile Header File"
  2586. auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
  2587. pchHeader, false, cmSourceFileLocationKind::Known);
  2588. pchHeader_sf->SetSpecialSourceType(
  2589. cmSourceFile::SpecialSourceType::PchHeader);
  2590. std::string err;
  2591. pchHeader_sf->ResolveFullPath(&err);
  2592. if (!err.empty()) {
  2593. std::ostringstream msg;
  2594. msg << "Unable to resolve full path of PCH-header '" << pchHeader
  2595. << "' assigned to target " << target->GetName()
  2596. << ", although its path is supposed to be known!";
  2597. this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
  2598. }
  2599. target->AddSource(pchHeader);
  2600. }
  2601. }
  2602. }
  2603. }
  2604. }
  2605. void cmLocalGenerator::CopyPchCompilePdb(
  2606. std::string const& config, std::string const& language,
  2607. cmGeneratorTarget* target, cmGeneratorTarget* reuseTarget,
  2608. std::vector<std::string> const& extensions)
  2609. {
  2610. std::string const copy_script = cmStrCat(target->GetSupportDirectory(),
  2611. "/copy_idb_pdb_", config, ".cmake");
  2612. cmGeneratedFileStream file(copy_script);
  2613. file << "# CMake generated file\n";
  2614. file << "# The compiler generated pdb file needs to be written to disk\n"
  2615. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2616. << "# the pdb file is ready to be copied.\n\n";
  2617. auto configGenex = [&](cm::string_view expr) -> std::string {
  2618. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2619. return cmStrCat("$<$<CONFIG:", config, ">:", expr, '>');
  2620. }
  2621. return std::string(expr);
  2622. };
  2623. std::vector<std::string> outputs;
  2624. auto replaceExtension = [](std::string const& path,
  2625. std::string const& ext) -> std::string {
  2626. auto const dir = cmSystemTools::GetFilenamePath(path);
  2627. auto const base = cmSystemTools::GetFilenameWithoutLastExtension(path);
  2628. if (dir.empty()) {
  2629. return cmStrCat(base, ext);
  2630. }
  2631. return cmStrCat(dir, '/', base, ext);
  2632. };
  2633. for (auto const& extension : extensions) {
  2634. std::string const from_file =
  2635. replaceExtension(reuseTarget->GetCompilePDBPath(config), extension);
  2636. std::string const to_dir = target->GetCompilePDBDirectory(config);
  2637. std::string const to_file =
  2638. replaceExtension(reuseTarget->GetCompilePDBName(config), extension);
  2639. std::string const dest_file = cmStrCat(to_dir, '/', to_file);
  2640. file << "foreach(retry RANGE 1 30)\n";
  2641. file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
  2642. << dest_file << "\" OR NOT \"" << dest_file << "\" IS_NEWER_THAN \""
  2643. << from_file << "\"))\n";
  2644. file << " file(MAKE_DIRECTORY \"" << to_dir << "\")\n";
  2645. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2646. file << " \"" << from_file << "\"" << " \"" << to_dir
  2647. << "\" RESULT_VARIABLE result " << " ERROR_QUIET)\n";
  2648. file << " if (NOT result EQUAL 0)\n"
  2649. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2650. << " -E sleep 1)\n"
  2651. << " else()\n";
  2652. file << " break()\n"
  2653. << " endif()\n";
  2654. file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
  2655. << " execute_process(COMMAND ${CMAKE_COMMAND}" << " -E sleep 1)\n"
  2656. << " endif()\n";
  2657. file << "endforeach()\n";
  2658. outputs.push_back(configGenex(dest_file));
  2659. }
  2660. cmCustomCommandLines commandLines =
  2661. cmMakeSingleCommandLine({ configGenex(cmSystemTools::GetCMakeCommand()),
  2662. configGenex("-P"), configGenex(copy_script) });
  2663. auto const comment =
  2664. cmStrCat("Copying PDB for PCH reuse from ", reuseTarget->GetName(),
  2665. " for ", target->GetName());
  2666. ;
  2667. auto cc = cm::make_unique<cmCustomCommand>();
  2668. cc->SetCommandLines(commandLines);
  2669. cc->SetComment(comment.c_str());
  2670. cc->SetStdPipesUTF8(true);
  2671. cc->AppendDepends(
  2672. { reuseTarget->GetPchFile(config, language), copy_script });
  2673. // Fastbuild needs to know that this custom command actually depends on a
  2674. // target that produces PCH, so it can sort by dependencies correctly.
  2675. if (this->GetGlobalGenerator()->IsFastbuild()) {
  2676. cc->AppendDepends({ reuseTarget->GetName() });
  2677. }
  2678. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2679. cc->SetByproducts(outputs);
  2680. this->AddCustomCommandToTarget(
  2681. target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
  2682. cmObjectLibraryCommands::Accept);
  2683. } else {
  2684. cc->SetOutputs(outputs);
  2685. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
  2686. if (copy_rule) {
  2687. copy_rule->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2688. auto* pch_pdb_sf = target->AddSource(copy_rule->ResolveFullPath());
  2689. pch_pdb_sf->SetSpecialSourceType(
  2690. cmSourceFile::SpecialSourceType::PchPdbReuseSource);
  2691. }
  2692. }
  2693. }
  2694. cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
  2695. std::string const& config, cmGeneratorTarget const* target)
  2696. {
  2697. // MSVC debug information format selection is activated by the presence
  2698. // of a default whether or not it is overridden by a property.
  2699. cm::optional<std::string> msvcDebugInformationFormat;
  2700. cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
  2701. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
  2702. if (cmNonempty(msvcDebugInformationFormatDefault)) {
  2703. cmValue msvcDebugInformationFormatValue =
  2704. target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
  2705. if (!msvcDebugInformationFormatValue) {
  2706. msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
  2707. }
  2708. msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
  2709. *msvcDebugInformationFormatValue, this, config, target);
  2710. }
  2711. return msvcDebugInformationFormat;
  2712. }
  2713. cm::optional<cmSwiftCompileMode> cmLocalGenerator::GetSwiftCompileMode(
  2714. cmGeneratorTarget const* target, std::string const& config)
  2715. {
  2716. cmMakefile const* mf = this->GetMakefile();
  2717. cmValue const swiftCompileModeDefault =
  2718. mf->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT");
  2719. if (!cmNonempty(swiftCompileModeDefault)) {
  2720. return {};
  2721. }
  2722. cmValue swiftCompileMode = target->GetProperty("Swift_COMPILATION_MODE");
  2723. if (!swiftCompileMode) {
  2724. swiftCompileMode = swiftCompileModeDefault;
  2725. }
  2726. std::string const expandedCompileMode =
  2727. cmGeneratorExpression::Evaluate(*swiftCompileMode, this, config, target);
  2728. if (expandedCompileMode == "wholemodule") {
  2729. return cmSwiftCompileMode::Wholemodule;
  2730. }
  2731. if (expandedCompileMode == "singlefile") {
  2732. return cmSwiftCompileMode::Singlefile;
  2733. }
  2734. if (expandedCompileMode == "incremental") {
  2735. return cmSwiftCompileMode::Incremental;
  2736. }
  2737. return cmSwiftCompileMode::Unknown;
  2738. }
  2739. bool cmLocalGenerator::IsSplitSwiftBuild() const
  2740. {
  2741. return cmNonempty(this->GetMakefile()->GetDefinition(
  2742. "CMAKE_Swift_COMPILATION_MODE_DEFAULT"));
  2743. }
  2744. namespace {
  2745. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2746. std::string const& filename)
  2747. {
  2748. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2749. sf->SetProperty("UNITY_SOURCE_FILE", filename);
  2750. }
  2751. }
  2752. cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
  2753. cmGeneratorTarget* target, std::vector<std::string> const& configs,
  2754. cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
  2755. cmValue beforeInclude, cmValue afterInclude, std::string filename,
  2756. std::string const& unityFileDirectory, UnityPathMode pathMode) const
  2757. {
  2758. cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
  2759. cmGeneratedFileStream file(
  2760. filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
  2761. file.SetCopyIfDifferent(true);
  2762. file << "/* generated by CMake */\n\n";
  2763. bool perConfig = false;
  2764. for (UnityBatchedSource const& ubs : sources) {
  2765. cm::optional<std::string> cond;
  2766. if (ubs.Configs.size() != configs.size()) {
  2767. perConfig = true;
  2768. cond = std::string();
  2769. cm::string_view sep;
  2770. for (size_t ci : ubs.Configs) {
  2771. cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
  2772. cmSystemTools::UpperCase(configs[ci]), ')');
  2773. sep = " || "_s;
  2774. }
  2775. }
  2776. RegisterUnitySources(target, ubs.Source, filename);
  2777. WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
  2778. beforeInclude, afterInclude, uniqueIdName,
  2779. pathMode, unityFileDirectory);
  2780. }
  2781. return UnitySource(std::move(filename), perConfig);
  2782. }
  2783. void cmLocalGenerator::WriteUnitySourceInclude(
  2784. std::ostream& unity_file, cm::optional<std::string> const& cond,
  2785. std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
  2786. cmValue uniqueIdName, UnityPathMode pathMode,
  2787. std::string const& unityFileDirectory) const
  2788. {
  2789. if (cond) {
  2790. unity_file << "#if " << *cond << "\n";
  2791. }
  2792. std::string pathToHash;
  2793. std::string relocatableIncludePath;
  2794. auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
  2795. return (cmSystemTools::ComparePath(a, b) ||
  2796. cmSystemTools::IsSubDirectory(a, b));
  2797. };
  2798. auto const path = cmSystemTools::GetFilenamePath(sf_full_path);
  2799. if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
  2800. relocatableIncludePath =
  2801. cmSystemTools::RelativePath(unityFileDirectory, sf_full_path);
  2802. pathToHash = "BLD_" +
  2803. cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
  2804. } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
  2805. relocatableIncludePath =
  2806. cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
  2807. pathToHash = "SRC_" + relocatableIncludePath;
  2808. } else {
  2809. relocatableIncludePath = sf_full_path;
  2810. pathToHash = "ABS_" + sf_full_path;
  2811. }
  2812. if (cmNonempty(uniqueIdName)) {
  2813. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  2814. unity_file << "/* " << pathToHash << " */\n"
  2815. << "#undef " << *uniqueIdName << "\n"
  2816. << "#define " << *uniqueIdName << " unity_"
  2817. << hasher.HashString(pathToHash) << "\n";
  2818. }
  2819. if (beforeInclude) {
  2820. unity_file << *beforeInclude << "\n";
  2821. }
  2822. // clang-tidy-17 has new include checks that needs NOLINT too.
  2823. unity_file
  2824. << "/* NOLINTNEXTLINE(bugprone-suspicious-include,misc-include-cleaner) "
  2825. "*/\n";
  2826. if (pathMode == UnityPathMode::Relative) {
  2827. unity_file << "#include \"" << relocatableIncludePath << "\"\n";
  2828. } else {
  2829. unity_file << "#include \"" << sf_full_path << "\"\n";
  2830. }
  2831. if (afterInclude) {
  2832. unity_file << *afterInclude << "\n";
  2833. }
  2834. if (cond) {
  2835. unity_file << "#endif\n";
  2836. }
  2837. unity_file << "\n";
  2838. }
  2839. namespace {
  2840. std::string unity_file_extension(std::string const& lang)
  2841. {
  2842. std::string extension;
  2843. if (lang == "C") {
  2844. extension = "_c.c";
  2845. } else if (lang == "CXX") {
  2846. extension = "_cxx.cxx";
  2847. } else if (lang == "CUDA") {
  2848. extension = "_cu.cu";
  2849. } else if (lang == "OBJC") {
  2850. extension = "_m.m";
  2851. } else if (lang == "OBJCXX") {
  2852. extension = "_mm.mm";
  2853. }
  2854. return extension;
  2855. }
  2856. char const* unity_file_prefix(cmGeneratorTarget* target)
  2857. {
  2858. if (cmValue val = target->GetProperty("UNITY_BUILD_FILENAME_PREFIX")) {
  2859. return val->c_str();
  2860. }
  2861. return "unity_";
  2862. }
  2863. }
  2864. std::vector<cmLocalGenerator::UnitySource>
  2865. cmLocalGenerator::AddUnityFilesModeAuto(
  2866. cmGeneratorTarget* target, std::string const& lang,
  2867. std::vector<std::string> const& configs,
  2868. std::vector<UnityBatchedSource> const& filtered_sources,
  2869. cmValue beforeInclude, cmValue afterInclude,
  2870. std::string const& filename_base, UnityPathMode pathMode, size_t batchSize)
  2871. {
  2872. if (batchSize == 0) {
  2873. batchSize = filtered_sources.size();
  2874. }
  2875. char const* filename_prefix = unity_file_prefix(target);
  2876. std::vector<UnitySource> unity_files;
  2877. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2878. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2879. chunk = std::min(itemsLeft, batchSize);
  2880. std::string filename = cmStrCat(filename_base, filename_prefix, batch,
  2881. unity_file_extension(lang));
  2882. auto const begin = filtered_sources.begin() + batch * batchSize;
  2883. auto const end = begin + chunk;
  2884. unity_files.emplace_back(this->WriteUnitySource(
  2885. target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
  2886. std::move(filename), filename_base, pathMode));
  2887. }
  2888. return unity_files;
  2889. }
  2890. std::vector<cmLocalGenerator::UnitySource>
  2891. cmLocalGenerator::AddUnityFilesModeGroup(
  2892. cmGeneratorTarget* target, std::string const& lang,
  2893. std::vector<std::string> const& configs,
  2894. std::vector<UnityBatchedSource> const& filtered_sources,
  2895. cmValue beforeInclude, cmValue afterInclude,
  2896. std::string const& filename_base, UnityPathMode pathMode)
  2897. {
  2898. std::vector<UnitySource> unity_files;
  2899. // sources organized by group name. Drop any source
  2900. // without a group
  2901. std::unordered_map<std::string, std::vector<UnityBatchedSource>>
  2902. explicit_mapping;
  2903. for (UnityBatchedSource const& ubs : filtered_sources) {
  2904. if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
  2905. auto i = explicit_mapping.find(*value);
  2906. if (i == explicit_mapping.end()) {
  2907. std::vector<UnityBatchedSource> sources{ ubs };
  2908. explicit_mapping.emplace(*value, std::move(sources));
  2909. } else {
  2910. i->second.emplace_back(ubs);
  2911. }
  2912. }
  2913. }
  2914. char const* filename_prefix = unity_file_prefix(target);
  2915. for (auto const& item : explicit_mapping) {
  2916. auto const& name = item.first;
  2917. std::string filename = cmStrCat(filename_base, filename_prefix, name,
  2918. unity_file_extension(lang));
  2919. unity_files.emplace_back(this->WriteUnitySource(
  2920. target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
  2921. std::move(filename), filename_base, pathMode));
  2922. }
  2923. return unity_files;
  2924. }
  2925. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2926. {
  2927. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2928. return;
  2929. }
  2930. std::vector<UnityBatchedSource> unitySources;
  2931. std::vector<std::string> configs =
  2932. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2933. std::map<cmSourceFile const*, size_t> index;
  2934. for (size_t ci = 0; ci < configs.size(); ++ci) {
  2935. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2936. // Their final set of object files might be transformed by unity builds.
  2937. std::vector<cmSourceFile*> sources;
  2938. target->GetSourceFiles(sources, configs[ci]);
  2939. for (cmSourceFile* sf : sources) {
  2940. // Files which need C++ scanning cannot participate in unity builds as
  2941. // there is a single place in TUs that may perform module-dependency bits
  2942. // and a unity source cannot `#include` them in-order and represent a
  2943. // valid TU.
  2944. if (sf->GetLanguage() == "CXX"_s &&
  2945. target->NeedDyndepForSource("CXX", configs[ci], sf)) {
  2946. continue;
  2947. }
  2948. auto mi = index.find(sf);
  2949. if (mi == index.end()) {
  2950. unitySources.emplace_back(sf);
  2951. std::map<cmSourceFile const*, size_t>::value_type entry(
  2952. sf, unitySources.size() - 1);
  2953. mi = index.insert(entry).first;
  2954. }
  2955. unitySources[mi->second].Configs.emplace_back(ci);
  2956. }
  2957. }
  2958. std::string filename_base =
  2959. cmStrCat(target->GetCMFSupportDirectory(), "/Unity/");
  2960. cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2961. size_t const unityBatchSize = batchSizeString
  2962. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2963. : 0;
  2964. cmValue beforeInclude =
  2965. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2966. cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2967. cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2968. UnityPathMode pathMode = target->GetPropertyAsBool("UNITY_BUILD_RELOCATABLE")
  2969. ? UnityPathMode::Relative
  2970. : UnityPathMode::Absolute;
  2971. for (std::string lang : { "C", "CXX", "OBJC", "OBJCXX", "CUDA" }) {
  2972. std::vector<UnityBatchedSource> filtered_sources;
  2973. std::copy_if(unitySources.begin(), unitySources.end(),
  2974. std::back_inserter(filtered_sources),
  2975. [&](UnityBatchedSource const& ubs) -> bool {
  2976. cmSourceFile* sf = ubs.Source;
  2977. return sf->GetLanguage() == lang &&
  2978. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2979. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2980. !sf->GetProperty("COMPILE_OPTIONS") &&
  2981. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2982. !sf->GetProperty("COMPILE_FLAGS") &&
  2983. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2984. });
  2985. std::vector<UnitySource> unity_files;
  2986. if (!unityMode || *unityMode == "BATCH") {
  2987. unity_files = AddUnityFilesModeAuto(
  2988. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2989. filename_base, pathMode, unityBatchSize);
  2990. } else if (unityMode && *unityMode == "GROUP") {
  2991. unity_files = AddUnityFilesModeGroup(
  2992. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2993. filename_base, pathMode);
  2994. } else {
  2995. // unity mode is set to an unsupported value
  2996. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2997. " assigned to target " + target->GetName() +
  2998. ". Acceptable values are BATCH and GROUP.");
  2999. this->IssueMessage(MessageType::FATAL_ERROR, e);
  3000. }
  3001. for (UnitySource const& file : unity_files) {
  3002. auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
  3003. unity->SetSpecialSourceType(
  3004. cmSourceFile::SpecialSourceType::UnitySource);
  3005. target->AddSource(file.Path, true);
  3006. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  3007. unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
  3008. unity->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  3009. if (file.PerConfig) {
  3010. unity->SetProperty("COMPILE_DEFINITIONS",
  3011. "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
  3012. }
  3013. if (pathMode == UnityPathMode::Relative) {
  3014. unity->AppendProperty("INCLUDE_DIRECTORIES",
  3015. this->GetSourceDirectory(), false);
  3016. }
  3017. }
  3018. }
  3019. }
  3020. void cmLocalGenerator::AppendTargetCreationLinkFlags(
  3021. std::string& flags, cmGeneratorTarget const* target,
  3022. std::string const& linkLanguage)
  3023. {
  3024. std::string createFlagsVar;
  3025. cmValue createFlagsVal;
  3026. switch (target->GetType()) {
  3027. case cmStateEnums::STATIC_LIBRARY:
  3028. break;
  3029. case cmStateEnums::MODULE_LIBRARY:
  3030. createFlagsVar =
  3031. cmStrCat("CMAKE_SHARED_MODULE_CREATE_", linkLanguage, "_FLAGS");
  3032. createFlagsVal = this->Makefile->GetDefinition(createFlagsVar);
  3033. // On some platforms we use shared library creation flags for modules.
  3034. CM_FALLTHROUGH;
  3035. case cmStateEnums::SHARED_LIBRARY:
  3036. if (!createFlagsVal) {
  3037. createFlagsVar =
  3038. cmStrCat("CMAKE_SHARED_LIBRARY_CREATE_", linkLanguage, "_FLAGS");
  3039. createFlagsVal = this->Makefile->GetDefinition(createFlagsVar);
  3040. }
  3041. break;
  3042. case cmStateEnums::EXECUTABLE:
  3043. createFlagsVar = cmStrCat("CMAKE_", linkLanguage, "_LINK_FLAGS");
  3044. createFlagsVal = this->Makefile->GetDefinition(createFlagsVar);
  3045. break;
  3046. default:
  3047. break;
  3048. }
  3049. if (createFlagsVal) {
  3050. this->AppendFlags(flags, *createFlagsVal, createFlagsVar, target,
  3051. cmBuildStep::Link, linkLanguage);
  3052. }
  3053. }
  3054. void cmLocalGenerator::AppendLinkerTypeFlags(std::string& flags,
  3055. cmGeneratorTarget* target,
  3056. std::string const& config,
  3057. std::string const& linkLanguage)
  3058. {
  3059. switch (target->GetType()) {
  3060. case cmStateEnums::EXECUTABLE:
  3061. case cmStateEnums::SHARED_LIBRARY:
  3062. case cmStateEnums::MODULE_LIBRARY:
  3063. break;
  3064. default:
  3065. return;
  3066. }
  3067. auto linkMode =
  3068. cmStrCat("CMAKE_", linkLanguage, target->IsDeviceLink() ? "_DEVICE_" : "_",
  3069. "LINK_MODE");
  3070. auto mode = this->Makefile->GetDefinition(linkMode);
  3071. if (mode && mode != "DRIVER"_s) {
  3072. return;
  3073. }
  3074. auto linkerType = target->GetLinkerTypeProperty(linkLanguage, config);
  3075. if (linkerType.empty()) {
  3076. linkerType = "DEFAULT";
  3077. }
  3078. auto usingLinker =
  3079. cmStrCat("CMAKE_", linkLanguage, "_USING_",
  3080. target->IsDeviceLink() ? "DEVICE_" : "", "LINKER_", linkerType);
  3081. auto linkerTypeFlags = this->Makefile->GetDefinition(usingLinker);
  3082. if (linkerTypeFlags) {
  3083. if (!linkerTypeFlags.IsEmpty()) {
  3084. auto linkerFlags = cmExpandListWithBacktrace(linkerTypeFlags);
  3085. target->ResolveLinkerWrapper(linkerFlags, linkLanguage);
  3086. this->AppendFlags(flags, linkerFlags);
  3087. }
  3088. } else if (linkerType != "DEFAULT"_s) {
  3089. auto isCMakeLinkerType = [](std::string const& type) -> bool {
  3090. return std::all_of(type.cbegin(), type.cend(),
  3091. [](char c) { return std::isupper(c); });
  3092. };
  3093. if (isCMakeLinkerType(linkerType)) {
  3094. this->IssueMessage(
  3095. MessageType::FATAL_ERROR,
  3096. cmStrCat("LINKER_TYPE '", linkerType,
  3097. "' is unknown or not supported by this toolchain."));
  3098. } else {
  3099. this->IssueMessage(
  3100. MessageType::FATAL_ERROR,
  3101. cmStrCat("LINKER_TYPE '", linkerType,
  3102. "' is unknown. Did you forget to define the '", usingLinker,
  3103. "' variable?"));
  3104. }
  3105. }
  3106. }
  3107. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  3108. cmGeneratorTarget* target,
  3109. std::string const& config,
  3110. std::string const& lang)
  3111. {
  3112. if (!target->IsIPOEnabled(lang, config)) {
  3113. return;
  3114. }
  3115. switch (target->GetType()) {
  3116. case cmStateEnums::EXECUTABLE:
  3117. case cmStateEnums::SHARED_LIBRARY:
  3118. case cmStateEnums::MODULE_LIBRARY:
  3119. break;
  3120. default:
  3121. return;
  3122. }
  3123. std::string const name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  3124. cmValue rawFlagsList = this->Makefile->GetDefinition(name);
  3125. if (!rawFlagsList) {
  3126. return;
  3127. }
  3128. cmList flagsList{ *rawFlagsList };
  3129. for (std::string const& o : flagsList) {
  3130. this->AppendFlagEscape(flags, o);
  3131. }
  3132. }
  3133. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  3134. std::string& flags, cmGeneratorTarget* target, std::string const& config,
  3135. std::string const& lang)
  3136. {
  3137. // For now, only EXECUTABLE is concerned
  3138. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  3139. return;
  3140. }
  3141. char const* PICValue = target->GetLinkPIEProperty(config);
  3142. if (!PICValue) {
  3143. // POSITION_INDEPENDENT_CODE is not set
  3144. return;
  3145. }
  3146. std::string const mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  3147. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  3148. if (this->Makefile->GetDefinition(supported).IsOff()) {
  3149. return;
  3150. }
  3151. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  3152. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  3153. if (pieFlags.empty()) {
  3154. return;
  3155. }
  3156. cmList flagsList{ pieFlags };
  3157. for (auto const& flag : flagsList) {
  3158. this->AppendFlagEscape(flags, flag);
  3159. }
  3160. }
  3161. void cmLocalGenerator::AppendWarningAsErrorLinkerFlags(
  3162. std::string& flags, cmGeneratorTarget* target, std::string const& lang)
  3163. {
  3164. if (this->GetCMakeInstance()->GetIgnoreLinkWarningAsError()) {
  3165. return;
  3166. }
  3167. switch (target->GetType()) {
  3168. case cmStateEnums::EXECUTABLE:
  3169. case cmStateEnums::SHARED_LIBRARY:
  3170. case cmStateEnums::MODULE_LIBRARY:
  3171. break;
  3172. default:
  3173. return;
  3174. }
  3175. auto const wError = target->GetProperty("LINK_WARNING_AS_ERROR");
  3176. if (wError.IsOff()) {
  3177. return;
  3178. }
  3179. cmList wErrorOptions;
  3180. if (wError.IsOn()) {
  3181. wErrorOptions = { "DRIVER", "LINKER" };
  3182. } else {
  3183. wErrorOptions = wError;
  3184. std::sort(wErrorOptions.begin(), wErrorOptions.end());
  3185. wErrorOptions.erase(
  3186. std::unique(wErrorOptions.begin(), wErrorOptions.end()),
  3187. wErrorOptions.end());
  3188. }
  3189. auto linkModeIsDriver =
  3190. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_LINK_MODE")) ==
  3191. "DRIVER"_s;
  3192. std::string errorMessage;
  3193. for (auto const& option : wErrorOptions) {
  3194. if (option != "DRIVER"_s && option != "LINKER"_s) {
  3195. errorMessage += cmStrCat(" ", option, '\n');
  3196. continue;
  3197. }
  3198. if (option == "DRIVER"_s && !linkModeIsDriver) {
  3199. continue;
  3200. }
  3201. auto const wErrorOpts = this->Makefile->GetDefinition(cmStrCat(
  3202. "CMAKE_", lang, '_', (option == "DRIVER"_s ? "COMPILE" : "LINK"),
  3203. "_OPTIONS_WARNING_AS_ERROR"));
  3204. if (wErrorOpts.IsSet()) {
  3205. auto items =
  3206. cmExpandListWithBacktrace(wErrorOpts, target->GetBacktrace());
  3207. if (option == "LINKER"_s) {
  3208. target->ResolveLinkerWrapper(items, lang);
  3209. }
  3210. for (auto const& item : items) {
  3211. this->AppendFlagEscape(flags, item.Value);
  3212. }
  3213. }
  3214. }
  3215. if (!errorMessage.empty()) {
  3216. this->Makefile->GetCMakeInstance()->IssueMessage(
  3217. MessageType::FATAL_ERROR,
  3218. cmStrCat(
  3219. "Erroneous value(s) for 'LINK_WARNING_AS_ERROR' property of target '",
  3220. target->GetName(), "':\n", errorMessage));
  3221. }
  3222. }
  3223. void cmLocalGenerator::AppendDependencyInfoLinkerFlags(
  3224. std::string& flags, cmGeneratorTarget* target, std::string const& config,
  3225. std::string const& linkLanguage)
  3226. {
  3227. if (!this->GetGlobalGenerator()->SupportsLinkerDependencyFile() ||
  3228. !target->HasLinkDependencyFile(config)) {
  3229. return;
  3230. }
  3231. auto depFlag = *this->Makefile->GetDefinition(
  3232. cmStrCat("CMAKE_", linkLanguage, "_LINKER_DEPFILE_FLAGS"));
  3233. if (depFlag.empty()) {
  3234. return;
  3235. }
  3236. auto depFile = this->ConvertToOutputFormat(
  3237. this->MaybeRelativeToWorkDir(this->GetLinkDependencyFile(target, config)),
  3238. cmOutputConverter::SHELL);
  3239. auto rulePlaceholderExpander = this->CreateRulePlaceholderExpander();
  3240. cmRulePlaceholderExpander::RuleVariables linkDepsVariables;
  3241. linkDepsVariables.DependencyFile = depFile.c_str();
  3242. rulePlaceholderExpander->ExpandRuleVariables(this, depFlag,
  3243. linkDepsVariables);
  3244. auto depFlags = cmExpandListWithBacktrace(depFlag);
  3245. target->ResolveLinkerWrapper(depFlags, linkLanguage);
  3246. this->AppendFlags(flags, depFlags);
  3247. }
  3248. std::string cmLocalGenerator::GetLinkDependencyFile(
  3249. cmGeneratorTarget* /*target*/, std::string const& /*config*/) const
  3250. {
  3251. return "link.d";
  3252. }
  3253. void cmLocalGenerator::AppendModuleDefinitionFlag(
  3254. std::string& flags, cmGeneratorTarget const* target,
  3255. cmLinkLineComputer* linkLineComputer, std::string const& config,
  3256. std::string const& lang)
  3257. {
  3258. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  3259. target->GetModuleDefinitionInfo(config);
  3260. if (!mdi || mdi->DefFile.empty()) {
  3261. return;
  3262. }
  3263. cmValue defFileFlag = this->Makefile->GetDefinition(
  3264. cmStrCat("CMAKE_", lang, "_LINK_DEF_FILE_FLAG"));
  3265. if (!defFileFlag) {
  3266. defFileFlag = this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  3267. }
  3268. if (!defFileFlag) {
  3269. return;
  3270. }
  3271. // Append the flag and value. Use ConvertToLinkReference to help
  3272. // vs6's "cl -link" pass it to the linker.
  3273. std::string flag =
  3274. cmStrCat(*defFileFlag,
  3275. this->ConvertToOutputFormat(
  3276. linkLineComputer->ConvertToLinkReference(mdi->DefFile),
  3277. cmOutputConverter::SHELL));
  3278. this->AppendFlags(flags, flag);
  3279. }
  3280. bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
  3281. cmGeneratorTarget const* target,
  3282. std::string const& lang)
  3283. {
  3284. auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  3285. (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
  3286. target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
  3287. target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
  3288. if (useLWYU) {
  3289. auto const& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
  3290. cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
  3291. useLWYU = !lwyuFlag.empty();
  3292. if (useLWYU) {
  3293. std::vector<BT<std::string>> lwyuOpts;
  3294. lwyuOpts.emplace_back(lwyuFlag);
  3295. this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
  3296. }
  3297. }
  3298. return useLWYU;
  3299. }
  3300. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  3301. std::string const& options_list,
  3302. char const* regex) const
  3303. {
  3304. // Short-circuit if there are no options.
  3305. if (options_list.empty()) {
  3306. return;
  3307. }
  3308. // Expand the list of options.
  3309. cmList options_vec{ options_list };
  3310. this->AppendCompileOptions(options, options_vec, regex);
  3311. }
  3312. void cmLocalGenerator::AppendCompileOptions(
  3313. std::string& options, std::vector<std::string> const& options_vec,
  3314. char const* regex) const
  3315. {
  3316. if (regex) {
  3317. // Filter flags upon specified reges.
  3318. cmsys::RegularExpression r(regex);
  3319. for (std::string const& opt : options_vec) {
  3320. if (r.find(opt)) {
  3321. this->AppendFlagEscape(options, opt);
  3322. }
  3323. }
  3324. } else {
  3325. for (std::string const& opt : options_vec) {
  3326. this->AppendFlagEscape(options, opt);
  3327. }
  3328. }
  3329. }
  3330. void cmLocalGenerator::AppendCompileOptions(
  3331. std::vector<BT<std::string>>& options,
  3332. std::vector<BT<std::string>> const& options_vec, char const* regex) const
  3333. {
  3334. if (regex) {
  3335. // Filter flags upon specified regular expressions.
  3336. cmsys::RegularExpression r(regex);
  3337. for (BT<std::string> const& opt : options_vec) {
  3338. if (r.find(opt.Value)) {
  3339. std::string flag;
  3340. this->AppendFlagEscape(flag, opt.Value);
  3341. options.emplace_back(std::move(flag), opt.Backtrace);
  3342. }
  3343. }
  3344. } else {
  3345. for (BT<std::string> const& opt : options_vec) {
  3346. std::string flag;
  3347. this->AppendFlagEscape(flag, opt.Value);
  3348. options.emplace_back(std::move(flag), opt.Backtrace);
  3349. }
  3350. }
  3351. }
  3352. void cmLocalGenerator::AppendIncludeDirectories(
  3353. std::vector<std::string>& includes, std::string const& includes_list,
  3354. cmSourceFile const& sourceFile) const
  3355. {
  3356. // Short-circuit if there are no includes.
  3357. if (includes_list.empty()) {
  3358. return;
  3359. }
  3360. // Expand the list of includes.
  3361. cmList includes_vec{ includes_list };
  3362. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  3363. }
  3364. void cmLocalGenerator::AppendIncludeDirectories(
  3365. std::vector<std::string>& includes,
  3366. std::vector<std::string> const& includes_vec,
  3367. cmSourceFile const& sourceFile) const
  3368. {
  3369. std::unordered_set<std::string> uniqueIncludes;
  3370. for (std::string const& include : includes_vec) {
  3371. if (!cmSystemTools::FileIsFullPath(include)) {
  3372. std::ostringstream e;
  3373. e << "Found relative path while evaluating include directories of "
  3374. "\""
  3375. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  3376. << "\"\n";
  3377. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3378. return;
  3379. }
  3380. std::string inc = include;
  3381. if (!cmIsOff(inc)) {
  3382. cmSystemTools::ConvertToUnixSlashes(inc);
  3383. }
  3384. if (uniqueIncludes.insert(inc).second) {
  3385. includes.push_back(std::move(inc));
  3386. }
  3387. }
  3388. }
  3389. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  3390. std::string const& defines_list) const
  3391. {
  3392. std::set<BT<std::string>> tmp;
  3393. this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
  3394. for (BT<std::string> const& i : tmp) {
  3395. defines.emplace(i.Value);
  3396. }
  3397. }
  3398. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  3399. std::string const& defines_list) const
  3400. {
  3401. // Short-circuit if there are no definitions.
  3402. if (defines_list.empty()) {
  3403. return;
  3404. }
  3405. // Expand the list of definitions.
  3406. this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
  3407. }
  3408. void cmLocalGenerator::AppendDefines(
  3409. std::set<BT<std::string>>& defines,
  3410. std::vector<BT<std::string>> const& defines_vec) const
  3411. {
  3412. for (BT<std::string> const& d : defines_vec) {
  3413. // Skip unsupported definitions.
  3414. if (!this->CheckDefinition(d.Value)) {
  3415. continue;
  3416. }
  3417. // remove any leading -D
  3418. if (cmHasLiteralPrefix(d.Value, "-D")) {
  3419. defines.emplace(d.Value.substr(2), d.Backtrace);
  3420. } else {
  3421. defines.insert(d);
  3422. }
  3423. }
  3424. }
  3425. void cmLocalGenerator::JoinDefines(std::set<std::string> const& defines,
  3426. std::string& definesString,
  3427. std::string const& lang)
  3428. {
  3429. // Lookup the define flag for the current language.
  3430. std::string dflag = "-D";
  3431. if (!lang.empty()) {
  3432. cmValue df =
  3433. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  3434. if (cmNonempty(df)) {
  3435. dflag = *df;
  3436. }
  3437. }
  3438. char const* itemSeparator = definesString.empty() ? "" : " ";
  3439. for (std::string const& define : defines) {
  3440. // Append the definition with proper escaping.
  3441. std::string def = dflag;
  3442. if (this->GetState()->UseWatcomWMake()) {
  3443. // The Watcom compiler does its own command line parsing instead
  3444. // of using the windows shell rules. Definitions are one of
  3445. // -DNAME
  3446. // -DNAME=<cpp-token>
  3447. // -DNAME="c-string with spaces and other characters(?@#$)"
  3448. //
  3449. // Watcom will properly parse each of these cases from the
  3450. // command line without any escapes. However we still have to
  3451. // get the '$' and '#' characters through WMake as '$$' and
  3452. // '$#'.
  3453. for (char c : define) {
  3454. if (c == '$' || c == '#') {
  3455. def += '$';
  3456. }
  3457. def += c;
  3458. }
  3459. } else {
  3460. // Make the definition appear properly on the command line. Use
  3461. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  3462. std::string::size_type eq = define.find('=');
  3463. def += define.substr(0, eq);
  3464. if (eq != std::string::npos) {
  3465. def += "=";
  3466. def += this->EscapeForShell(define.substr(eq + 1), true);
  3467. }
  3468. }
  3469. definesString += itemSeparator;
  3470. itemSeparator = " ";
  3471. definesString += def;
  3472. }
  3473. }
  3474. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  3475. std::string const& lang,
  3476. char const* feature)
  3477. {
  3478. cmValue optionList = this->Makefile->GetDefinition(
  3479. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  3480. if (optionList) {
  3481. cmList options{ *optionList };
  3482. for (std::string const& o : options) {
  3483. this->AppendFlagEscape(flags, o);
  3484. }
  3485. }
  3486. }
  3487. cmValue cmLocalGenerator::GetFeature(std::string const& feature,
  3488. std::string const& config)
  3489. {
  3490. std::string featureName = feature;
  3491. // TODO: Define accumulation policy for features (prepend, append,
  3492. // replace). Currently we always replace.
  3493. if (!config.empty()) {
  3494. featureName += "_";
  3495. featureName += cmSystemTools::UpperCase(config);
  3496. }
  3497. cmStateSnapshot snp = this->StateSnapshot;
  3498. while (snp.IsValid()) {
  3499. if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
  3500. return value;
  3501. }
  3502. snp = snp.GetBuildsystemDirectoryParent();
  3503. }
  3504. return nullptr;
  3505. }
  3506. std::string cmLocalGenerator::GetProjectName() const
  3507. {
  3508. return this->StateSnapshot.GetProjectName();
  3509. }
  3510. std::string cmLocalGenerator::ConstructComment(
  3511. cmCustomCommandGenerator const& ccg, char const* default_comment) const
  3512. {
  3513. // Check for a comment provided with the command.
  3514. if (cm::optional<std::string> comment = ccg.GetComment()) {
  3515. return *comment;
  3516. }
  3517. // Construct a reasonable default comment if possible.
  3518. if (!ccg.GetOutputs().empty()) {
  3519. std::string comment;
  3520. comment = "Generating ";
  3521. char const* sep = "";
  3522. for (std::string const& o : ccg.GetOutputs()) {
  3523. comment += sep;
  3524. comment += this->MaybeRelativeToCurBinDir(o);
  3525. sep = ", ";
  3526. }
  3527. return comment;
  3528. }
  3529. // Otherwise use the provided default.
  3530. return default_comment;
  3531. }
  3532. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  3533. {
  3534. public:
  3535. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  3536. std::string const& dest, bool implib)
  3537. : cmInstallTargetGenerator(
  3538. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  3539. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  3540. false)
  3541. {
  3542. this->Compute(lg);
  3543. }
  3544. };
  3545. void cmLocalGenerator::GenerateTargetInstallRules(
  3546. std::ostream& os, std::string const& config,
  3547. std::vector<std::string> const& configurationTypes)
  3548. {
  3549. // Convert the old-style install specification from each target to
  3550. // an install generator and run it.
  3551. auto const& tgts = this->GetGeneratorTargets();
  3552. for (auto const& l : tgts) {
  3553. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3554. continue;
  3555. }
  3556. // Include the user-specified pre-install script for this target.
  3557. if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3558. cmInstallScriptGenerator g(*preinstall, false, "", false, false);
  3559. g.Generate(os, config, configurationTypes);
  3560. }
  3561. // Install this target if a destination is given.
  3562. if (!l->Target->GetInstallPath().empty()) {
  3563. // Compute the full install destination. Note that converting
  3564. // to unix slashes also removes any trailing slash.
  3565. // We also skip over the leading slash given by the user.
  3566. std::string destination = l->Target->GetInstallPath().substr(1);
  3567. cmSystemTools::ConvertToUnixSlashes(destination);
  3568. if (destination.empty()) {
  3569. destination = ".";
  3570. }
  3571. // Generate the proper install generator for this target type.
  3572. switch (l->GetType()) {
  3573. case cmStateEnums::EXECUTABLE:
  3574. case cmStateEnums::STATIC_LIBRARY:
  3575. case cmStateEnums::MODULE_LIBRARY: {
  3576. // Use a target install generator.
  3577. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3578. false);
  3579. g.Generate(os, config, configurationTypes);
  3580. } break;
  3581. case cmStateEnums::SHARED_LIBRARY: {
  3582. #if defined(_WIN32) || defined(__CYGWIN__)
  3583. // Special code to handle DLL. Install the import library
  3584. // to the normal destination and the DLL to the runtime
  3585. // destination.
  3586. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3587. true);
  3588. g1.Generate(os, config, configurationTypes);
  3589. // We also skip over the leading slash given by the user.
  3590. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3591. cmSystemTools::ConvertToUnixSlashes(destination);
  3592. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3593. false);
  3594. g2.Generate(os, config, configurationTypes);
  3595. #else
  3596. // Use a target install generator.
  3597. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3598. false);
  3599. g.Generate(os, config, configurationTypes);
  3600. #endif
  3601. } break;
  3602. default:
  3603. break;
  3604. }
  3605. }
  3606. // Include the user-specified post-install script for this target.
  3607. if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3608. cmInstallScriptGenerator g(*postinstall, false, "", false, false);
  3609. g.Generate(os, config, configurationTypes);
  3610. }
  3611. }
  3612. }
  3613. namespace {
  3614. bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3615. std::string::size_type max_len)
  3616. {
  3617. // Check if the path can be shortened using an md5 sum replacement for
  3618. // a portion of the path.
  3619. std::string::size_type md5Len = 32;
  3620. std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
  3621. std::string::size_type pos = objName.find('/', numExtraChars);
  3622. if (pos == std::string::npos) {
  3623. pos = objName.rfind('/', numExtraChars);
  3624. if (pos == std::string::npos || pos <= md5Len) {
  3625. return false;
  3626. }
  3627. }
  3628. // Replace the beginning of the path portion of the object name with
  3629. // its own md5 sum.
  3630. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3631. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3632. cm::string_view(objName).substr(pos));
  3633. objName = md5name;
  3634. // The object name is now shorter, check if it is short enough.
  3635. return pos >= numExtraChars;
  3636. }
  3637. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3638. std::string::size_type dir_len,
  3639. std::string::size_type max_total_len)
  3640. {
  3641. // Enforce the maximum file name length if possible.
  3642. std::string::size_type max_obj_len = max_total_len;
  3643. if (dir_len < max_total_len) {
  3644. max_obj_len = max_total_len - dir_len;
  3645. if (objName.size() > max_obj_len) {
  3646. // The current object file name is too long. Try to shorten it.
  3647. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3648. }
  3649. // The object file name is short enough.
  3650. return true;
  3651. }
  3652. // The build directory in which the object will be stored is
  3653. // already too deep.
  3654. return false;
  3655. }
  3656. }
  3657. std::string cmLocalGenerator::CreateSafeObjectFileName(
  3658. std::string const& sin) const
  3659. {
  3660. // Start with the original name.
  3661. std::string ssin = sin;
  3662. // Avoid full paths by removing leading slashes.
  3663. ssin.erase(0, ssin.find_first_not_of('/'));
  3664. // Avoid full paths by removing colons.
  3665. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3666. // Avoid relative paths that go up the tree.
  3667. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3668. // Avoid spaces.
  3669. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3670. return ssin;
  3671. }
  3672. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3673. std::string const& sin, std::string const& dir_max)
  3674. {
  3675. // Look for an existing mapped name for this object file.
  3676. auto it = this->UniqueObjectNamesMap.find(sin);
  3677. // If no entry exists create one.
  3678. if (it == this->UniqueObjectNamesMap.end()) {
  3679. auto ssin = this->CreateSafeObjectFileName(sin);
  3680. // Mangle the name if necessary.
  3681. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3682. bool done;
  3683. int cc = 0;
  3684. char rpstr[100];
  3685. snprintf(rpstr, sizeof(rpstr), "_p_");
  3686. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3687. std::string sssin = sin;
  3688. do {
  3689. done = true;
  3690. for (it = this->UniqueObjectNamesMap.begin();
  3691. it != this->UniqueObjectNamesMap.end(); ++it) {
  3692. if (it->second == ssin) {
  3693. done = false;
  3694. }
  3695. }
  3696. if (done) {
  3697. break;
  3698. }
  3699. sssin = ssin;
  3700. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3701. snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
  3702. } while (!done);
  3703. }
  3704. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3705. this->ObjectPathMax)) {
  3706. // Warn if this is the first time the path has been seen.
  3707. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3708. std::ostringstream m;
  3709. /* clang-format off */
  3710. m << "The object file directory\n"
  3711. << " " << dir_max << "\n"
  3712. << "has " << dir_max.size() << " characters. "
  3713. << "The maximum full path to an object file is "
  3714. << this->ObjectPathMax << " characters "
  3715. << "(see CMAKE_OBJECT_PATH_MAX). "
  3716. << "Object file\n"
  3717. << " " << ssin << "\n"
  3718. << "cannot be safely placed under this directory. "
  3719. << "The build may not work correctly.";
  3720. /* clang-format on */
  3721. this->IssueMessage(MessageType::WARNING, m.str());
  3722. }
  3723. }
  3724. // Insert the newly mapped object file name.
  3725. std::map<std::string, std::string>::value_type e(sin, ssin);
  3726. it = this->UniqueObjectNamesMap.insert(e).first;
  3727. }
  3728. // Return the map entry.
  3729. return it->second;
  3730. }
  3731. void cmLocalGenerator::ComputeObjectFilenames(
  3732. std::map<cmSourceFile const*, cmObjectLocations>& /*unused*/,
  3733. std::string const& /*unused*/, cmGeneratorTarget const* /*unused*/)
  3734. {
  3735. }
  3736. bool cmLocalGenerator::IsWindowsShell() const
  3737. {
  3738. return this->GetState()->UseWindowsShell();
  3739. }
  3740. bool cmLocalGenerator::IsWatcomWMake() const
  3741. {
  3742. return this->GetState()->UseWatcomWMake();
  3743. }
  3744. bool cmLocalGenerator::IsMinGWMake() const
  3745. {
  3746. return this->GetState()->UseMinGWMake();
  3747. }
  3748. bool cmLocalGenerator::IsNMake() const
  3749. {
  3750. return this->GetState()->UseNMake();
  3751. }
  3752. bool cmLocalGenerator::IsNinjaMulti() const
  3753. {
  3754. return this->GetState()->UseNinjaMulti();
  3755. }
  3756. namespace {
  3757. std::string relativeIfUnder(std::string const& top, std::string const& cur,
  3758. std::string const& path)
  3759. {
  3760. // Use a path relative to 'cur' if it can be expressed without
  3761. // a `../` sequence that leaves 'top'.
  3762. if (cmSystemTools::IsSubDirectory(path, cur) ||
  3763. (cmSystemTools::IsSubDirectory(cur, top) &&
  3764. cmSystemTools::IsSubDirectory(path, top))) {
  3765. return cmSystemTools::ForceToRelativePath(cur, path);
  3766. }
  3767. return path;
  3768. }
  3769. }
  3770. std::string cmLocalGenerator::GetRelativeSourceFileName(
  3771. cmSourceFile const& source) const
  3772. {
  3773. // Construct the object file name using the full path to the source
  3774. // file which is its only unique identification.
  3775. std::string const& fullPath = source.GetFullPath();
  3776. // Try referencing the source relative to the source tree.
  3777. std::string relFromSource = relativeIfUnder(
  3778. this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
  3779. assert(!relFromSource.empty());
  3780. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3781. bool subSource = relSource && relFromSource[0] != '.';
  3782. // Try referencing the source relative to the binary tree.
  3783. std::string relFromBinary = relativeIfUnder(
  3784. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
  3785. assert(!relFromBinary.empty());
  3786. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3787. bool subBinary = relBinary && relFromBinary[0] != '.';
  3788. // Select a nice-looking reference to the source file to construct
  3789. // the object file name.
  3790. std::string objectName;
  3791. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3792. // NOLINTNEXTLINE(bugprone-branch-clone)
  3793. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3794. objectName = relFromSource;
  3795. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3796. relFromBinary.length() < relFromSource.length()) {
  3797. objectName = relFromBinary;
  3798. } else {
  3799. objectName = relFromSource;
  3800. }
  3801. return objectName;
  3802. }
  3803. std::string cmLocalGenerator::GetCustomObjectFileName(
  3804. cmSourceFile const& source) const
  3805. {
  3806. if (!this->GetGlobalGenerator()->SupportsCustomObjectNames()) {
  3807. return std::string{};
  3808. }
  3809. if (auto objName = source.GetProperty("OBJECT_NAME")) {
  3810. cmGeneratorExpression ge(*this->GetCMakeInstance());
  3811. auto cge = ge.Parse(objName);
  3812. static std::string const INVALID_GENEX =
  3813. "_cmake_invalid_object_name_genex";
  3814. static std::string const INVALID_VALUE =
  3815. "_cmake_invalid_object_name_value";
  3816. if (!cge) {
  3817. this->Makefile->IssueMessage(
  3818. MessageType::FATAL_ERROR,
  3819. cmStrCat("The \"OBJECT_NAME\" property for\n ", source.GetFullPath(),
  3820. "\nis not a valid generator expression (", objName, ")."));
  3821. return INVALID_GENEX;
  3822. }
  3823. if (cge->GetHadHeadSensitiveCondition()) {
  3824. // Not reachable; all target-sensitive genexes actually fail to parse.
  3825. this->Makefile->IssueMessage(
  3826. MessageType::FATAL_ERROR,
  3827. cmStrCat("The \"OBJECT_NAME\" property for\n ", source.GetFullPath(),
  3828. "\ncontains a condition that queries the consuming target "
  3829. "which is not supported (",
  3830. objName, ")."));
  3831. return INVALID_GENEX;
  3832. }
  3833. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  3834. // Not reachable; all target-sensitive genexes actually fail to parse.
  3835. this->Makefile->IssueMessage(
  3836. MessageType::FATAL_ERROR,
  3837. cmStrCat("The \"OBJECT_NAME\" property for\n ", source.GetFullPath(),
  3838. "\ncontains a condition that queries the link language "
  3839. "which is not supported (",
  3840. objName, ")."));
  3841. return INVALID_GENEX;
  3842. }
  3843. auto objNameValue = cge->Evaluate(this, "");
  3844. if (cge->GetHadContextSensitiveCondition()) {
  3845. this->Makefile->IssueMessage(
  3846. MessageType::FATAL_ERROR,
  3847. cmStrCat("The \"OBJECT_NAME\" property for\n ", source.GetFullPath(),
  3848. "\ncontains a context-sensitive condition which is not "
  3849. "supported (",
  3850. objName, ")."));
  3851. return INVALID_GENEX;
  3852. }
  3853. // Skip if it evaluates to empty.
  3854. if (!objNameValue.empty()) {
  3855. cmCMakePath objNamePath = objNameValue;
  3856. // Verify that it is a relative path.
  3857. if (objNamePath.IsAbsolute()) {
  3858. this->Makefile->IssueMessage(
  3859. MessageType::FATAL_ERROR,
  3860. cmStrCat(
  3861. "The \"OBJECT_NAME\" property for\n ", source.GetFullPath(),
  3862. "\nresolves to an absolute path which is not supported:\n ",
  3863. objNameValue));
  3864. return INVALID_VALUE;
  3865. }
  3866. auto isInvalidComponent = [](cmCMakePath const& component) -> bool {
  3867. return component == ".."_s;
  3868. };
  3869. // Verify that it contains no `..` components.
  3870. if (std::any_of(objNamePath.begin(), objNamePath.end(),
  3871. isInvalidComponent)) {
  3872. this->Makefile->IssueMessage(
  3873. MessageType::FATAL_ERROR,
  3874. cmStrCat("The \"OBJECT_NAME\" property for\n ",
  3875. source.GetFullPath(), "\ncontains an invalid component (",
  3876. objNameValue, ")."));
  3877. return INVALID_VALUE;
  3878. }
  3879. return objNameValue;
  3880. }
  3881. }
  3882. return std::string{};
  3883. }
  3884. std::string cmLocalGenerator::GetCustomInstallObjectFileName(
  3885. cmSourceFile const& source, std::string const& config,
  3886. char const* custom_ext) const
  3887. {
  3888. if (auto objName = source.GetProperty("INSTALL_OBJECT_NAME")) {
  3889. cmGeneratorExpression ge(*this->GetCMakeInstance());
  3890. auto cge = ge.Parse(objName);
  3891. static std::string const INVALID_GENEX =
  3892. "_cmake_invalid_object_name_genex";
  3893. static std::string const INVALID_VALUE =
  3894. "_cmake_invalid_object_name_value";
  3895. if (!cge) {
  3896. this->Makefile->IssueMessage(
  3897. MessageType::FATAL_ERROR,
  3898. cmStrCat("The \"INSTALL_OBJECT_NAME\" property for\n ",
  3899. source.GetFullPath(),
  3900. "\nis not a valid generator expression (", objName, ")."));
  3901. return INVALID_GENEX;
  3902. }
  3903. if (cge->GetHadHeadSensitiveCondition()) {
  3904. // Not reachable; all target-sensitive genexes actually fail to parse.
  3905. this->Makefile->IssueMessage(
  3906. MessageType::FATAL_ERROR,
  3907. cmStrCat("The \"INSTALL_OBJECT_NAME\" property for\n ",
  3908. source.GetFullPath(),
  3909. "\ncontains a condition that queries the consuming target "
  3910. "which is not supported (",
  3911. objName, ")."));
  3912. return INVALID_GENEX;
  3913. }
  3914. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  3915. // Not reachable; all target-sensitive genexes actually fail to parse.
  3916. this->Makefile->IssueMessage(
  3917. MessageType::FATAL_ERROR,
  3918. cmStrCat("The \"INSTALL_OBJECT_NAME\" property for\n ",
  3919. source.GetFullPath(),
  3920. "\ncontains a condition that queries the link language "
  3921. "which is not supported (",
  3922. objName, ")."));
  3923. return INVALID_GENEX;
  3924. }
  3925. auto objNameValue = cge->Evaluate(this, config);
  3926. // Skip if it evaluates to empty.
  3927. if (!objNameValue.empty()) {
  3928. cmCMakePath objNamePath = objNameValue;
  3929. // Verify that it is a relative path.
  3930. if (objNamePath.IsAbsolute()) {
  3931. this->Makefile->IssueMessage(
  3932. MessageType::FATAL_ERROR,
  3933. cmStrCat(
  3934. "The \"INSTALL_OBJECT_NAME\" property for\n ",
  3935. source.GetFullPath(),
  3936. "\nresolves to an absolute path which is not supported:\n ",
  3937. objNameValue));
  3938. return INVALID_VALUE;
  3939. }
  3940. auto isInvalidComponent = [](cmCMakePath const& component) -> bool {
  3941. return component == ".."_s;
  3942. };
  3943. // Verify that it contains no `..` components.
  3944. if (std::any_of(objNamePath.begin(), objNamePath.end(),
  3945. isInvalidComponent)) {
  3946. this->Makefile->IssueMessage(
  3947. MessageType::FATAL_ERROR,
  3948. cmStrCat("The \"INSTALL_OBJECT_NAME\" property for\n ",
  3949. source.GetFullPath(), "\ncontains an invalid component (",
  3950. objNameValue, ")."));
  3951. return INVALID_VALUE;
  3952. }
  3953. if (custom_ext) {
  3954. objNameValue += custom_ext;
  3955. } else {
  3956. objNameValue +=
  3957. this->GetGlobalGenerator()->GetLanguageOutputExtension(source);
  3958. }
  3959. return objNameValue;
  3960. }
  3961. }
  3962. return std::string{};
  3963. }
  3964. void cmLocalGenerator::FillCustomInstallObjectLocations(
  3965. cmSourceFile const& source, std::string const& config,
  3966. char const* custom_ext,
  3967. std::map<std::string, cmObjectLocation>& mapping) const
  3968. {
  3969. auto installLoc =
  3970. this->GetCustomInstallObjectFileName(source, config, custom_ext);
  3971. if (!installLoc.empty()) {
  3972. mapping[config] = installLoc;
  3973. }
  3974. }
  3975. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3976. cmSourceFile const& source, std::string const& dir_max,
  3977. bool* hasSourceExtension, char const* customOutputExtension,
  3978. bool const* forceShortObjectName)
  3979. {
  3980. bool useShortObjectNames = this->UseShortObjectNames();
  3981. if (forceShortObjectName) {
  3982. useShortObjectNames = *forceShortObjectName;
  3983. }
  3984. if (!useShortObjectNames &&
  3985. this->GetGlobalGenerator()->SupportsCustomObjectNames()) {
  3986. auto customName = this->GetCustomObjectFileName(source);
  3987. if (!customName.empty()) {
  3988. auto ext = this->GlobalGenerator->GetLanguageOutputExtension(source);
  3989. if (customOutputExtension) {
  3990. ext = *customOutputExtension;
  3991. }
  3992. return cmStrCat(customName, ext);
  3993. }
  3994. }
  3995. // This can return an absolute path in the case where source is
  3996. // not relative to the current source or binary directories
  3997. std::string objectName = this->GetRelativeSourceFileName(source);
  3998. // if it is still a full path check for the try compile case
  3999. // try compile never have in source sources, and should not
  4000. // have conflicting source file names in the same target
  4001. if (cmSystemTools::FileIsFullPath(objectName)) {
  4002. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  4003. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  4004. }
  4005. }
  4006. bool const isPchObject = source.IsPchHeader() || source.IsPchSource();
  4007. // Short object path policy selected, use as little info as necessary to
  4008. // select an object name
  4009. bool keptSourceExtension = true;
  4010. if (useShortObjectNames) {
  4011. objectName = this->GetShortObjectFileName(source);
  4012. keptSourceExtension = false;
  4013. }
  4014. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  4015. // we don't end up having:
  4016. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  4017. cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  4018. cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
  4019. if (unitySourceFile || pchExtension || isPchObject) {
  4020. if (pchExtension) {
  4021. customOutputExtension = pchExtension->c_str();
  4022. }
  4023. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  4024. if (var.find(objectName)) {
  4025. objectName.erase(var.start(), var.end() - var.start());
  4026. }
  4027. }
  4028. // Replace the original source file extension with the object file
  4029. // extension.
  4030. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  4031. // Decide whether this language wants to replace the source
  4032. // extension with the object extension.
  4033. bool replaceExt = false;
  4034. std::string lang = source.GetLanguage();
  4035. if (!lang.empty()) {
  4036. replaceExt = this->Makefile->IsOn(
  4037. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  4038. }
  4039. // Remove the source extension if it is to be replaced.
  4040. if (replaceExt || customOutputExtension) {
  4041. keptSourceExtension = false;
  4042. std::string::size_type dot_pos = objectName.rfind('.');
  4043. if (dot_pos != std::string::npos) {
  4044. objectName = objectName.substr(0, dot_pos);
  4045. }
  4046. }
  4047. // Strip source file extension when shortening object file paths
  4048. if (this->UseShortObjectNames()) {
  4049. objectName = cmSystemTools::GetFilenameWithoutExtension(objectName);
  4050. }
  4051. // Store the new extension.
  4052. if (customOutputExtension) {
  4053. objectName += customOutputExtension;
  4054. } else {
  4055. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  4056. }
  4057. }
  4058. if (hasSourceExtension) {
  4059. *hasSourceExtension = keptSourceExtension;
  4060. }
  4061. // Convert to a safe name.
  4062. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  4063. }
  4064. bool cmLocalGenerator::UseShortObjectNames(
  4065. cmStateEnums::IntermediateDirKind kind) const
  4066. {
  4067. return this->GlobalGenerator->UseShortObjectNames(kind);
  4068. }
  4069. std::string cmLocalGenerator::GetObjectOutputRoot(
  4070. cmStateEnums::IntermediateDirKind kind) const
  4071. {
  4072. if (this->UseShortObjectNames(kind)) {
  4073. return cmStrCat(this->GetCurrentBinaryDirectory(), '/',
  4074. this->GlobalGenerator->GetShortBinaryOutputDir());
  4075. }
  4076. return cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
  4077. }
  4078. bool cmLocalGenerator::AlwaysUsesCMFPaths() const
  4079. {
  4080. return true;
  4081. }
  4082. std::string cmLocalGenerator::GetShortObjectFileName(
  4083. cmSourceFile const& source) const
  4084. {
  4085. std::string objectName = this->GetRelativeSourceFileName(source);
  4086. std::string objectFileName =
  4087. cmSystemTools::GetFilenameName(source.GetFullPath());
  4088. cmCryptoHash objNameHasher(cmCryptoHash::AlgoSHA3_512);
  4089. std::string terseObjectName =
  4090. objNameHasher.HashString(objectName).substr(0, 8);
  4091. return terseObjectName;
  4092. }
  4093. std::string cmLocalGenerator::ComputeShortTargetDirectory(
  4094. cmGeneratorTarget const* target) const
  4095. {
  4096. auto const& tgtName = target->GetName();
  4097. return this->GetGlobalGenerator()->ComputeTargetShortName(
  4098. this->GetCurrentBinaryDirectory(), tgtName);
  4099. }
  4100. std::string cmLocalGenerator::GetSourceFileLanguage(cmSourceFile const& source)
  4101. {
  4102. return source.GetLanguage();
  4103. }
  4104. cmake* cmLocalGenerator::GetCMakeInstance() const
  4105. {
  4106. return this->GlobalGenerator->GetCMakeInstance();
  4107. }
  4108. std::string const& cmLocalGenerator::GetSourceDirectory() const
  4109. {
  4110. return this->GetCMakeInstance()->GetHomeDirectory();
  4111. }
  4112. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  4113. {
  4114. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  4115. }
  4116. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  4117. {
  4118. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  4119. }
  4120. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  4121. {
  4122. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  4123. }
  4124. std::string cmLocalGenerator::GetTargetDirectory(
  4125. cmGeneratorTarget const* /*unused*/,
  4126. cmStateEnums::IntermediateDirKind /*kind*/) const
  4127. {
  4128. cmSystemTools::Error("GetTargetDirectory"
  4129. " called on cmLocalGenerator");
  4130. return "";
  4131. }
  4132. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  4133. cmPolicies::PolicyID id) const
  4134. {
  4135. return this->Makefile->GetPolicyStatus(id);
  4136. }
  4137. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  4138. {
  4139. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  4140. std::string::size_type pos = define.find_first_of("(=");
  4141. if (pos != std::string::npos) {
  4142. if (define[pos] == '(') {
  4143. std::ostringstream e;
  4144. /* clang-format off */
  4145. e << "WARNING: Function-style preprocessor definitions may not be "
  4146. "passed on the compiler command line because many compilers "
  4147. "do not support it.\n"
  4148. "CMake is dropping a preprocessor definition: " << define << "\n"
  4149. "Consider defining the macro in a (configured) header file.\n";
  4150. /* clang-format on */
  4151. cmSystemTools::Message(e.str());
  4152. return false;
  4153. }
  4154. }
  4155. // Many compilers do not support # in the value so we disable it.
  4156. if (define.find_first_of('#') != std::string::npos) {
  4157. std::ostringstream e;
  4158. /* clang-format off */
  4159. e << "WARNING: Preprocessor definitions containing '#' may not be "
  4160. "passed on the compiler command line because many compilers "
  4161. "do not support it.\n"
  4162. "CMake is dropping a preprocessor definition: " << define << "\n"
  4163. "Consider defining the macro in a (configured) header file.\n";
  4164. /* clang-format on */
  4165. cmSystemTools::Message(e.str());
  4166. return false;
  4167. }
  4168. // Assume it is supported.
  4169. return true;
  4170. }
  4171. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  4172. std::string const& prop)
  4173. {
  4174. if (cmValue val = target->GetProperty(prop)) {
  4175. mf->AddDefinition(prop, *val);
  4176. }
  4177. }
  4178. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  4179. std::string const& targetName,
  4180. std::string const& fname)
  4181. {
  4182. // Find the Info.plist template.
  4183. cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  4184. std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
  4185. if (!cmSystemTools::FileIsFullPath(inFile)) {
  4186. std::string inMod = this->Makefile->GetModulesFile(inFile);
  4187. if (!inMod.empty()) {
  4188. inFile = inMod;
  4189. }
  4190. }
  4191. if (!cmSystemTools::FileExists(inFile, true)) {
  4192. std::ostringstream e;
  4193. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  4194. << "\" could not be found.";
  4195. cmSystemTools::Error(e.str());
  4196. return;
  4197. }
  4198. // Convert target properties to variables in an isolated makefile
  4199. // scope to configure the file. If properties are set they will
  4200. // override user make variables. If not the configuration will fall
  4201. // back to the directory-level values set by the user.
  4202. cmMakefile* mf = this->Makefile;
  4203. cmMakefile::ScopePushPop varScope(mf);
  4204. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  4205. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  4206. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  4207. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  4208. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  4209. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  4210. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  4211. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  4212. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  4213. mf->ConfigureFile(inFile, fname, false, false, false);
  4214. }
  4215. void cmLocalGenerator::GenerateFrameworkInfoPList(
  4216. cmGeneratorTarget* target, std::string const& targetName,
  4217. std::string const& fname)
  4218. {
  4219. // Find the Info.plist template.
  4220. cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  4221. std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
  4222. if (!cmSystemTools::FileIsFullPath(inFile)) {
  4223. std::string inMod = this->Makefile->GetModulesFile(inFile);
  4224. if (!inMod.empty()) {
  4225. inFile = inMod;
  4226. }
  4227. }
  4228. if (!cmSystemTools::FileExists(inFile, true)) {
  4229. std::ostringstream e;
  4230. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  4231. << "\" could not be found.";
  4232. cmSystemTools::Error(e.str());
  4233. return;
  4234. }
  4235. // Convert target properties to variables in an isolated makefile
  4236. // scope to configure the file. If properties are set they will
  4237. // override user make variables. If not the configuration will fall
  4238. // back to the directory-level values set by the user.
  4239. cmMakefile* mf = this->Makefile;
  4240. cmMakefile::ScopePushPop varScope(mf);
  4241. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  4242. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  4243. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  4244. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  4245. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_NAME");
  4246. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  4247. mf->ConfigureFile(inFile, fname, false, false, false);
  4248. }
  4249. namespace {
  4250. cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
  4251. {
  4252. return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
  4253. : "BYPRODUCTS"_s);
  4254. }
  4255. void CreateGeneratedSource(cmLocalGenerator& lg, std::string const& output,
  4256. cmLocalGenerator::OutputRole role,
  4257. cmCommandOrigin origin,
  4258. cmListFileBacktrace const& lfbt)
  4259. {
  4260. if (cmGeneratorExpression::Find(output) != std::string::npos) {
  4261. lg.GetCMakeInstance()->IssueMessage(
  4262. MessageType::FATAL_ERROR,
  4263. "Generator expressions in custom command outputs are not implemented!",
  4264. lfbt);
  4265. return;
  4266. }
  4267. // Make sure the file will not be generated into the source
  4268. // directory during an out of source build.
  4269. if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
  4270. lg.GetCMakeInstance()->IssueMessage(
  4271. MessageType::FATAL_ERROR,
  4272. cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
  4273. "\nin a source directory as an output of custom command."),
  4274. lfbt);
  4275. return;
  4276. }
  4277. // Make sure the output file name has no invalid characters.
  4278. bool const hashNotAllowed = lg.GetState()->UseBorlandMake();
  4279. std::string::size_type pos = output.find_first_of("<>");
  4280. if (pos == std::string::npos && hashNotAllowed) {
  4281. pos = output.find_first_of('#');
  4282. }
  4283. if (pos != std::string::npos) {
  4284. lg.GetCMakeInstance()->IssueMessage(
  4285. MessageType::FATAL_ERROR,
  4286. cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
  4287. "\" is not allowed."),
  4288. lfbt);
  4289. return;
  4290. }
  4291. // Outputs without generator expressions from the project are already
  4292. // created and marked as generated. Do not mark them again, because
  4293. // other commands might have overwritten the property.
  4294. if (origin == cmCommandOrigin::Generator) {
  4295. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  4296. }
  4297. }
  4298. std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
  4299. cmListFileBacktrace const& bt,
  4300. std::string const& output)
  4301. {
  4302. // If the output path has no generator expressions, use it directly.
  4303. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  4304. return output;
  4305. }
  4306. // The output path contains a generator expression, but we must choose
  4307. // a single source file path to which to attach the custom command.
  4308. // Use some heuristics to provide a nice-looking name when possible.
  4309. // If the only genex is $<CONFIG>, replace that gracefully.
  4310. {
  4311. std::string simple = output;
  4312. cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
  4313. if (cmGeneratorExpression::Find(simple) == std::string::npos) {
  4314. return simple;
  4315. }
  4316. }
  4317. // If the genex evaluates to the same value in all configurations, use that.
  4318. {
  4319. std::vector<std::string> allConfigOutputs =
  4320. lg.ExpandCustomCommandOutputGenex(output, bt);
  4321. if (allConfigOutputs.size() == 1) {
  4322. return allConfigOutputs.front();
  4323. }
  4324. }
  4325. // Fall back to a deterministic unique name.
  4326. cmCryptoHash h(cmCryptoHash::AlgoSHA256);
  4327. return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
  4328. h.HashString(output).substr(0, 16));
  4329. }
  4330. cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  4331. std::unique_ptr<cmCustomCommand> cc,
  4332. bool replace)
  4333. {
  4334. cmMakefile* mf = lg.GetMakefile();
  4335. auto const& lfbt = cc->GetBacktrace();
  4336. auto const& outputs = cc->GetOutputs();
  4337. auto const& byproducts = cc->GetByproducts();
  4338. auto const& commandLines = cc->GetCommandLines();
  4339. // Choose a source file on which to store the custom command.
  4340. cmSourceFile* file = nullptr;
  4341. if (!commandLines.empty() && cc->HasMainDependency()) {
  4342. auto const& main_dependency = cc->GetMainDependency();
  4343. // The main dependency was specified. Use it unless a different
  4344. // custom command already used it.
  4345. file = mf->GetSource(main_dependency);
  4346. if (file && file->GetCustomCommand() && !replace) {
  4347. // The main dependency already has a custom command.
  4348. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  4349. // The existing custom command is identical. Silently ignore
  4350. // the duplicate.
  4351. return file;
  4352. }
  4353. // The existing custom command is different. We need to
  4354. // generate a rule file for this new command.
  4355. file = nullptr;
  4356. } else if (!file) {
  4357. file = mf->CreateSource(main_dependency);
  4358. }
  4359. }
  4360. // Generate a rule file if the main dependency is not available.
  4361. if (!file) {
  4362. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  4363. // Construct a rule file associated with the first output produced.
  4364. std::string outName = gg->GenerateRuleFile(
  4365. ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
  4366. // Check if the rule file already exists.
  4367. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  4368. if (file && file->GetCustomCommand() && !replace) {
  4369. // The rule file already exists.
  4370. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  4371. lg.GetCMakeInstance()->IssueMessage(
  4372. MessageType::FATAL_ERROR,
  4373. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  4374. "\nwhich already has a custom rule."),
  4375. lfbt);
  4376. }
  4377. return file;
  4378. }
  4379. // Create a cmSourceFile for the rule file.
  4380. if (!file) {
  4381. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  4382. }
  4383. file->SetProperty("__CMAKE_RULE", "1");
  4384. }
  4385. // Attach the custom command to the file.
  4386. if (file) {
  4387. cc->SetEscapeAllowMakeVars(true);
  4388. lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
  4389. lfbt, origin);
  4390. lg.AddSourceOutputs(file, byproducts,
  4391. cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
  4392. file->SetCustomCommand(std::move(cc));
  4393. }
  4394. return file;
  4395. }
  4396. bool AnyOutputMatches(std::string const& name,
  4397. std::vector<std::string> const& outputs)
  4398. {
  4399. return std::any_of(outputs.begin(), outputs.end(),
  4400. [&name](std::string const& output) -> bool {
  4401. std::string::size_type pos = output.rfind(name);
  4402. // If the output matches exactly
  4403. return (pos != std::string::npos &&
  4404. pos == output.size() - name.size() &&
  4405. (pos == 0 || output[pos - 1] == '/'));
  4406. });
  4407. }
  4408. bool AnyTargetCommandOutputMatches(
  4409. std::string const& name, std::vector<cmCustomCommand> const& commands)
  4410. {
  4411. return std::any_of(commands.begin(), commands.end(),
  4412. [&name](cmCustomCommand const& command) -> bool {
  4413. return AnyOutputMatches(name, command.GetByproducts());
  4414. });
  4415. }
  4416. }
  4417. namespace detail {
  4418. void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
  4419. cmTarget* target, cmCustomCommandType type,
  4420. std::unique_ptr<cmCustomCommand> cc)
  4421. {
  4422. // Add the command to the appropriate build step for the target.
  4423. cc->SetEscapeAllowMakeVars(true);
  4424. cc->SetTarget(target->GetName());
  4425. lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
  4426. origin);
  4427. switch (type) {
  4428. case cmCustomCommandType::PRE_BUILD:
  4429. target->AddPreBuildCommand(std::move(*cc));
  4430. break;
  4431. case cmCustomCommandType::PRE_LINK:
  4432. target->AddPreLinkCommand(std::move(*cc));
  4433. break;
  4434. case cmCustomCommandType::POST_BUILD:
  4435. target->AddPostBuildCommand(std::move(*cc));
  4436. break;
  4437. }
  4438. cc.reset();
  4439. }
  4440. cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
  4441. cmCommandOrigin origin,
  4442. std::unique_ptr<cmCustomCommand> cc,
  4443. bool replace)
  4444. {
  4445. return AddCustomCommand(lg, origin, std::move(cc), replace);
  4446. }
  4447. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  4448. cmListFileBacktrace const& lfbt,
  4449. std::string const& output,
  4450. std::vector<std::string> const& depends,
  4451. cmImplicitDependsList const& implicit_depends,
  4452. cmCustomCommandLines const& commandLines)
  4453. {
  4454. // Lookup an existing command.
  4455. cmSourceFile* sf = nullptr;
  4456. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  4457. sf = lg.GetSourceFileWithOutput(output);
  4458. } else {
  4459. // This output path has a generator expression. Evaluate it to
  4460. // find the output for any configurations.
  4461. for (std::string const& out :
  4462. lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
  4463. sf = lg.GetSourceFileWithOutput(out);
  4464. if (sf) {
  4465. break;
  4466. }
  4467. }
  4468. }
  4469. if (sf) {
  4470. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  4471. cc->AppendCommands(commandLines);
  4472. cc->AppendDepends(depends);
  4473. if (cc->GetCodegen() && !implicit_depends.empty()) {
  4474. lg.GetCMakeInstance()->IssueMessage(
  4475. MessageType::FATAL_ERROR,
  4476. "Cannot append IMPLICIT_DEPENDS to existing CODEGEN custom "
  4477. "command.");
  4478. }
  4479. cc->AppendImplicitDepends(implicit_depends);
  4480. return;
  4481. }
  4482. }
  4483. // No existing command found.
  4484. lg.GetCMakeInstance()->IssueMessage(
  4485. MessageType::FATAL_ERROR,
  4486. cmStrCat("Attempt to APPEND to custom command with output\n ", output,
  4487. "\nwhich is not already a custom command output."),
  4488. lfbt);
  4489. }
  4490. void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  4491. cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
  4492. {
  4493. // They might be moved away
  4494. auto byproducts = cc->GetByproducts();
  4495. auto lfbt = cc->GetBacktrace();
  4496. // Use an empty comment to avoid generation of default comment.
  4497. if (!cc->GetComment()) {
  4498. cc->SetComment("");
  4499. }
  4500. // Create the generated symbolic output name of the utility target.
  4501. std::string output =
  4502. lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
  4503. cc->SetOutputs(output);
  4504. cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
  4505. /*replace=*/false);
  4506. if (rule) {
  4507. lg.AddTargetByproducts(target, byproducts, lfbt, origin);
  4508. }
  4509. target->AddSource(output);
  4510. }
  4511. std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
  4512. {
  4513. cmValue const targetProperty = target->GetProperty("ISPC_INSTRUCTION_SETS");
  4514. cmList ispcTargets;
  4515. if (!targetProperty.IsOff()) {
  4516. ispcTargets.assign(targetProperty);
  4517. for (auto& ispcTarget : ispcTargets) {
  4518. // transform targets into the suffixes
  4519. auto pos = ispcTarget.find('-');
  4520. auto target_suffix = ispcTarget.substr(0, pos);
  4521. if (target_suffix ==
  4522. "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
  4523. target_suffix = "avx";
  4524. }
  4525. ispcTarget = target_suffix;
  4526. }
  4527. }
  4528. return std::move(ispcTargets.data());
  4529. }
  4530. std::vector<std::string> ComputeISPCExtraObjects(
  4531. std::string const& objectName, std::string const& buildDirectory,
  4532. std::vector<std::string> const& ispcSuffixes)
  4533. {
  4534. auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
  4535. std::vector<std::string> computedObjects;
  4536. computedObjects.reserve(ispcSuffixes.size());
  4537. auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
  4538. // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
  4539. // drops any directories in objectName
  4540. auto objNameNoExt = objectName;
  4541. std::string::size_type dot_pos = objectName.rfind('.');
  4542. if (dot_pos != std::string::npos) {
  4543. objNameNoExt.resize(dot_pos);
  4544. }
  4545. for (auto const& ispcTarget : ispcSuffixes) {
  4546. computedObjects.emplace_back(
  4547. cmStrCat(normalizedDir, '/', objNameNoExt, '_', ispcTarget, extension));
  4548. }
  4549. return computedObjects;
  4550. }
  4551. }
  4552. cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
  4553. std::string const& name) const
  4554. {
  4555. // Linear search? Also see GetSourceFileWithOutput for detail.
  4556. if (!cmSystemTools::FileIsFullPath(name)) {
  4557. cmSourcesWithOutput sources;
  4558. sources.Target = this->LinearGetTargetWithOutput(name);
  4559. sources.Source = this->LinearGetSourceFileWithOutput(
  4560. name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
  4561. return sources;
  4562. }
  4563. // Otherwise we use an efficient lookup map.
  4564. auto o = this->OutputToSource.find(name);
  4565. if (o != this->OutputToSource.end()) {
  4566. return o->second.Sources;
  4567. }
  4568. return {};
  4569. }
  4570. cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
  4571. std::string const& name, cmSourceOutputKind kind) const
  4572. {
  4573. // If the queried path is not absolute we use the backward compatible
  4574. // linear-time search for an output with a matching suffix.
  4575. if (!cmSystemTools::FileIsFullPath(name)) {
  4576. bool byproduct = false;
  4577. return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
  4578. }
  4579. // Otherwise we use an efficient lookup map.
  4580. auto o = this->OutputToSource.find(name);
  4581. if (o != this->OutputToSource.end() &&
  4582. (!o->second.Sources.SourceIsByproduct ||
  4583. kind == cmSourceOutputKind::OutputOrByproduct)) {
  4584. // Source file could also be null pointer for example if we found the
  4585. // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
  4586. // command of a target, or a not yet created custom command.
  4587. return o->second.Sources.Source;
  4588. }
  4589. return nullptr;
  4590. }
  4591. std::string cmLocalGenerator::CreateUtilityOutput(
  4592. std::string const& targetName, std::vector<std::string> const&,
  4593. cmListFileBacktrace const&)
  4594. {
  4595. std::string force =
  4596. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
  4597. // The output is not actually created so mark it symbolic.
  4598. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  4599. sf->SetProperty("SYMBOLIC", "1");
  4600. } else {
  4601. cmSystemTools::Error("Could not get source file entry for " + force);
  4602. }
  4603. return force;
  4604. }
  4605. std::vector<cmCustomCommandGenerator>
  4606. cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
  4607. std::string const& config)
  4608. {
  4609. std::vector<cmCustomCommandGenerator> ccgs;
  4610. ccgs.emplace_back(cc, config, this);
  4611. return ccgs;
  4612. }
  4613. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
  4614. cmCompiledGeneratorExpression const& cge, std::string const& config)
  4615. {
  4616. cmList paths{ cge.Evaluate(this, config) };
  4617. for (std::string& p : paths) {
  4618. p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
  4619. }
  4620. return std::move(paths.data());
  4621. }
  4622. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
  4623. std::string const& o, cmListFileBacktrace const& bt)
  4624. {
  4625. std::vector<std::string> allConfigOutputs;
  4626. cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
  4627. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
  4628. std::vector<std::string> configs =
  4629. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4630. for (std::string const& config : configs) {
  4631. std::vector<std::string> configOutputs =
  4632. this->ExpandCustomCommandOutputPaths(*cge, config);
  4633. allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
  4634. std::move(configOutputs.begin(), configOutputs.end(),
  4635. std::back_inserter(allConfigOutputs));
  4636. }
  4637. auto endUnique =
  4638. cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
  4639. allConfigOutputs.erase(endUnique, allConfigOutputs.end());
  4640. return allConfigOutputs;
  4641. }
  4642. void cmLocalGenerator::AddTargetByproducts(
  4643. cmTarget* target, std::vector<std::string> const& byproducts,
  4644. cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4645. {
  4646. for (std::string const& o : byproducts) {
  4647. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4648. this->UpdateOutputToSourceMap(o, target, bt, origin);
  4649. continue;
  4650. }
  4651. // This byproduct path has a generator expression. Evaluate it to
  4652. // register the byproducts for all configurations.
  4653. for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
  4654. this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
  4655. }
  4656. }
  4657. }
  4658. void cmLocalGenerator::AddSourceOutputs(
  4659. cmSourceFile* source, std::vector<std::string> const& outputs,
  4660. OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4661. {
  4662. for (std::string const& o : outputs) {
  4663. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4664. this->UpdateOutputToSourceMap(o, source, role, bt, origin);
  4665. continue;
  4666. }
  4667. // This output path has a generator expression. Evaluate it to
  4668. // register the outputs for all configurations.
  4669. for (std::string const& out :
  4670. this->ExpandCustomCommandOutputGenex(o, bt)) {
  4671. this->UpdateOutputToSourceMap(out, source, role, bt,
  4672. cmCommandOrigin::Generator);
  4673. }
  4674. }
  4675. }
  4676. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
  4677. cmTarget* target,
  4678. cmListFileBacktrace const& bt,
  4679. cmCommandOrigin origin)
  4680. {
  4681. SourceEntry entry;
  4682. entry.Sources.Target = target;
  4683. auto pr = this->OutputToSource.emplace(byproduct, entry);
  4684. if (pr.second) {
  4685. CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
  4686. } else {
  4687. SourceEntry& current = pr.first->second;
  4688. // Has the target already been set?
  4689. if (!current.Sources.Target) {
  4690. current.Sources.Target = target;
  4691. } else {
  4692. // Multiple custom commands/targets produce the same output (source file
  4693. // or target). See also comment in other UpdateOutputToSourceMap
  4694. // overload.
  4695. //
  4696. // TODO: Warn the user about this case.
  4697. }
  4698. }
  4699. }
  4700. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
  4701. cmSourceFile* source,
  4702. OutputRole role,
  4703. cmListFileBacktrace const& bt,
  4704. cmCommandOrigin origin)
  4705. {
  4706. SourceEntry entry;
  4707. entry.Sources.Source = source;
  4708. entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
  4709. auto pr = this->OutputToSource.emplace(output, entry);
  4710. if (pr.second) {
  4711. CreateGeneratedSource(*this, output, role, origin, bt);
  4712. } else {
  4713. SourceEntry& current = pr.first->second;
  4714. // Outputs take precedence over byproducts
  4715. if (!current.Sources.Source ||
  4716. (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
  4717. current.Sources.Source = source;
  4718. current.Sources.SourceIsByproduct = false;
  4719. } else {
  4720. // Multiple custom commands produce the same output but may
  4721. // be attached to a different source file (MAIN_DEPENDENCY).
  4722. // LinearGetSourceFileWithOutput would return the first one,
  4723. // so keep the mapping for the first one.
  4724. //
  4725. // TODO: Warn the user about this case. However, the VS 8 generator
  4726. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  4727. // individual targets.
  4728. }
  4729. }
  4730. }
  4731. cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
  4732. std::string const& name) const
  4733. {
  4734. // We go through the ordered vector of targets to get reproducible results
  4735. // should multiple names match.
  4736. for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
  4737. // Does the output of any command match the source file name?
  4738. if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
  4739. return t;
  4740. }
  4741. if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
  4742. return t;
  4743. }
  4744. if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
  4745. return t;
  4746. }
  4747. }
  4748. return nullptr;
  4749. }
  4750. cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
  4751. std::string const& name, cmSourceOutputKind kind, bool& byproduct) const
  4752. {
  4753. // Outputs take precedence over byproducts.
  4754. byproduct = false;
  4755. cmSourceFile* fallback = nullptr;
  4756. // Look through all the source files that have custom commands and see if the
  4757. // custom command has the passed source file as an output.
  4758. for (auto const& src : this->Makefile->GetSourceFiles()) {
  4759. // Does this source file have a custom command?
  4760. if (src->GetCustomCommand()) {
  4761. // Does the output of the custom command match the source file name?
  4762. if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
  4763. // Return the first matching output.
  4764. return src.get();
  4765. }
  4766. if (kind == cmSourceOutputKind::OutputOrByproduct) {
  4767. if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
  4768. // Do not return the source yet as there might be a matching output.
  4769. fallback = src.get();
  4770. }
  4771. }
  4772. }
  4773. }
  4774. // Did we find a byproduct?
  4775. byproduct = fallback != nullptr;
  4776. return fallback;
  4777. }