cmLocalGenerator.cxx 103 KB

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