cmLocalGenerator.cxx 141 KB

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