cmLocalGenerator.cxx 107 KB

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