cmLocalGenerator.cxx 142 KB

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