cmLocalGenerator.cxx 102 KB

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