cmLocalGenerator.cxx 101 KB

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