cmLocalGenerator.cxx 102 KB

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