cmLocalGenerator.cxx 160 KB

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