cmLocalGenerator.cxx 169 KB

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