cmLocalGenerator.cxx 159 KB

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