cmLocalGenerator.cxx 103 KB

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