cmLocalGenerator.cxx 139 KB

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