cmLocalGenerator.cxx 160 KB

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