cmLocalGenerator.cxx 161 KB

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