cmLocalGenerator.cxx 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977
  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 (cmIsOn(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. std::find(impDirVec.begin(), impDirVec.end(), "/usr/include") ==
  905. impDirVec.end() &&
  906. std::find_if(impDirVec.begin(), impDirVec.end(),
  907. [](std::string const& d) {
  908. return cmHasLiteralSuffix(d, "/usr/include");
  909. }) != impDirVec.end()) {
  910. // Only exclude this hard coded path for backwards compatibility.
  911. implicitExclude.emplace("/usr/include");
  912. }
  913. for (std::string const& i : impDirVec) {
  914. if (implicitSet.insert(cmSystemTools::GetRealPath(i)).second) {
  915. implicitDirs.emplace_back(i);
  916. }
  917. }
  918. }
  919. // Checks if this is not an excluded (implicit) include directory.
  920. auto notExcluded = [this, &implicitSet, &implicitExclude,
  921. &lang](std::string const& dir) {
  922. return (
  923. // Do not exclude directories that are not in an excluded set.
  924. ((implicitSet.find(cmSystemTools::GetRealPath(dir)) ==
  925. implicitSet.end()) &&
  926. (implicitExclude.find(dir) == implicitExclude.end()))
  927. // Do not exclude entries of the CPATH environment variable even though
  928. // they are implicitly searched by the compiler. They are meant to be
  929. // user-specified directories that can be re-ordered or converted to
  930. // -isystem without breaking real compiler builtin headers.
  931. || ((lang == "C" || lang == "CXX") &&
  932. (this->EnvCPATH.find(dir) != this->EnvCPATH.end())));
  933. };
  934. // Get the target-specific include directories.
  935. std::vector<BT<std::string>> userDirs =
  936. target->GetIncludeDirectories(config, lang);
  937. // Support putting all the in-project include directories first if
  938. // it is requested by the project.
  939. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  940. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  941. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  942. for (BT<std::string> const& udr : userDirs) {
  943. // Emit this directory only if it is a subdirectory of the
  944. // top-level source or binary tree.
  945. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  946. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  947. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  948. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  949. if (notExcluded(udr.Value)) {
  950. emitBT(udr);
  951. }
  952. }
  953. }
  954. }
  955. // Emit remaining non implicit user direcories.
  956. for (BT<std::string> const& udr : userDirs) {
  957. if (notExcluded(udr.Value)) {
  958. emitBT(udr);
  959. }
  960. }
  961. // Sort result
  962. MoveSystemIncludesToEnd(result, config, lang, target);
  963. // Append standard include directories for this language.
  964. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  965. for (std::string& usd : userStandardDirs) {
  966. emitDir(usd);
  967. userDirs.emplace_back(std::move(usd));
  968. }
  969. // Append compiler implicit include directories
  970. if (!stripImplicitDirs) {
  971. // Append implicit directories that were requested by the user only
  972. for (BT<std::string> const& udr : userDirs) {
  973. if (implicitSet.find(cmSystemTools::GetRealPath(udr.Value)) !=
  974. implicitSet.end()) {
  975. emitBT(udr);
  976. }
  977. }
  978. // Append remaining implicit directories (on demand)
  979. if (appendAllImplicitDirs) {
  980. for (std::string& imd : implicitDirs) {
  981. emitDir(imd);
  982. }
  983. }
  984. }
  985. return result;
  986. }
  987. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  988. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  989. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  990. bool appendAllImplicitDirs) const
  991. {
  992. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  993. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  994. dirs.reserve(dirs.size() + tmp.size());
  995. for (BT<std::string>& v : tmp) {
  996. dirs.emplace_back(std::move(v.Value));
  997. }
  998. }
  999. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1000. cmGeneratorTarget const* target, std::string const& lang,
  1001. std::string const& config) const
  1002. {
  1003. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1004. }
  1005. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1006. cmGeneratorTarget const* target,
  1007. const std::string& lang,
  1008. const std::string& config) const
  1009. {
  1010. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1011. }
  1012. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1013. std::string const& config,
  1014. std::string const& linkLanguage,
  1015. cmGeneratorTarget* target)
  1016. {
  1017. if (linkLanguage != "Swift") {
  1018. this->AppendFlags(
  1019. flags, this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1020. if (!config.empty()) {
  1021. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  1022. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(name));
  1023. }
  1024. }
  1025. this->AppendFlags(flags, target->GetProperty("STATIC_LIBRARY_FLAGS"));
  1026. if (!config.empty()) {
  1027. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  1028. this->AppendFlags(flags, target->GetProperty(name));
  1029. }
  1030. std::vector<std::string> options;
  1031. target->GetStaticLibraryLinkOptions(options, config, linkLanguage);
  1032. // STATIC_LIBRARY_OPTIONS are escaped.
  1033. this->AppendCompileOptions(flags, options);
  1034. }
  1035. void cmLocalGenerator::GetTargetFlags(
  1036. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1037. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1038. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1039. {
  1040. const std::string buildType = cmSystemTools::UpperCase(config);
  1041. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1042. const char* libraryLinkVariable =
  1043. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1044. const std::string linkLanguage =
  1045. linkLineComputer->GetLinkerLanguage(target, buildType);
  1046. switch (target->GetType()) {
  1047. case cmStateEnums::STATIC_LIBRARY:
  1048. this->GetStaticLibraryFlags(linkFlags, buildType, linkLanguage, target);
  1049. break;
  1050. case cmStateEnums::MODULE_LIBRARY:
  1051. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1052. CM_FALLTHROUGH;
  1053. case cmStateEnums::SHARED_LIBRARY: {
  1054. if (linkLanguage != "Swift") {
  1055. linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
  1056. linkFlags += " ";
  1057. if (!buildType.empty()) {
  1058. std::string build = libraryLinkVariable;
  1059. build += "_";
  1060. build += buildType;
  1061. linkFlags += this->Makefile->GetSafeDefinition(build);
  1062. linkFlags += " ";
  1063. }
  1064. if (this->Makefile->IsOn("WIN32") &&
  1065. !(this->Makefile->IsOn("CYGWIN") ||
  1066. this->Makefile->IsOn("MINGW"))) {
  1067. std::vector<cmSourceFile*> sources;
  1068. target->GetSourceFiles(sources, buildType);
  1069. std::string defFlag =
  1070. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  1071. for (cmSourceFile* sf : sources) {
  1072. if (sf->GetExtension() == "def") {
  1073. linkFlags += defFlag;
  1074. linkFlags += this->ConvertToOutputFormat(
  1075. cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
  1076. linkFlags += " ";
  1077. }
  1078. }
  1079. }
  1080. }
  1081. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1082. if (targetLinkFlags) {
  1083. linkFlags += targetLinkFlags;
  1084. linkFlags += " ";
  1085. }
  1086. if (!buildType.empty()) {
  1087. targetLinkFlags =
  1088. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1089. if (targetLinkFlags) {
  1090. linkFlags += targetLinkFlags;
  1091. linkFlags += " ";
  1092. }
  1093. }
  1094. std::vector<std::string> opts;
  1095. target->GetLinkOptions(opts, config, linkLanguage);
  1096. // LINK_OPTIONS are escaped.
  1097. this->AppendCompileOptions(linkFlags, opts);
  1098. if (pcli) {
  1099. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1100. frameworkPath, linkPath);
  1101. }
  1102. } break;
  1103. case cmStateEnums::EXECUTABLE: {
  1104. if (linkLanguage != "Swift") {
  1105. linkFlags +=
  1106. this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1107. linkFlags += " ";
  1108. if (!buildType.empty()) {
  1109. linkFlags += this->Makefile->GetSafeDefinition(
  1110. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", buildType));
  1111. linkFlags += " ";
  1112. }
  1113. if (linkLanguage.empty()) {
  1114. cmSystemTools::Error(
  1115. "CMake can not determine linker language for target: " +
  1116. target->GetName());
  1117. return;
  1118. }
  1119. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  1120. linkFlags +=
  1121. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  1122. linkFlags += " ";
  1123. } else {
  1124. linkFlags +=
  1125. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1126. linkFlags += " ";
  1127. }
  1128. if (target->IsExecutableWithExports()) {
  1129. linkFlags += this->Makefile->GetSafeDefinition(
  1130. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1131. linkFlags += " ";
  1132. }
  1133. }
  1134. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  1135. if (pcli) {
  1136. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1137. frameworkPath, linkPath);
  1138. }
  1139. if (cmIsOn(this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  1140. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  1141. linkLanguage + std::string("_FLAGS");
  1142. linkFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1143. linkFlags += " ";
  1144. }
  1145. std::string cmp0065Flags =
  1146. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1147. if (!cmp0065Flags.empty()) {
  1148. linkFlags += cmp0065Flags;
  1149. linkFlags += " ";
  1150. }
  1151. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1152. if (targetLinkFlags) {
  1153. linkFlags += targetLinkFlags;
  1154. linkFlags += " ";
  1155. }
  1156. if (!buildType.empty()) {
  1157. targetLinkFlags =
  1158. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1159. if (targetLinkFlags) {
  1160. linkFlags += targetLinkFlags;
  1161. linkFlags += " ";
  1162. }
  1163. }
  1164. std::vector<std::string> opts;
  1165. target->GetLinkOptions(opts, config, linkLanguage);
  1166. // LINK_OPTIONS are escaped.
  1167. this->AppendCompileOptions(linkFlags, opts);
  1168. } break;
  1169. default:
  1170. break;
  1171. }
  1172. this->AppendPositionIndependentLinkerFlags(linkFlags, target, config,
  1173. linkLanguage);
  1174. this->AppendIPOLinkerFlags(linkFlags, target, config, linkLanguage);
  1175. }
  1176. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1177. std::string const& config,
  1178. std::string const& lang,
  1179. std::string& flags)
  1180. {
  1181. cmMakefile* mf = this->GetMakefile();
  1182. // Add language-specific flags.
  1183. this->AddLanguageFlags(flags, target, lang, config);
  1184. if (target->IsIPOEnabled(lang, config)) {
  1185. this->AppendFeatureOptions(flags, lang, "IPO");
  1186. }
  1187. this->AddArchitectureFlags(flags, target, lang, config);
  1188. if (lang == "Fortran") {
  1189. this->AppendFlags(flags, this->GetTargetFortranFlags(target, config));
  1190. }
  1191. this->AddCMP0018Flags(flags, target, lang, config);
  1192. this->AddVisibilityPresetFlags(flags, target, lang);
  1193. this->AppendFlags(flags, mf->GetDefineFlags());
  1194. this->AppendFlags(flags, this->GetFrameworkFlags(lang, config, target));
  1195. this->AddCompileOptions(flags, target, lang, config);
  1196. }
  1197. static std::string GetFrameworkFlags(const std::string& lang,
  1198. const std::string& config,
  1199. cmGeneratorTarget* target)
  1200. {
  1201. cmLocalGenerator* lg = target->GetLocalGenerator();
  1202. cmMakefile* mf = lg->GetMakefile();
  1203. if (!mf->IsOn("APPLE")) {
  1204. return std::string();
  1205. }
  1206. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1207. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1208. if (!(fwSearchFlag && *fwSearchFlag)) {
  1209. return std::string();
  1210. }
  1211. std::set<std::string> emitted;
  1212. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1213. emitted.insert("/System/Library/Frameworks");
  1214. #endif
  1215. std::vector<std::string> includes;
  1216. lg->GetIncludeDirectories(includes, target, "C", config);
  1217. // check all include directories for frameworks as this
  1218. // will already have added a -F for the framework
  1219. for (std::string const& include : includes) {
  1220. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1221. std::string frameworkDir = include;
  1222. frameworkDir += "/../";
  1223. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1224. emitted.insert(frameworkDir);
  1225. }
  1226. }
  1227. std::string flags;
  1228. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1229. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1230. for (std::string const& framework : frameworks) {
  1231. if (emitted.insert(framework).second) {
  1232. flags += fwSearchFlag;
  1233. flags +=
  1234. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1235. flags += " ";
  1236. }
  1237. }
  1238. }
  1239. return flags;
  1240. }
  1241. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1242. std::string const& config,
  1243. cmGeneratorTarget* target)
  1244. {
  1245. return ::GetFrameworkFlags(l, config, target);
  1246. }
  1247. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1248. std::string const& config,
  1249. std::string const& lang,
  1250. std::set<std::string>& defines) const
  1251. {
  1252. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1253. for (BT<std::string> const& v : tmp) {
  1254. defines.emplace(v.Value);
  1255. }
  1256. }
  1257. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1258. cmGeneratorTarget const* target, std::string const& config,
  1259. std::string const& lang) const
  1260. {
  1261. std::set<BT<std::string>> defines;
  1262. // Add the export symbol definition for shared library objects.
  1263. if (const std::string* exportMacro = target->GetExportMacro()) {
  1264. this->AppendDefines(defines, *exportMacro);
  1265. }
  1266. // Add preprocessor definitions for this target and configuration.
  1267. std::vector<BT<std::string>> targetDefines =
  1268. target->GetCompileDefinitions(config, lang);
  1269. this->AppendDefines(defines, targetDefines);
  1270. return defines;
  1271. }
  1272. std::string cmLocalGenerator::GetTargetFortranFlags(
  1273. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1274. {
  1275. // Implemented by specific generators that override this.
  1276. return std::string();
  1277. }
  1278. /**
  1279. * Output the linking rules on a command line. For executables,
  1280. * targetLibrary should be a NULL pointer. For libraries, it should point
  1281. * to the name of the library. This will not link a library against itself.
  1282. */
  1283. void cmLocalGenerator::OutputLinkLibraries(
  1284. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1285. std::string& linkLibraries, std::string& frameworkPath,
  1286. std::string& linkPath)
  1287. {
  1288. cmComputeLinkInformation& cli = *pcli;
  1289. std::string linkLanguage = cli.GetLinkLanguage();
  1290. std::string libPathFlag;
  1291. if (const char* value = this->Makefile->GetDefinition(
  1292. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1293. libPathFlag = value;
  1294. } else {
  1295. libPathFlag =
  1296. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1297. }
  1298. std::string libPathTerminator;
  1299. if (const char* value = this->Makefile->GetDefinition(
  1300. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1301. libPathTerminator = value;
  1302. } else {
  1303. libPathTerminator =
  1304. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1305. }
  1306. // Add standard libraries for this language.
  1307. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1308. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1309. // Append the framework search path flags.
  1310. std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
  1311. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1312. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1313. linkPath =
  1314. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
  1315. linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
  1316. }
  1317. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1318. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1319. {
  1320. std::string linkFlags;
  1321. // Flags to link an executable to shared libraries.
  1322. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1323. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1324. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1325. bool add_shlib_flags = false;
  1326. switch (tgt.GetPolicyStatusCMP0065()) {
  1327. case cmPolicies::WARN:
  1328. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1329. this->Makefile->PolicyOptionalWarningEnabled(
  1330. "CMAKE_POLICY_WARNING_CMP0065")) {
  1331. std::ostringstream w;
  1332. /* clang-format off */
  1333. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1334. "For compatibility with older versions of CMake, "
  1335. "additional flags may be added to export symbols on all "
  1336. "executables regardless of their ENABLE_EXPORTS property.";
  1337. /* clang-format on */
  1338. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1339. }
  1340. CM_FALLTHROUGH;
  1341. case cmPolicies::OLD:
  1342. // OLD behavior is to always add the flags, except on AIX where
  1343. // we compute symbol exports if ENABLE_EXPORTS is on.
  1344. add_shlib_flags =
  1345. !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1346. break;
  1347. case cmPolicies::REQUIRED_IF_USED:
  1348. case cmPolicies::REQUIRED_ALWAYS:
  1349. this->IssueMessage(
  1350. MessageType::FATAL_ERROR,
  1351. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1352. CM_FALLTHROUGH;
  1353. case cmPolicies::NEW:
  1354. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1355. // except on AIX where we compute symbol exports.
  1356. add_shlib_flags =
  1357. !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1358. break;
  1359. }
  1360. if (add_shlib_flags) {
  1361. linkFlags = this->Makefile->GetSafeDefinition(
  1362. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1363. }
  1364. }
  1365. return linkFlags;
  1366. }
  1367. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1368. cmGeneratorTarget const* target,
  1369. const std::string& lang,
  1370. const std::string& config)
  1371. {
  1372. // Only add macOS specific flags on Darwin platforms (macOS and iOS):
  1373. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1374. std::vector<std::string> archs;
  1375. target->GetAppleArchs(config, archs);
  1376. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1377. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1378. sysroot = nullptr;
  1379. }
  1380. std::string sysrootFlagVar =
  1381. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1382. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1383. const char* deploymentTarget =
  1384. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1385. std::string deploymentTargetFlagVar =
  1386. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1387. const char* deploymentTargetFlag =
  1388. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1389. if (!archs.empty() && !lang.empty() &&
  1390. (lang[0] == 'C' || lang[0] == 'F')) {
  1391. for (std::string const& arch : archs) {
  1392. flags += " -arch ";
  1393. flags += arch;
  1394. }
  1395. }
  1396. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1397. flags += " ";
  1398. flags += sysrootFlag;
  1399. flags += " ";
  1400. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1401. }
  1402. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1403. *deploymentTarget) {
  1404. flags += " ";
  1405. flags += deploymentTargetFlag;
  1406. flags += deploymentTarget;
  1407. }
  1408. }
  1409. }
  1410. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1411. cmGeneratorTarget const* target,
  1412. const std::string& lang,
  1413. const std::string& config)
  1414. {
  1415. // Add language-specific flags.
  1416. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1417. config);
  1418. // Add MSVC runtime library flags. This is activated by the presence
  1419. // of a default selection whether or not it is overridden by a property.
  1420. const char* msvcRuntimeLibraryDefault =
  1421. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1422. if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) {
  1423. const char* msvcRuntimeLibraryValue =
  1424. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1425. if (!msvcRuntimeLibraryValue) {
  1426. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1427. }
  1428. cmGeneratorExpression ge;
  1429. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  1430. ge.Parse(msvcRuntimeLibraryValue);
  1431. std::string const msvcRuntimeLibrary =
  1432. cge->Evaluate(this, config, false, target);
  1433. if (!msvcRuntimeLibrary.empty()) {
  1434. if (const char* msvcRuntimeLibraryOptions =
  1435. this->Makefile->GetDefinition(
  1436. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1437. msvcRuntimeLibrary)) {
  1438. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1439. } else if ((this->Makefile->GetSafeDefinition(
  1440. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1441. this->Makefile->GetSafeDefinition(
  1442. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1443. !cmSystemTools::GetErrorOccuredFlag()) {
  1444. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1445. this->IssueMessage(MessageType::FATAL_ERROR,
  1446. "MSVC_RUNTIME_LIBRARY value '" +
  1447. msvcRuntimeLibrary + "' not known for this " +
  1448. lang + " compiler.");
  1449. }
  1450. }
  1451. }
  1452. }
  1453. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1454. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1455. const std::string& config)
  1456. {
  1457. if (this->Makefile->IsOn("CMAKE_" + lang +
  1458. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1459. // This toolchain requires use of the language standard flag
  1460. // when linking in order to use the matching standard library.
  1461. // FIXME: If CMake gains an abstraction for standard library
  1462. // selection, this will have to be reconciled with it.
  1463. this->AddCompilerRequirementFlag(flags, target, lang);
  1464. }
  1465. this->AddLanguageFlags(flags, target, lang, config);
  1466. if (target->IsIPOEnabled(lang, config)) {
  1467. this->AppendFeatureOptions(flags, lang, "IPO");
  1468. }
  1469. }
  1470. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1471. const std::string& name) const
  1472. {
  1473. GeneratorTargetMap::const_iterator imported =
  1474. this->ImportedGeneratorTargets.find(name);
  1475. if (imported != this->ImportedGeneratorTargets.end()) {
  1476. return imported->second;
  1477. }
  1478. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1479. return t;
  1480. }
  1481. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1482. }
  1483. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1484. const std::string& config,
  1485. std::string& dep)
  1486. {
  1487. // Older CMake code may specify the dependency using the target
  1488. // output file rather than the target name. Such code would have
  1489. // been written before there was support for target properties that
  1490. // modify the name so stripping down to just the file name should
  1491. // produce the target name in this case.
  1492. std::string name = cmSystemTools::GetFilenameName(inName);
  1493. // If the input name is the empty string, there is no real
  1494. // dependency. Short-circuit the other checks:
  1495. if (name.empty()) {
  1496. return false;
  1497. }
  1498. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1499. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1500. }
  1501. // Look for a CMake target with the given name.
  1502. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1503. // make sure it is not just a coincidence that the target name
  1504. // found is part of the inName
  1505. if (cmSystemTools::FileIsFullPath(inName)) {
  1506. std::string tLocation;
  1507. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1508. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1509. tLocation = target->GetLocation(config);
  1510. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1511. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1512. }
  1513. std::string depLocation =
  1514. cmSystemTools::GetFilenamePath(std::string(inName));
  1515. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1516. if (depLocation != tLocation) {
  1517. // it is a full path to a depend that has the same name
  1518. // as a target but is in a different location so do not use
  1519. // the target as the depend
  1520. dep = inName;
  1521. return true;
  1522. }
  1523. }
  1524. switch (target->GetType()) {
  1525. case cmStateEnums::EXECUTABLE:
  1526. case cmStateEnums::STATIC_LIBRARY:
  1527. case cmStateEnums::SHARED_LIBRARY:
  1528. case cmStateEnums::MODULE_LIBRARY:
  1529. case cmStateEnums::UNKNOWN_LIBRARY:
  1530. dep = target->GetLocation(config);
  1531. return true;
  1532. case cmStateEnums::OBJECT_LIBRARY:
  1533. // An object library has no single file on which to depend.
  1534. // This was listed to get the target-level dependency.
  1535. return false;
  1536. case cmStateEnums::INTERFACE_LIBRARY:
  1537. // An interface library has no file on which to depend.
  1538. // This was listed to get the target-level dependency.
  1539. return false;
  1540. case cmStateEnums::UTILITY:
  1541. case cmStateEnums::GLOBAL_TARGET:
  1542. // A utility target has no file on which to depend. This was listed
  1543. // only to get the target-level dependency.
  1544. return false;
  1545. }
  1546. }
  1547. // The name was not that of a CMake target. It must name a file.
  1548. if (cmSystemTools::FileIsFullPath(inName)) {
  1549. // This is a full path. Return it as given.
  1550. dep = inName;
  1551. return true;
  1552. }
  1553. // Check for a source file in this directory that matches the
  1554. // dependency.
  1555. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1556. dep = sf->GetFullPath();
  1557. return true;
  1558. }
  1559. // Treat the name as relative to the source directory in which it
  1560. // was given.
  1561. dep = this->StateSnapshot.GetDirectory().GetCurrentSource();
  1562. dep += "/";
  1563. dep += inName;
  1564. return true;
  1565. }
  1566. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1567. const std::string& lang, bool shared)
  1568. {
  1569. std::string flagsVar;
  1570. // Add flags for dealing with shared libraries for this language.
  1571. if (shared) {
  1572. this->AppendFlags(flags,
  1573. this->Makefile->GetDefinition(
  1574. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1575. }
  1576. }
  1577. void cmLocalGenerator::AddCompilerRequirementFlag(
  1578. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1579. {
  1580. if (lang.empty()) {
  1581. return;
  1582. }
  1583. const char* defaultStd =
  1584. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1585. if (!defaultStd || !*defaultStd) {
  1586. // This compiler has no notion of language standard levels.
  1587. return;
  1588. }
  1589. std::string extProp = lang + "_EXTENSIONS";
  1590. bool ext = true;
  1591. if (const char* extPropValue = target->GetProperty(extProp)) {
  1592. if (cmIsOff(extPropValue)) {
  1593. ext = false;
  1594. }
  1595. }
  1596. std::string stdProp = lang + "_STANDARD";
  1597. const char* standardProp = target->GetProperty(stdProp);
  1598. if (!standardProp) {
  1599. if (ext) {
  1600. // No language standard is specified and extensions are not disabled.
  1601. // Check if this compiler needs a flag to enable extensions.
  1602. std::string const option_flag =
  1603. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1604. if (const char* opt =
  1605. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1606. std::vector<std::string> optVec;
  1607. cmExpandList(opt, optVec);
  1608. for (std::string const& i : optVec) {
  1609. this->AppendFlagEscape(flags, i);
  1610. }
  1611. }
  1612. }
  1613. return;
  1614. }
  1615. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1616. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1617. std::string option_flag =
  1618. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1619. const char* opt =
  1620. target->Target->GetMakefile()->GetDefinition(option_flag);
  1621. if (!opt) {
  1622. std::ostringstream e;
  1623. e << "Target \"" << target->GetName()
  1624. << "\" requires the language "
  1625. "dialect \""
  1626. << lang << standardProp << "\" "
  1627. << (ext ? "(with compiler extensions)" : "")
  1628. << ", but CMake "
  1629. "does not know the compile flags to use to enable it.";
  1630. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1631. } else {
  1632. std::vector<std::string> optVec;
  1633. cmExpandList(opt, optVec);
  1634. for (std::string const& i : optVec) {
  1635. this->AppendFlagEscape(flags, i);
  1636. }
  1637. }
  1638. return;
  1639. }
  1640. static std::map<std::string, std::vector<std::string>> langStdMap;
  1641. if (langStdMap.empty()) {
  1642. // Maintain sorted order, most recent first.
  1643. langStdMap["CXX"].emplace_back("20");
  1644. langStdMap["CXX"].emplace_back("17");
  1645. langStdMap["CXX"].emplace_back("14");
  1646. langStdMap["CXX"].emplace_back("11");
  1647. langStdMap["CXX"].emplace_back("98");
  1648. langStdMap["C"].emplace_back("11");
  1649. langStdMap["C"].emplace_back("99");
  1650. langStdMap["C"].emplace_back("90");
  1651. langStdMap["CUDA"].emplace_back("14");
  1652. langStdMap["CUDA"].emplace_back("11");
  1653. langStdMap["CUDA"].emplace_back("98");
  1654. }
  1655. std::string standard(standardProp);
  1656. std::vector<std::string>& stds = langStdMap[lang];
  1657. std::vector<std::string>::const_iterator stdIt =
  1658. std::find(stds.begin(), stds.end(), standard);
  1659. if (stdIt == stds.end()) {
  1660. std::string e =
  1661. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1662. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1663. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1664. return;
  1665. }
  1666. std::vector<std::string>::const_iterator defaultStdIt =
  1667. std::find(stds.begin(), stds.end(), defaultStd);
  1668. if (defaultStdIt == stds.end()) {
  1669. std::string e = "CMAKE_" + lang +
  1670. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1671. "'";
  1672. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1673. return;
  1674. }
  1675. // If the standard requested is older than the compiler's default
  1676. // then we need to use a flag to change it. The comparison is
  1677. // greater-or-equal because the standards are stored in backward
  1678. // chronological order.
  1679. if (stdIt >= defaultStdIt) {
  1680. std::string option_flag =
  1681. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1682. std::string const& opt =
  1683. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1684. std::vector<std::string> optVec;
  1685. cmExpandList(opt, optVec);
  1686. for (std::string const& i : optVec) {
  1687. this->AppendFlagEscape(flags, i);
  1688. }
  1689. return;
  1690. }
  1691. // The standard requested is at least as new as the compiler's default,
  1692. // and the standard request is not required. Decay to the newest standard
  1693. // for which a flag is defined.
  1694. for (; stdIt < defaultStdIt; ++stdIt) {
  1695. std::string option_flag =
  1696. cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION");
  1697. if (const char* opt =
  1698. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1699. std::vector<std::string> optVec;
  1700. cmExpandList(opt, optVec);
  1701. for (std::string const& i : optVec) {
  1702. this->AppendFlagEscape(flags, i);
  1703. }
  1704. return;
  1705. }
  1706. }
  1707. }
  1708. static void AddVisibilityCompileOption(std::string& flags,
  1709. cmGeneratorTarget const* target,
  1710. cmLocalGenerator* lg,
  1711. const std::string& lang,
  1712. std::string* warnCMP0063)
  1713. {
  1714. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1715. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1716. if (!opt) {
  1717. return;
  1718. }
  1719. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1720. const char* prop = target->GetProperty(flagDefine);
  1721. if (!prop) {
  1722. return;
  1723. }
  1724. if (warnCMP0063) {
  1725. *warnCMP0063 += " " + flagDefine + "\n";
  1726. return;
  1727. }
  1728. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1729. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1730. std::ostringstream e;
  1731. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1732. << "\" for " << flagDefine << "."
  1733. << " The supported values are: default, hidden, protected, and "
  1734. "internal.";
  1735. cmSystemTools::Error(e.str());
  1736. return;
  1737. }
  1738. std::string option = std::string(opt) + prop;
  1739. lg->AppendFlags(flags, option);
  1740. }
  1741. static void AddInlineVisibilityCompileOption(std::string& flags,
  1742. cmGeneratorTarget const* target,
  1743. cmLocalGenerator* lg,
  1744. std::string* warnCMP0063)
  1745. {
  1746. std::string compileOption =
  1747. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1748. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1749. if (!opt) {
  1750. return;
  1751. }
  1752. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1753. if (!prop) {
  1754. return;
  1755. }
  1756. if (warnCMP0063) {
  1757. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1758. return;
  1759. }
  1760. lg->AppendFlags(flags, opt);
  1761. }
  1762. void cmLocalGenerator::AddVisibilityPresetFlags(
  1763. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1764. {
  1765. if (lang.empty()) {
  1766. return;
  1767. }
  1768. std::string warnCMP0063;
  1769. std::string* pWarnCMP0063 = nullptr;
  1770. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1771. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1772. !target->IsExecutableWithExports()) {
  1773. switch (target->GetPolicyStatusCMP0063()) {
  1774. case cmPolicies::OLD:
  1775. return;
  1776. case cmPolicies::WARN:
  1777. pWarnCMP0063 = &warnCMP0063;
  1778. break;
  1779. default:
  1780. break;
  1781. }
  1782. }
  1783. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1784. if (lang == "CXX") {
  1785. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1786. }
  1787. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1788. std::ostringstream w;
  1789. /* clang-format off */
  1790. w <<
  1791. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1792. "Target \"" << target->GetName() << "\" of "
  1793. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1794. "has the following visibility properties set for " << lang << ":\n" <<
  1795. warnCMP0063 <<
  1796. "For compatibility CMake is not honoring them for this target.";
  1797. /* clang-format on */
  1798. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1799. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1800. }
  1801. }
  1802. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1803. cmGeneratorTarget const* target,
  1804. std::string const& lang,
  1805. const std::string& config)
  1806. {
  1807. int targetType = target->GetType();
  1808. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1809. (targetType == cmStateEnums::MODULE_LIBRARY));
  1810. if (this->GetShouldUseOldFlags(shared, lang)) {
  1811. this->AddSharedFlags(flags, lang, shared);
  1812. } else {
  1813. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1814. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1815. this->AddPositionIndependentFlags(flags, lang, targetType);
  1816. }
  1817. return;
  1818. }
  1819. if (target->GetLinkInterfaceDependentBoolProperty(
  1820. "POSITION_INDEPENDENT_CODE", config)) {
  1821. this->AddPositionIndependentFlags(flags, lang, targetType);
  1822. }
  1823. if (shared) {
  1824. this->AppendFeatureOptions(flags, lang, "DLL");
  1825. }
  1826. }
  1827. }
  1828. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1829. const std::string& lang) const
  1830. {
  1831. std::string originalFlags =
  1832. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1833. if (shared) {
  1834. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  1835. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  1836. if (flags != originalFlags) {
  1837. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1838. case cmPolicies::WARN: {
  1839. std::ostringstream e;
  1840. e << "Variable " << flagsVar
  1841. << " has been modified. CMake "
  1842. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1843. "shared libraries and will use the "
  1844. << flagsVar
  1845. << " variable "
  1846. "instead. This may cause errors if the original content of "
  1847. << flagsVar << " was removed.\n"
  1848. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1849. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1850. CM_FALLTHROUGH;
  1851. }
  1852. case cmPolicies::OLD:
  1853. return true;
  1854. case cmPolicies::REQUIRED_IF_USED:
  1855. case cmPolicies::REQUIRED_ALWAYS:
  1856. case cmPolicies::NEW:
  1857. return false;
  1858. }
  1859. }
  1860. }
  1861. return false;
  1862. }
  1863. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1864. std::string const& lang,
  1865. int targetType)
  1866. {
  1867. std::string picFlags;
  1868. if (targetType == cmStateEnums::EXECUTABLE) {
  1869. picFlags = this->Makefile->GetSafeDefinition(
  1870. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  1871. }
  1872. if (picFlags.empty()) {
  1873. picFlags = this->Makefile->GetSafeDefinition(
  1874. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  1875. }
  1876. if (!picFlags.empty()) {
  1877. std::vector<std::string> options;
  1878. cmExpandList(picFlags, options);
  1879. for (std::string const& o : options) {
  1880. this->AppendFlagEscape(flags, o);
  1881. }
  1882. }
  1883. }
  1884. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1885. const std::string& var,
  1886. const std::string& config)
  1887. {
  1888. // Add the flags from the variable itself.
  1889. std::string flagsVar = var;
  1890. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1891. // Add the flags from the build-type specific variable.
  1892. if (!config.empty()) {
  1893. flagsVar += "_";
  1894. flagsVar += cmSystemTools::UpperCase(config);
  1895. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1896. }
  1897. }
  1898. void cmLocalGenerator::AppendFlags(std::string& flags,
  1899. const std::string& newFlags) const
  1900. {
  1901. if (!newFlags.empty()) {
  1902. if (!flags.empty()) {
  1903. flags += " ";
  1904. }
  1905. flags += newFlags;
  1906. }
  1907. }
  1908. void cmLocalGenerator::AppendFlags(std::string& flags,
  1909. const char* newFlags) const
  1910. {
  1911. if (newFlags && *newFlags) {
  1912. this->AppendFlags(flags, std::string(newFlags));
  1913. }
  1914. }
  1915. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  1916. const std::string& rawFlag) const
  1917. {
  1918. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  1919. }
  1920. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  1921. cmGeneratorTarget* target,
  1922. const std::string& config,
  1923. const std::string& lang)
  1924. {
  1925. if (!target->IsIPOEnabled(lang, config)) {
  1926. return;
  1927. }
  1928. switch (target->GetType()) {
  1929. case cmStateEnums::EXECUTABLE:
  1930. case cmStateEnums::SHARED_LIBRARY:
  1931. case cmStateEnums::MODULE_LIBRARY:
  1932. break;
  1933. default:
  1934. return;
  1935. }
  1936. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  1937. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  1938. if (rawFlagsList == nullptr) {
  1939. return;
  1940. }
  1941. std::vector<std::string> flagsList;
  1942. cmExpandList(rawFlagsList, flagsList);
  1943. for (std::string const& o : flagsList) {
  1944. this->AppendFlagEscape(flags, o);
  1945. }
  1946. }
  1947. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  1948. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  1949. const std::string& lang)
  1950. {
  1951. // For now, only EXECUTABLE is concerned
  1952. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  1953. return;
  1954. }
  1955. const char* PICValue = target->GetLinkPIEProperty(config);
  1956. if (PICValue == nullptr) {
  1957. // POSITION_INDEPENDENT_CODE is not set
  1958. return;
  1959. }
  1960. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  1961. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  1962. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  1963. return;
  1964. }
  1965. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  1966. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  1967. if (pieFlags.empty()) {
  1968. return;
  1969. }
  1970. std::vector<std::string> flagsList;
  1971. cmExpandList(pieFlags, flagsList);
  1972. for (const auto& flag : flagsList) {
  1973. this->AppendFlagEscape(flags, flag);
  1974. }
  1975. }
  1976. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  1977. const char* options_list,
  1978. const char* regex) const
  1979. {
  1980. // Short-circuit if there are no options.
  1981. if (!options_list) {
  1982. return;
  1983. }
  1984. // Expand the list of options.
  1985. std::vector<std::string> options_vec;
  1986. cmExpandList(options_list, options_vec);
  1987. this->AppendCompileOptions(options, options_vec, regex);
  1988. }
  1989. void cmLocalGenerator::AppendCompileOptions(
  1990. std::string& options, const std::vector<std::string>& options_vec,
  1991. const char* regex) const
  1992. {
  1993. if (regex != nullptr) {
  1994. // Filter flags upon specified reges.
  1995. cmsys::RegularExpression r(regex);
  1996. for (std::string const& opt : options_vec) {
  1997. if (r.find(opt)) {
  1998. this->AppendFlagEscape(options, opt);
  1999. }
  2000. }
  2001. } else {
  2002. for (std::string const& opt : options_vec) {
  2003. this->AppendFlagEscape(options, opt);
  2004. }
  2005. }
  2006. }
  2007. void cmLocalGenerator::AppendIncludeDirectories(
  2008. std::vector<std::string>& includes, const char* includes_list,
  2009. const cmSourceFile& sourceFile) const
  2010. {
  2011. // Short-circuit if there are no includes.
  2012. if (!includes_list) {
  2013. return;
  2014. }
  2015. // Expand the list of includes.
  2016. std::vector<std::string> includes_vec;
  2017. cmExpandList(includes_list, includes_vec);
  2018. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2019. }
  2020. void cmLocalGenerator::AppendIncludeDirectories(
  2021. std::vector<std::string>& includes,
  2022. const std::vector<std::string>& includes_vec,
  2023. const cmSourceFile& sourceFile) const
  2024. {
  2025. std::unordered_set<std::string> uniqueIncludes;
  2026. for (const std::string& include : includes_vec) {
  2027. if (!cmSystemTools::FileIsFullPath(include)) {
  2028. std::ostringstream e;
  2029. e << "Found relative path while evaluating include directories of "
  2030. "\""
  2031. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2032. << "\"\n";
  2033. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2034. return;
  2035. }
  2036. std::string inc = include;
  2037. if (!cmIsOff(inc)) {
  2038. cmSystemTools::ConvertToUnixSlashes(inc);
  2039. }
  2040. if (uniqueIncludes.insert(inc).second) {
  2041. includes.push_back(std::move(inc));
  2042. }
  2043. }
  2044. }
  2045. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2046. std::string const& defines_list) const
  2047. {
  2048. std::set<BT<std::string>> tmp;
  2049. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2050. for (BT<std::string> const& i : tmp) {
  2051. defines.emplace(i.Value);
  2052. }
  2053. }
  2054. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2055. std::string const& defines_list) const
  2056. {
  2057. // Short-circuit if there are no definitions.
  2058. if (defines_list.empty()) {
  2059. return;
  2060. }
  2061. // Expand the list of definitions.
  2062. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2063. }
  2064. void cmLocalGenerator::AppendDefines(
  2065. std::set<BT<std::string>>& defines,
  2066. const std::vector<BT<std::string>>& defines_vec) const
  2067. {
  2068. for (BT<std::string> const& d : defines_vec) {
  2069. // Skip unsupported definitions.
  2070. if (!this->CheckDefinition(d.Value)) {
  2071. continue;
  2072. }
  2073. defines.insert(d);
  2074. }
  2075. }
  2076. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2077. std::string& definesString,
  2078. const std::string& lang)
  2079. {
  2080. // Lookup the define flag for the current language.
  2081. std::string dflag = "-D";
  2082. if (!lang.empty()) {
  2083. const char* df =
  2084. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  2085. if (df && *df) {
  2086. dflag = df;
  2087. }
  2088. }
  2089. const char* itemSeparator = definesString.empty() ? "" : " ";
  2090. for (std::string const& define : defines) {
  2091. // Append the definition with proper escaping.
  2092. std::string def = dflag;
  2093. if (this->GetState()->UseWatcomWMake()) {
  2094. // The Watcom compiler does its own command line parsing instead
  2095. // of using the windows shell rules. Definitions are one of
  2096. // -DNAME
  2097. // -DNAME=<cpp-token>
  2098. // -DNAME="c-string with spaces and other characters(?@#$)"
  2099. //
  2100. // Watcom will properly parse each of these cases from the
  2101. // command line without any escapes. However we still have to
  2102. // get the '$' and '#' characters through WMake as '$$' and
  2103. // '$#'.
  2104. for (const char* c = define.c_str(); *c; ++c) {
  2105. if (*c == '$' || *c == '#') {
  2106. def += '$';
  2107. }
  2108. def += *c;
  2109. }
  2110. } else {
  2111. // Make the definition appear properly on the command line. Use
  2112. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2113. std::string::size_type eq = define.find('=');
  2114. def += define.substr(0, eq);
  2115. if (eq != std::string::npos) {
  2116. def += "=";
  2117. def += this->EscapeForShell(define.substr(eq + 1), true);
  2118. }
  2119. }
  2120. definesString += itemSeparator;
  2121. itemSeparator = " ";
  2122. definesString += def;
  2123. }
  2124. }
  2125. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2126. const std::string& lang,
  2127. const char* feature)
  2128. {
  2129. const char* optionList = this->Makefile->GetDefinition(
  2130. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  2131. if (optionList != nullptr) {
  2132. std::vector<std::string> options;
  2133. cmExpandList(optionList, options);
  2134. for (std::string const& o : options) {
  2135. this->AppendFlagEscape(flags, o);
  2136. }
  2137. }
  2138. }
  2139. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2140. const std::string& config)
  2141. {
  2142. std::string featureName = feature;
  2143. // TODO: Define accumulation policy for features (prepend, append, replace).
  2144. // Currently we always replace.
  2145. if (!config.empty()) {
  2146. featureName += "_";
  2147. featureName += cmSystemTools::UpperCase(config);
  2148. }
  2149. cmStateSnapshot snp = this->StateSnapshot;
  2150. while (snp.IsValid()) {
  2151. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2152. return value;
  2153. }
  2154. snp = snp.GetBuildsystemDirectoryParent();
  2155. }
  2156. return nullptr;
  2157. }
  2158. std::string cmLocalGenerator::GetProjectName() const
  2159. {
  2160. return this->StateSnapshot.GetProjectName();
  2161. }
  2162. std::string cmLocalGenerator::ConstructComment(
  2163. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2164. {
  2165. // Check for a comment provided with the command.
  2166. if (ccg.GetComment()) {
  2167. return ccg.GetComment();
  2168. }
  2169. // Construct a reasonable default comment if possible.
  2170. if (!ccg.GetOutputs().empty()) {
  2171. std::string comment;
  2172. comment = "Generating ";
  2173. const char* sep = "";
  2174. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2175. for (std::string const& o : ccg.GetOutputs()) {
  2176. comment += sep;
  2177. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2178. sep = ", ";
  2179. }
  2180. return comment;
  2181. }
  2182. // Otherwise use the provided default.
  2183. return default_comment;
  2184. }
  2185. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2186. {
  2187. public:
  2188. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2189. const char* dest, bool implib)
  2190. : cmInstallTargetGenerator(
  2191. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2192. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2193. false)
  2194. {
  2195. this->Compute(lg);
  2196. }
  2197. };
  2198. void cmLocalGenerator::GenerateTargetInstallRules(
  2199. std::ostream& os, const std::string& config,
  2200. std::vector<std::string> const& configurationTypes)
  2201. {
  2202. // Convert the old-style install specification from each target to
  2203. // an install generator and run it.
  2204. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  2205. for (cmGeneratorTarget* l : tgts) {
  2206. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2207. continue;
  2208. }
  2209. // Include the user-specified pre-install script for this target.
  2210. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2211. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2212. g.Generate(os, config, configurationTypes);
  2213. }
  2214. // Install this target if a destination is given.
  2215. if (!l->Target->GetInstallPath().empty()) {
  2216. // Compute the full install destination. Note that converting
  2217. // to unix slashes also removes any trailing slash.
  2218. // We also skip over the leading slash given by the user.
  2219. std::string destination = l->Target->GetInstallPath().substr(1);
  2220. cmSystemTools::ConvertToUnixSlashes(destination);
  2221. if (destination.empty()) {
  2222. destination = ".";
  2223. }
  2224. // Generate the proper install generator for this target type.
  2225. switch (l->GetType()) {
  2226. case cmStateEnums::EXECUTABLE:
  2227. case cmStateEnums::STATIC_LIBRARY:
  2228. case cmStateEnums::MODULE_LIBRARY: {
  2229. // Use a target install generator.
  2230. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2231. destination.c_str(), false);
  2232. g.Generate(os, config, configurationTypes);
  2233. } break;
  2234. case cmStateEnums::SHARED_LIBRARY: {
  2235. #if defined(_WIN32) || defined(__CYGWIN__)
  2236. // Special code to handle DLL. Install the import library
  2237. // to the normal destination and the DLL to the runtime
  2238. // destination.
  2239. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2240. destination.c_str(), true);
  2241. g1.Generate(os, config, configurationTypes);
  2242. // We also skip over the leading slash given by the user.
  2243. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2244. cmSystemTools::ConvertToUnixSlashes(destination);
  2245. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2246. destination.c_str(), false);
  2247. g2.Generate(os, config, configurationTypes);
  2248. #else
  2249. // Use a target install generator.
  2250. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2251. destination.c_str(), false);
  2252. g.Generate(os, config, configurationTypes);
  2253. #endif
  2254. } break;
  2255. default:
  2256. break;
  2257. }
  2258. }
  2259. // Include the user-specified post-install script for this target.
  2260. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2261. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2262. g.Generate(os, config, configurationTypes);
  2263. }
  2264. }
  2265. }
  2266. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2267. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2268. std::string::size_type max_len)
  2269. {
  2270. // Replace the beginning of the path portion of the object name with
  2271. // its own md5 sum.
  2272. std::string::size_type pos =
  2273. objName.find('/', objName.size() - max_len + 32);
  2274. if (pos != std::string::npos) {
  2275. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2276. std::string md5name = md5.HashString(objName.substr(0, pos));
  2277. md5name += objName.substr(pos);
  2278. objName = md5name;
  2279. // The object name is now short enough.
  2280. return true;
  2281. }
  2282. // The object name could not be shortened enough.
  2283. return false;
  2284. }
  2285. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2286. std::string::size_type dir_len,
  2287. std::string::size_type max_total_len)
  2288. {
  2289. // Enforce the maximum file name length if possible.
  2290. std::string::size_type max_obj_len = max_total_len;
  2291. if (dir_len < max_total_len) {
  2292. max_obj_len = max_total_len - dir_len;
  2293. if (objName.size() > max_obj_len) {
  2294. // The current object file name is too long. Try to shorten it.
  2295. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2296. }
  2297. // The object file name is short enough.
  2298. return true;
  2299. }
  2300. // The build directory in which the object will be stored is
  2301. // already too deep.
  2302. return false;
  2303. }
  2304. #endif
  2305. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2306. const std::string& sin, std::string const& dir_max)
  2307. {
  2308. // Look for an existing mapped name for this object file.
  2309. std::map<std::string, std::string>::iterator it =
  2310. this->UniqueObjectNamesMap.find(sin);
  2311. // If no entry exists create one.
  2312. if (it == this->UniqueObjectNamesMap.end()) {
  2313. // Start with the original name.
  2314. std::string ssin = sin;
  2315. // Avoid full paths by removing leading slashes.
  2316. ssin.erase(0, ssin.find_first_not_of('/'));
  2317. // Avoid full paths by removing colons.
  2318. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2319. // Avoid relative paths that go up the tree.
  2320. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2321. // Avoid spaces.
  2322. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2323. // Mangle the name if necessary.
  2324. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2325. bool done;
  2326. int cc = 0;
  2327. char rpstr[100];
  2328. sprintf(rpstr, "_p_");
  2329. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2330. std::string sssin = sin;
  2331. do {
  2332. done = true;
  2333. for (it = this->UniqueObjectNamesMap.begin();
  2334. it != this->UniqueObjectNamesMap.end(); ++it) {
  2335. if (it->second == ssin) {
  2336. done = false;
  2337. }
  2338. }
  2339. if (done) {
  2340. break;
  2341. }
  2342. sssin = ssin;
  2343. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2344. sprintf(rpstr, "_p%d_", cc++);
  2345. } while (!done);
  2346. }
  2347. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2348. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2349. this->ObjectPathMax)) {
  2350. // Warn if this is the first time the path has been seen.
  2351. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2352. std::ostringstream m;
  2353. /* clang-format off */
  2354. m << "The object file directory\n"
  2355. << " " << dir_max << "\n"
  2356. << "has " << dir_max.size() << " characters. "
  2357. << "The maximum full path to an object file is "
  2358. << this->ObjectPathMax << " characters "
  2359. << "(see CMAKE_OBJECT_PATH_MAX). "
  2360. << "Object file\n"
  2361. << " " << ssin << "\n"
  2362. << "cannot be safely placed under this directory. "
  2363. << "The build may not work correctly.";
  2364. /* clang-format on */
  2365. this->IssueMessage(MessageType::WARNING, m.str());
  2366. }
  2367. }
  2368. #else
  2369. (void)dir_max;
  2370. #endif
  2371. // Insert the newly mapped object file name.
  2372. std::map<std::string, std::string>::value_type e(sin, ssin);
  2373. it = this->UniqueObjectNamesMap.insert(e).first;
  2374. }
  2375. // Return the map entry.
  2376. return it->second;
  2377. }
  2378. void cmLocalGenerator::ComputeObjectFilenames(
  2379. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2380. cmGeneratorTarget const* /*unused*/)
  2381. {
  2382. }
  2383. bool cmLocalGenerator::IsWindowsShell() const
  2384. {
  2385. return this->GetState()->UseWindowsShell();
  2386. }
  2387. bool cmLocalGenerator::IsWatcomWMake() const
  2388. {
  2389. return this->GetState()->UseWatcomWMake();
  2390. }
  2391. bool cmLocalGenerator::IsMinGWMake() const
  2392. {
  2393. return this->GetState()->UseMinGWMake();
  2394. }
  2395. bool cmLocalGenerator::IsNMake() const
  2396. {
  2397. return this->GetState()->UseNMake();
  2398. }
  2399. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2400. const cmSourceFile& source, std::string const& dir_max,
  2401. bool* hasSourceExtension, char const* customOutputExtension)
  2402. {
  2403. // Construct the object file name using the full path to the source
  2404. // file which is its only unique identification.
  2405. std::string const& fullPath = source.GetFullPath();
  2406. // Try referencing the source relative to the source tree.
  2407. std::string relFromSource = this->MaybeConvertToRelativePath(
  2408. this->GetCurrentSourceDirectory(), fullPath);
  2409. assert(!relFromSource.empty());
  2410. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2411. bool subSource = relSource && relFromSource[0] != '.';
  2412. // Try referencing the source relative to the binary tree.
  2413. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2414. this->GetCurrentBinaryDirectory(), fullPath);
  2415. assert(!relFromBinary.empty());
  2416. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2417. bool subBinary = relBinary && relFromBinary[0] != '.';
  2418. // Select a nice-looking reference to the source file to construct
  2419. // the object file name.
  2420. std::string objectName;
  2421. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2422. objectName = relFromSource;
  2423. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2424. objectName = relFromBinary;
  2425. } else if (relFromBinary.length() < relFromSource.length()) {
  2426. objectName = relFromBinary;
  2427. } else {
  2428. objectName = relFromSource;
  2429. }
  2430. // if it is still a full path check for the try compile case
  2431. // try compile never have in source sources, and should not
  2432. // have conflicting source file names in the same target
  2433. if (cmSystemTools::FileIsFullPath(objectName)) {
  2434. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2435. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2436. }
  2437. }
  2438. // Replace the original source file extension with the object file
  2439. // extension.
  2440. bool keptSourceExtension = true;
  2441. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2442. // Decide whether this language wants to replace the source
  2443. // extension with the object extension. For CMake 2.4
  2444. // compatibility do this by default.
  2445. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2446. if (!replaceExt) {
  2447. std::string lang = source.GetLanguage();
  2448. if (!lang.empty()) {
  2449. replaceExt = this->Makefile->IsOn(
  2450. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  2451. }
  2452. }
  2453. // Remove the source extension if it is to be replaced.
  2454. if (replaceExt || customOutputExtension) {
  2455. keptSourceExtension = false;
  2456. std::string::size_type dot_pos = objectName.rfind('.');
  2457. if (dot_pos != std::string::npos) {
  2458. objectName = objectName.substr(0, dot_pos);
  2459. }
  2460. }
  2461. // Store the new extension.
  2462. if (customOutputExtension) {
  2463. objectName += customOutputExtension;
  2464. } else {
  2465. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2466. }
  2467. }
  2468. if (hasSourceExtension) {
  2469. *hasSourceExtension = keptSourceExtension;
  2470. }
  2471. // Convert to a safe name.
  2472. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2473. }
  2474. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2475. {
  2476. return source.GetLanguage();
  2477. }
  2478. cmake* cmLocalGenerator::GetCMakeInstance() const
  2479. {
  2480. return this->GlobalGenerator->GetCMakeInstance();
  2481. }
  2482. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2483. {
  2484. return this->GetCMakeInstance()->GetHomeDirectory();
  2485. }
  2486. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2487. {
  2488. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2489. }
  2490. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2491. {
  2492. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2493. }
  2494. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2495. {
  2496. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2497. }
  2498. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2499. std::string const& local_path, std::string const& remote_path) const
  2500. {
  2501. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2502. local_path, remote_path);
  2503. }
  2504. std::string cmLocalGenerator::GetTargetDirectory(
  2505. const cmGeneratorTarget* /*unused*/) const
  2506. {
  2507. cmSystemTools::Error("GetTargetDirectory"
  2508. " called on cmLocalGenerator");
  2509. return "";
  2510. }
  2511. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2512. {
  2513. // The computed version may change until the project is fully
  2514. // configured.
  2515. if (!this->BackwardsCompatibilityFinal) {
  2516. unsigned int major = 0;
  2517. unsigned int minor = 0;
  2518. unsigned int patch = 0;
  2519. if (const char* value =
  2520. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2521. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2522. case 2:
  2523. patch = 0;
  2524. break;
  2525. case 1:
  2526. minor = 0;
  2527. patch = 0;
  2528. break;
  2529. default:
  2530. break;
  2531. }
  2532. }
  2533. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2534. this->BackwardsCompatibilityFinal = true;
  2535. }
  2536. return this->BackwardsCompatibility;
  2537. }
  2538. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2539. {
  2540. // Check the policy to decide whether to pay attention to this
  2541. // variable.
  2542. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2543. case cmPolicies::WARN:
  2544. // WARN is just OLD without warning because user code does not
  2545. // always affect whether this check is done.
  2546. case cmPolicies::OLD:
  2547. // Old behavior is to check the variable.
  2548. break;
  2549. case cmPolicies::NEW:
  2550. // New behavior is to ignore the variable.
  2551. return false;
  2552. case cmPolicies::REQUIRED_IF_USED:
  2553. case cmPolicies::REQUIRED_ALWAYS:
  2554. // This will never be the case because the only way to require
  2555. // the setting is to require the user to specify version policy
  2556. // 2.6 or higher. Once we add that requirement then this whole
  2557. // method can be removed anyway.
  2558. return false;
  2559. }
  2560. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2561. // equal to or lower than the given version.
  2562. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2563. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2564. }
  2565. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2566. cmPolicies::PolicyID id) const
  2567. {
  2568. return this->Makefile->GetPolicyStatus(id);
  2569. }
  2570. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2571. {
  2572. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2573. std::string::size_type pos = define.find_first_of("(=");
  2574. if (pos != std::string::npos) {
  2575. if (define[pos] == '(') {
  2576. std::ostringstream e;
  2577. /* clang-format off */
  2578. e << "WARNING: Function-style preprocessor definitions may not be "
  2579. << "passed on the compiler command line because many compilers "
  2580. << "do not support it.\n"
  2581. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2582. << "Consider defining the macro in a (configured) header file.\n";
  2583. /* clang-format on */
  2584. cmSystemTools::Message(e.str());
  2585. return false;
  2586. }
  2587. }
  2588. // Many compilers do not support # in the value so we disable it.
  2589. if (define.find_first_of('#') != std::string::npos) {
  2590. std::ostringstream e;
  2591. /* clang-format off */
  2592. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2593. << "passed on the compiler command line because many compilers "
  2594. << "do not support it.\n"
  2595. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2596. << "Consider defining the macro in a (configured) header file.\n";
  2597. /* clang-format on */
  2598. cmSystemTools::Message(e.str());
  2599. return false;
  2600. }
  2601. // Assume it is supported.
  2602. return true;
  2603. }
  2604. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2605. const std::string& prop)
  2606. {
  2607. if (const char* val = target->GetProperty(prop)) {
  2608. mf->AddDefinition(prop, val);
  2609. }
  2610. }
  2611. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2612. const std::string& targetName,
  2613. const std::string& fname)
  2614. {
  2615. // Find the Info.plist template.
  2616. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2617. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2618. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2619. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2620. if (!inMod.empty()) {
  2621. inFile = inMod;
  2622. }
  2623. }
  2624. if (!cmSystemTools::FileExists(inFile, true)) {
  2625. std::ostringstream e;
  2626. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2627. << "\" could not be found.";
  2628. cmSystemTools::Error(e.str());
  2629. return;
  2630. }
  2631. // Convert target properties to variables in an isolated makefile
  2632. // scope to configure the file. If properties are set they will
  2633. // override user make variables. If not the configuration will fall
  2634. // back to the directory-level values set by the user.
  2635. cmMakefile* mf = this->Makefile;
  2636. cmMakefile::ScopePushPop varScope(mf);
  2637. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  2638. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2639. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2640. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2641. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2642. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2643. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2644. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2645. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2646. mf->ConfigureFile(inFile, fname, false, false, false);
  2647. }
  2648. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2649. cmGeneratorTarget* target, const std::string& targetName,
  2650. const std::string& fname)
  2651. {
  2652. // Find the Info.plist template.
  2653. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2654. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2655. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2656. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2657. if (!inMod.empty()) {
  2658. inFile = inMod;
  2659. }
  2660. }
  2661. if (!cmSystemTools::FileExists(inFile, true)) {
  2662. std::ostringstream e;
  2663. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2664. << "\" could not be found.";
  2665. cmSystemTools::Error(e.str());
  2666. return;
  2667. }
  2668. // Convert target properties to variables in an isolated makefile
  2669. // scope to configure the file. If properties are set they will
  2670. // override user make variables. If not the configuration will fall
  2671. // back to the directory-level values set by the user.
  2672. cmMakefile* mf = this->Makefile;
  2673. cmMakefile::ScopePushPop varScope(mf);
  2674. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  2675. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  2676. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  2677. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  2678. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  2679. mf->ConfigureFile(inFile, fname, false, false, false);
  2680. }