cmLocalGenerator.cxx 103 KB

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