cmLocalGenerator.cxx 175 KB

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