cmLocalGenerator.cxx 143 KB

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