cmLocalGenerator.cxx 168 KB

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