cmLocalGenerator.cxx 149 KB

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