1
0

cmLocalGenerator.cxx 163 KB

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