cmLocalGenerator.cxx 138 KB

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