cmLocalGenerator.cxx 179 KB

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