cmLocalGenerator.cxx 92 KB

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