cmLocalGenerator.cxx 144 KB

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