cmLocalGenerator.cxx 111 KB

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