cmLocalGenerator.cxx 104 KB

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