cmLocalGenerator.cxx 108 KB

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