cmLocalGenerator.cxx 178 KB

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