cmLocalGenerator.cxx 160 KB

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