cmLocalGenerator.cxx 182 KB

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