cmLocalGenerator.cxx 101 KB

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