cmLocalGenerator.cxx 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723
  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. const char* 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. cmGeneratorTarget* target)
  889. {
  890. this->AppendFlags(
  891. flags, this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  892. if (!config.empty()) {
  893. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  894. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(name));
  895. }
  896. this->AppendFlags(flags, target->GetProperty("STATIC_LIBRARY_FLAGS"));
  897. if (!config.empty()) {
  898. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  899. this->AppendFlags(flags, target->GetProperty(name));
  900. }
  901. }
  902. void cmLocalGenerator::GetTargetFlags(
  903. cmLinkLineComputer* linkLineComputer, const std::string& config,
  904. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  905. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  906. {
  907. const std::string buildType = cmSystemTools::UpperCase(config);
  908. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  909. const char* libraryLinkVariable =
  910. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  911. const std::string linkLanguage =
  912. linkLineComputer->GetLinkerLanguage(target, buildType);
  913. switch (target->GetType()) {
  914. case cmStateEnums::STATIC_LIBRARY:
  915. this->GetStaticLibraryFlags(linkFlags, buildType, target);
  916. break;
  917. case cmStateEnums::MODULE_LIBRARY:
  918. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  919. CM_FALLTHROUGH;
  920. case cmStateEnums::SHARED_LIBRARY: {
  921. linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
  922. linkFlags += " ";
  923. if (!buildType.empty()) {
  924. std::string build = libraryLinkVariable;
  925. build += "_";
  926. build += buildType;
  927. linkFlags += this->Makefile->GetSafeDefinition(build);
  928. linkFlags += " ";
  929. }
  930. if (this->Makefile->IsOn("WIN32") &&
  931. !(this->Makefile->IsOn("CYGWIN") || this->Makefile->IsOn("MINGW"))) {
  932. std::vector<cmSourceFile*> sources;
  933. target->GetSourceFiles(sources, buildType);
  934. std::string defFlag =
  935. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  936. for (cmSourceFile* sf : sources) {
  937. if (sf->GetExtension() == "def") {
  938. linkFlags += defFlag;
  939. linkFlags += this->ConvertToOutputFormat(
  940. cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
  941. linkFlags += " ";
  942. }
  943. }
  944. }
  945. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  946. if (targetLinkFlags) {
  947. linkFlags += targetLinkFlags;
  948. linkFlags += " ";
  949. }
  950. if (!buildType.empty()) {
  951. std::string configLinkFlags = "LINK_FLAGS_";
  952. configLinkFlags += buildType;
  953. targetLinkFlags = target->GetProperty(configLinkFlags);
  954. if (targetLinkFlags) {
  955. linkFlags += targetLinkFlags;
  956. linkFlags += " ";
  957. }
  958. }
  959. std::vector<std::string> opts;
  960. target->GetLinkOptions(opts, config, linkLanguage);
  961. // LINK_OPTIONS are escaped.
  962. this->AppendCompileOptions(linkFlags, opts);
  963. if (pcli) {
  964. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  965. frameworkPath, linkPath);
  966. }
  967. } break;
  968. case cmStateEnums::EXECUTABLE: {
  969. linkFlags += this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  970. linkFlags += " ";
  971. if (!buildType.empty()) {
  972. std::string build = "CMAKE_EXE_LINKER_FLAGS_";
  973. build += buildType;
  974. linkFlags += this->Makefile->GetSafeDefinition(build);
  975. linkFlags += " ";
  976. }
  977. if (linkLanguage.empty()) {
  978. cmSystemTools::Error(
  979. "CMake can not determine linker language for target: ",
  980. target->GetName().c_str());
  981. return;
  982. }
  983. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  984. if (pcli) {
  985. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  986. frameworkPath, linkPath);
  987. }
  988. if (cmSystemTools::IsOn(
  989. this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  990. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  991. linkLanguage + std::string("_FLAGS");
  992. linkFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  993. linkFlags += " ";
  994. }
  995. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  996. linkFlags +=
  997. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  998. linkFlags += " ";
  999. } else {
  1000. linkFlags +=
  1001. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1002. linkFlags += " ";
  1003. }
  1004. if (target->IsExecutableWithExports()) {
  1005. std::string exportFlagVar = "CMAKE_EXE_EXPORTS_";
  1006. exportFlagVar += linkLanguage;
  1007. exportFlagVar += "_FLAG";
  1008. linkFlags += this->Makefile->GetSafeDefinition(exportFlagVar);
  1009. linkFlags += " ";
  1010. }
  1011. std::string cmp0065Flags =
  1012. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1013. if (!cmp0065Flags.empty()) {
  1014. linkFlags += cmp0065Flags;
  1015. linkFlags += " ";
  1016. }
  1017. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1018. if (targetLinkFlags) {
  1019. linkFlags += targetLinkFlags;
  1020. linkFlags += " ";
  1021. }
  1022. if (!buildType.empty()) {
  1023. std::string configLinkFlags = "LINK_FLAGS_";
  1024. configLinkFlags += buildType;
  1025. targetLinkFlags = target->GetProperty(configLinkFlags);
  1026. if (targetLinkFlags) {
  1027. linkFlags += targetLinkFlags;
  1028. linkFlags += " ";
  1029. }
  1030. }
  1031. std::vector<std::string> opts;
  1032. target->GetLinkOptions(opts, config, linkLanguage);
  1033. // LINK_OPTIONS are escaped.
  1034. this->AppendCompileOptions(linkFlags, opts);
  1035. } break;
  1036. default:
  1037. break;
  1038. }
  1039. this->AppendIPOLinkerFlags(linkFlags, target, config, linkLanguage);
  1040. }
  1041. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1042. std::string const& config,
  1043. std::string const& lang,
  1044. std::string& flags)
  1045. {
  1046. cmMakefile* mf = this->GetMakefile();
  1047. // Add language-specific flags.
  1048. this->AddLanguageFlags(flags, target, lang, config);
  1049. this->AddArchitectureFlags(flags, target, lang, config);
  1050. if (lang == "Fortran") {
  1051. this->AppendFlags(flags, this->GetTargetFortranFlags(target, config));
  1052. }
  1053. this->AddCMP0018Flags(flags, target, lang, config);
  1054. this->AddVisibilityPresetFlags(flags, target, lang);
  1055. this->AppendFlags(flags, mf->GetDefineFlags());
  1056. this->AppendFlags(flags, this->GetFrameworkFlags(lang, config, target));
  1057. this->AddCompileOptions(flags, target, lang, config);
  1058. }
  1059. static std::string GetFrameworkFlags(const std::string& lang,
  1060. const std::string& config,
  1061. cmGeneratorTarget* target)
  1062. {
  1063. cmLocalGenerator* lg = target->GetLocalGenerator();
  1064. cmMakefile* mf = lg->GetMakefile();
  1065. if (!mf->IsOn("APPLE")) {
  1066. return std::string();
  1067. }
  1068. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1069. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1070. if (!(fwSearchFlag && *fwSearchFlag)) {
  1071. return std::string();
  1072. }
  1073. std::set<std::string> emitted;
  1074. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1075. emitted.insert("/System/Library/Frameworks");
  1076. #endif
  1077. std::vector<std::string> includes;
  1078. lg->GetIncludeDirectories(includes, target, "C", config);
  1079. // check all include directories for frameworks as this
  1080. // will already have added a -F for the framework
  1081. for (std::string const& include : includes) {
  1082. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1083. std::string frameworkDir = include;
  1084. frameworkDir += "/../";
  1085. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1086. emitted.insert(frameworkDir);
  1087. }
  1088. }
  1089. std::string flags;
  1090. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1091. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1092. for (std::string const& framework : frameworks) {
  1093. if (emitted.insert(framework).second) {
  1094. flags += fwSearchFlag;
  1095. flags +=
  1096. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1097. flags += " ";
  1098. }
  1099. }
  1100. }
  1101. return flags;
  1102. }
  1103. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1104. std::string const& config,
  1105. cmGeneratorTarget* target)
  1106. {
  1107. return ::GetFrameworkFlags(l, config, target);
  1108. }
  1109. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1110. std::string const& config,
  1111. std::string const& lang,
  1112. std::set<std::string>& defines) const
  1113. {
  1114. // Add the export symbol definition for shared library objects.
  1115. if (const char* exportMacro = target->GetExportMacro()) {
  1116. this->AppendDefines(defines, exportMacro);
  1117. }
  1118. // Add preprocessor definitions for this target and configuration.
  1119. this->AddCompileDefinitions(defines, target, config, lang);
  1120. }
  1121. std::string cmLocalGenerator::GetTargetFortranFlags(
  1122. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1123. {
  1124. // Implemented by specific generators that override this.
  1125. return std::string();
  1126. }
  1127. /**
  1128. * Output the linking rules on a command line. For executables,
  1129. * targetLibrary should be a NULL pointer. For libraries, it should point
  1130. * to the name of the library. This will not link a library against itself.
  1131. */
  1132. void cmLocalGenerator::OutputLinkLibraries(
  1133. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1134. std::string& linkLibraries, std::string& frameworkPath,
  1135. std::string& linkPath)
  1136. {
  1137. cmComputeLinkInformation& cli = *pcli;
  1138. std::string linkLanguage = cli.GetLinkLanguage();
  1139. std::string libPathFlag =
  1140. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1141. std::string libPathTerminator =
  1142. this->Makefile->GetSafeDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1143. // Add standard libraries for this language.
  1144. std::string standardLibsVar = "CMAKE_";
  1145. standardLibsVar += cli.GetLinkLanguage();
  1146. standardLibsVar += "_STANDARD_LIBRARIES";
  1147. std::string stdLibString;
  1148. if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) {
  1149. stdLibString = stdLibs;
  1150. }
  1151. // Append the framework search path flags.
  1152. std::string fwSearchFlagVar = "CMAKE_";
  1153. fwSearchFlagVar += linkLanguage;
  1154. fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
  1155. std::string fwSearchFlag =
  1156. this->Makefile->GetSafeDefinition(fwSearchFlagVar);
  1157. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1158. linkPath =
  1159. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
  1160. linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
  1161. }
  1162. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1163. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1164. {
  1165. std::string linkFlags;
  1166. // Flags to link an executable to shared libraries.
  1167. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1168. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1169. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1170. bool add_shlib_flags = false;
  1171. switch (tgt.GetPolicyStatusCMP0065()) {
  1172. case cmPolicies::WARN:
  1173. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1174. this->Makefile->PolicyOptionalWarningEnabled(
  1175. "CMAKE_POLICY_WARNING_CMP0065")) {
  1176. std::ostringstream w;
  1177. /* clang-format off */
  1178. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1179. "For compatibility with older versions of CMake, "
  1180. "additional flags may be added to export symbols on all "
  1181. "executables regardless of their ENABLE_EXPORTS property.";
  1182. /* clang-format on */
  1183. this->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  1184. }
  1185. CM_FALLTHROUGH;
  1186. case cmPolicies::OLD:
  1187. // OLD behavior is to always add the flags
  1188. add_shlib_flags = true;
  1189. break;
  1190. case cmPolicies::REQUIRED_IF_USED:
  1191. case cmPolicies::REQUIRED_ALWAYS:
  1192. this->IssueMessage(
  1193. cmake::FATAL_ERROR,
  1194. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1195. CM_FALLTHROUGH;
  1196. case cmPolicies::NEW:
  1197. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on
  1198. add_shlib_flags = tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1199. break;
  1200. }
  1201. if (add_shlib_flags) {
  1202. std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_";
  1203. linkFlagsVar += linkLanguage;
  1204. linkFlagsVar += "_FLAGS";
  1205. linkFlags = this->Makefile->GetSafeDefinition(linkFlagsVar);
  1206. }
  1207. }
  1208. return linkFlags;
  1209. }
  1210. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1211. cmGeneratorTarget const* target,
  1212. const std::string& lang,
  1213. const std::string& config)
  1214. {
  1215. // Only add Mac OS X specific flags on Darwin platforms (OSX and iphone):
  1216. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1217. std::vector<std::string> archs;
  1218. target->GetAppleArchs(config, archs);
  1219. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1220. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1221. sysroot = nullptr;
  1222. }
  1223. std::string sysrootFlagVar =
  1224. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1225. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1226. const char* deploymentTarget =
  1227. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1228. std::string deploymentTargetFlagVar =
  1229. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1230. const char* deploymentTargetFlag =
  1231. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1232. if (!archs.empty() && !lang.empty() &&
  1233. (lang[0] == 'C' || lang[0] == 'F')) {
  1234. for (std::string const& arch : archs) {
  1235. flags += " -arch ";
  1236. flags += arch;
  1237. }
  1238. }
  1239. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1240. flags += " ";
  1241. flags += sysrootFlag;
  1242. flags += " ";
  1243. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1244. }
  1245. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1246. *deploymentTarget) {
  1247. flags += " ";
  1248. flags += deploymentTargetFlag;
  1249. flags += deploymentTarget;
  1250. }
  1251. }
  1252. }
  1253. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1254. cmGeneratorTarget const* target,
  1255. const std::string& lang,
  1256. const std::string& config)
  1257. {
  1258. // Add language-specific flags.
  1259. std::string flagsVar = "CMAKE_";
  1260. flagsVar += lang;
  1261. flagsVar += "_FLAGS";
  1262. this->AddConfigVariableFlags(flags, flagsVar, config);
  1263. if (target->IsIPOEnabled(lang, config)) {
  1264. this->AppendFeatureOptions(flags, lang, "IPO");
  1265. }
  1266. }
  1267. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1268. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1269. const std::string& config)
  1270. {
  1271. if (this->Makefile->IsOn("CMAKE_" + lang +
  1272. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1273. // This toolchain requires use of the language standard flag
  1274. // when linking in order to use the matching standard library.
  1275. // FIXME: If CMake gains an abstraction for standard library
  1276. // selection, this will have to be reconciled with it.
  1277. this->AddCompilerRequirementFlag(flags, target, lang);
  1278. }
  1279. this->AddLanguageFlags(flags, target, lang, config);
  1280. }
  1281. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1282. const std::string& name) const
  1283. {
  1284. GeneratorTargetMap::const_iterator imported =
  1285. this->ImportedGeneratorTargets.find(name);
  1286. if (imported != this->ImportedGeneratorTargets.end()) {
  1287. return imported->second;
  1288. }
  1289. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1290. return t;
  1291. }
  1292. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1293. }
  1294. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1295. const std::string& config,
  1296. std::string& dep)
  1297. {
  1298. // Older CMake code may specify the dependency using the target
  1299. // output file rather than the target name. Such code would have
  1300. // been written before there was support for target properties that
  1301. // modify the name so stripping down to just the file name should
  1302. // produce the target name in this case.
  1303. std::string name = cmSystemTools::GetFilenameName(inName);
  1304. // If the input name is the empty string, there is no real
  1305. // dependency. Short-circuit the other checks:
  1306. if (name.empty()) {
  1307. return false;
  1308. }
  1309. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1310. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1311. }
  1312. // Look for a CMake target with the given name.
  1313. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1314. // make sure it is not just a coincidence that the target name
  1315. // found is part of the inName
  1316. if (cmSystemTools::FileIsFullPath(inName)) {
  1317. std::string tLocation;
  1318. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1319. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1320. tLocation = target->GetLocation(config);
  1321. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1322. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1323. }
  1324. std::string depLocation =
  1325. cmSystemTools::GetFilenamePath(std::string(inName));
  1326. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1327. if (depLocation != tLocation) {
  1328. // it is a full path to a depend that has the same name
  1329. // as a target but is in a different location so do not use
  1330. // the target as the depend
  1331. dep = inName;
  1332. return true;
  1333. }
  1334. }
  1335. switch (target->GetType()) {
  1336. case cmStateEnums::EXECUTABLE:
  1337. case cmStateEnums::STATIC_LIBRARY:
  1338. case cmStateEnums::SHARED_LIBRARY:
  1339. case cmStateEnums::MODULE_LIBRARY:
  1340. case cmStateEnums::UNKNOWN_LIBRARY:
  1341. dep = target->GetLocation(config);
  1342. return true;
  1343. case cmStateEnums::OBJECT_LIBRARY:
  1344. // An object library has no single file on which to depend.
  1345. // This was listed to get the target-level dependency.
  1346. return false;
  1347. case cmStateEnums::INTERFACE_LIBRARY:
  1348. // An interface library has no file on which to depend.
  1349. // This was listed to get the target-level dependency.
  1350. return false;
  1351. case cmStateEnums::UTILITY:
  1352. case cmStateEnums::GLOBAL_TARGET:
  1353. // A utility target has no file on which to depend. This was listed
  1354. // only to get the target-level dependency.
  1355. return false;
  1356. }
  1357. }
  1358. // The name was not that of a CMake target. It must name a file.
  1359. if (cmSystemTools::FileIsFullPath(inName)) {
  1360. // This is a full path. Return it as given.
  1361. dep = inName;
  1362. return true;
  1363. }
  1364. // Check for a source file in this directory that matches the
  1365. // dependency.
  1366. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1367. dep = sf->GetFullPath();
  1368. return true;
  1369. }
  1370. // Treat the name as relative to the source directory in which it
  1371. // was given.
  1372. dep = this->StateSnapshot.GetDirectory().GetCurrentSource();
  1373. dep += "/";
  1374. dep += inName;
  1375. return true;
  1376. }
  1377. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1378. const std::string& lang, bool shared)
  1379. {
  1380. std::string flagsVar;
  1381. // Add flags for dealing with shared libraries for this language.
  1382. if (shared) {
  1383. flagsVar = "CMAKE_SHARED_LIBRARY_";
  1384. flagsVar += lang;
  1385. flagsVar += "_FLAGS";
  1386. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1387. }
  1388. }
  1389. void cmLocalGenerator::AddCompilerRequirementFlag(
  1390. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1391. {
  1392. if (lang.empty()) {
  1393. return;
  1394. }
  1395. const char* defaultStd =
  1396. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1397. if (!defaultStd || !*defaultStd) {
  1398. // This compiler has no notion of language standard levels.
  1399. return;
  1400. }
  1401. std::string extProp = lang + "_EXTENSIONS";
  1402. bool ext = true;
  1403. if (const char* extPropValue = target->GetProperty(extProp)) {
  1404. if (cmSystemTools::IsOff(extPropValue)) {
  1405. ext = false;
  1406. }
  1407. }
  1408. std::string stdProp = lang + "_STANDARD";
  1409. const char* standardProp = target->GetProperty(stdProp);
  1410. if (!standardProp) {
  1411. if (ext) {
  1412. // No language standard is specified and extensions are not disabled.
  1413. // Check if this compiler needs a flag to enable extensions.
  1414. std::string const option_flag =
  1415. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1416. if (const char* opt =
  1417. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1418. std::vector<std::string> optVec;
  1419. cmSystemTools::ExpandListArgument(opt, optVec);
  1420. for (std::string const& i : optVec) {
  1421. this->AppendFlagEscape(flags, i);
  1422. }
  1423. }
  1424. }
  1425. return;
  1426. }
  1427. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1428. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1429. std::string option_flag =
  1430. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1431. const char* opt =
  1432. target->Target->GetMakefile()->GetDefinition(option_flag);
  1433. if (!opt) {
  1434. std::ostringstream e;
  1435. e << "Target \"" << target->GetName()
  1436. << "\" requires the language "
  1437. "dialect \""
  1438. << lang << standardProp << "\" "
  1439. << (ext ? "(with compiler extensions)" : "")
  1440. << ", but CMake "
  1441. "does not know the compile flags to use to enable it.";
  1442. this->IssueMessage(cmake::FATAL_ERROR, e.str());
  1443. } else {
  1444. std::vector<std::string> optVec;
  1445. cmSystemTools::ExpandListArgument(opt, optVec);
  1446. for (std::string const& i : optVec) {
  1447. this->AppendFlagEscape(flags, i);
  1448. }
  1449. }
  1450. return;
  1451. }
  1452. static std::map<std::string, std::vector<std::string>> langStdMap;
  1453. if (langStdMap.empty()) {
  1454. // Maintain sorted order, most recent first.
  1455. langStdMap["CXX"].push_back("20");
  1456. langStdMap["CXX"].push_back("17");
  1457. langStdMap["CXX"].push_back("14");
  1458. langStdMap["CXX"].push_back("11");
  1459. langStdMap["CXX"].push_back("98");
  1460. langStdMap["C"].push_back("11");
  1461. langStdMap["C"].push_back("99");
  1462. langStdMap["C"].push_back("90");
  1463. langStdMap["CUDA"].push_back("14");
  1464. langStdMap["CUDA"].push_back("11");
  1465. langStdMap["CUDA"].push_back("98");
  1466. }
  1467. std::string standard(standardProp);
  1468. std::vector<std::string>& stds = langStdMap[lang];
  1469. std::vector<std::string>::const_iterator stdIt =
  1470. std::find(stds.begin(), stds.end(), standard);
  1471. if (stdIt == stds.end()) {
  1472. std::string e =
  1473. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1474. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1475. cmake::FATAL_ERROR, e, target->GetBacktrace());
  1476. return;
  1477. }
  1478. std::vector<std::string>::const_iterator defaultStdIt =
  1479. std::find(stds.begin(), stds.end(), defaultStd);
  1480. if (defaultStdIt == stds.end()) {
  1481. std::string e = "CMAKE_" + lang +
  1482. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1483. "'";
  1484. this->IssueMessage(cmake::INTERNAL_ERROR, e);
  1485. return;
  1486. }
  1487. // If the standard requested is older than the compiler's default
  1488. // then we need to use a flag to change it. The comparison is
  1489. // greater-or-equal because the standards are stored in backward
  1490. // chronological order.
  1491. if (stdIt >= defaultStdIt) {
  1492. std::string option_flag =
  1493. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1494. const char* opt =
  1495. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1496. std::vector<std::string> optVec;
  1497. cmSystemTools::ExpandListArgument(opt, optVec);
  1498. for (std::string const& i : optVec) {
  1499. this->AppendFlagEscape(flags, i);
  1500. }
  1501. return;
  1502. }
  1503. // The standard requested is at least as new as the compiler's default,
  1504. // and the standard request is not required. Decay to the newest standard
  1505. // for which a flag is defined.
  1506. for (; stdIt < defaultStdIt; ++stdIt) {
  1507. std::string option_flag =
  1508. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1509. if (const char* opt =
  1510. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1511. std::vector<std::string> optVec;
  1512. cmSystemTools::ExpandListArgument(opt, optVec);
  1513. for (std::string const& i : optVec) {
  1514. this->AppendFlagEscape(flags, i);
  1515. }
  1516. return;
  1517. }
  1518. }
  1519. }
  1520. static void AddVisibilityCompileOption(std::string& flags,
  1521. cmGeneratorTarget const* target,
  1522. cmLocalGenerator* lg,
  1523. const std::string& lang,
  1524. std::string* warnCMP0063)
  1525. {
  1526. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1527. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1528. if (!opt) {
  1529. return;
  1530. }
  1531. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1532. const char* prop = target->GetProperty(flagDefine);
  1533. if (!prop) {
  1534. return;
  1535. }
  1536. if (warnCMP0063) {
  1537. *warnCMP0063 += " " + flagDefine + "\n";
  1538. return;
  1539. }
  1540. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1541. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1542. std::ostringstream e;
  1543. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1544. << "\" for " << flagDefine << ".";
  1545. cmSystemTools::Error(e.str().c_str());
  1546. return;
  1547. }
  1548. std::string option = std::string(opt) + prop;
  1549. lg->AppendFlags(flags, option);
  1550. }
  1551. static void AddInlineVisibilityCompileOption(std::string& flags,
  1552. cmGeneratorTarget const* target,
  1553. cmLocalGenerator* lg,
  1554. std::string* warnCMP0063)
  1555. {
  1556. std::string compileOption =
  1557. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1558. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1559. if (!opt) {
  1560. return;
  1561. }
  1562. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1563. if (!prop) {
  1564. return;
  1565. }
  1566. if (warnCMP0063) {
  1567. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1568. return;
  1569. }
  1570. lg->AppendFlags(flags, opt);
  1571. }
  1572. void cmLocalGenerator::AddVisibilityPresetFlags(
  1573. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1574. {
  1575. if (lang.empty()) {
  1576. return;
  1577. }
  1578. std::string warnCMP0063;
  1579. std::string* pWarnCMP0063 = nullptr;
  1580. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1581. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1582. !target->IsExecutableWithExports()) {
  1583. switch (target->GetPolicyStatusCMP0063()) {
  1584. case cmPolicies::OLD:
  1585. return;
  1586. case cmPolicies::WARN:
  1587. pWarnCMP0063 = &warnCMP0063;
  1588. break;
  1589. default:
  1590. break;
  1591. }
  1592. }
  1593. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1594. if (lang == "CXX") {
  1595. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1596. }
  1597. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1598. std::ostringstream w;
  1599. /* clang-format off */
  1600. w <<
  1601. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1602. "Target \"" << target->GetName() << "\" of "
  1603. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1604. "has the following visibility properties set for " << lang << ":\n" <<
  1605. warnCMP0063 <<
  1606. "For compatibility CMake is not honoring them for this target.";
  1607. /* clang-format on */
  1608. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1609. cmake::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1610. }
  1611. }
  1612. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1613. cmGeneratorTarget const* target,
  1614. std::string const& lang,
  1615. const std::string& config)
  1616. {
  1617. int targetType = target->GetType();
  1618. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1619. (targetType == cmStateEnums::MODULE_LIBRARY));
  1620. if (this->GetShouldUseOldFlags(shared, lang)) {
  1621. this->AddSharedFlags(flags, lang, shared);
  1622. } else {
  1623. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1624. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1625. this->AddPositionIndependentFlags(flags, lang, targetType);
  1626. }
  1627. return;
  1628. }
  1629. if (target->GetLinkInterfaceDependentBoolProperty(
  1630. "POSITION_INDEPENDENT_CODE", config)) {
  1631. this->AddPositionIndependentFlags(flags, lang, targetType);
  1632. }
  1633. if (shared) {
  1634. this->AppendFeatureOptions(flags, lang, "DLL");
  1635. }
  1636. }
  1637. }
  1638. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1639. const std::string& lang) const
  1640. {
  1641. std::string originalFlags =
  1642. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1643. if (shared) {
  1644. std::string flagsVar = "CMAKE_SHARED_LIBRARY_";
  1645. flagsVar += lang;
  1646. flagsVar += "_FLAGS";
  1647. const char* flags = this->Makefile->GetSafeDefinition(flagsVar);
  1648. if (flags && flags != originalFlags) {
  1649. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1650. case cmPolicies::WARN: {
  1651. std::ostringstream e;
  1652. e << "Variable " << flagsVar
  1653. << " has been modified. CMake "
  1654. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1655. "shared libraries and will use the "
  1656. << flagsVar
  1657. << " variable "
  1658. "instead. This may cause errors if the original content of "
  1659. << flagsVar << " was removed.\n"
  1660. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1661. this->IssueMessage(cmake::AUTHOR_WARNING, e.str());
  1662. CM_FALLTHROUGH;
  1663. }
  1664. case cmPolicies::OLD:
  1665. return true;
  1666. case cmPolicies::REQUIRED_IF_USED:
  1667. case cmPolicies::REQUIRED_ALWAYS:
  1668. case cmPolicies::NEW:
  1669. return false;
  1670. }
  1671. }
  1672. }
  1673. return false;
  1674. }
  1675. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1676. std::string const& lang,
  1677. int targetType)
  1678. {
  1679. const char* picFlags = nullptr;
  1680. if (targetType == cmStateEnums::EXECUTABLE) {
  1681. std::string flagsVar = "CMAKE_";
  1682. flagsVar += lang;
  1683. flagsVar += "_COMPILE_OPTIONS_PIE";
  1684. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1685. }
  1686. if (!picFlags) {
  1687. std::string flagsVar = "CMAKE_";
  1688. flagsVar += lang;
  1689. flagsVar += "_COMPILE_OPTIONS_PIC";
  1690. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1691. }
  1692. if (picFlags) {
  1693. std::vector<std::string> options;
  1694. cmSystemTools::ExpandListArgument(picFlags, options);
  1695. for (std::string const& o : options) {
  1696. this->AppendFlagEscape(flags, o);
  1697. }
  1698. }
  1699. }
  1700. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1701. const std::string& var,
  1702. const std::string& config)
  1703. {
  1704. // Add the flags from the variable itself.
  1705. std::string flagsVar = var;
  1706. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1707. // Add the flags from the build-type specific variable.
  1708. if (!config.empty()) {
  1709. flagsVar += "_";
  1710. flagsVar += cmSystemTools::UpperCase(config);
  1711. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1712. }
  1713. }
  1714. void cmLocalGenerator::AppendFlags(std::string& flags,
  1715. const std::string& newFlags) const
  1716. {
  1717. if (!newFlags.empty()) {
  1718. if (!flags.empty()) {
  1719. flags += " ";
  1720. }
  1721. flags += newFlags;
  1722. }
  1723. }
  1724. void cmLocalGenerator::AppendFlags(std::string& flags,
  1725. const char* newFlags) const
  1726. {
  1727. if (newFlags && *newFlags) {
  1728. this->AppendFlags(flags, std::string(newFlags));
  1729. }
  1730. }
  1731. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  1732. const std::string& rawFlag) const
  1733. {
  1734. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  1735. }
  1736. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  1737. cmGeneratorTarget* target,
  1738. const std::string& config,
  1739. const std::string& lang)
  1740. {
  1741. if (!target->IsIPOEnabled(lang, config)) {
  1742. return;
  1743. }
  1744. switch (target->GetType()) {
  1745. case cmStateEnums::EXECUTABLE:
  1746. case cmStateEnums::SHARED_LIBRARY:
  1747. case cmStateEnums::MODULE_LIBRARY:
  1748. break;
  1749. default:
  1750. return;
  1751. }
  1752. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  1753. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  1754. if (rawFlagsList == nullptr) {
  1755. return;
  1756. }
  1757. std::vector<std::string> flagsList;
  1758. cmSystemTools::ExpandListArgument(rawFlagsList, flagsList);
  1759. for (std::string const& o : flagsList) {
  1760. this->AppendFlagEscape(flags, o);
  1761. }
  1762. }
  1763. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  1764. const char* options_list,
  1765. const char* regex) const
  1766. {
  1767. // Short-circuit if there are no options.
  1768. if (!options_list) {
  1769. return;
  1770. }
  1771. // Expand the list of options.
  1772. std::vector<std::string> options_vec;
  1773. cmSystemTools::ExpandListArgument(options_list, options_vec);
  1774. this->AppendCompileOptions(options, options_vec, regex);
  1775. }
  1776. void cmLocalGenerator::AppendCompileOptions(
  1777. std::string& options, const std::vector<std::string>& options_vec,
  1778. const char* regex) const
  1779. {
  1780. if (regex != nullptr) {
  1781. // Filter flags upon specified reges.
  1782. cmsys::RegularExpression r(regex);
  1783. for (std::string const& opt : options_vec) {
  1784. if (r.find(opt)) {
  1785. this->AppendFlagEscape(options, opt);
  1786. }
  1787. }
  1788. } else {
  1789. for (std::string const& opt : options_vec) {
  1790. this->AppendFlagEscape(options, opt);
  1791. }
  1792. }
  1793. }
  1794. void cmLocalGenerator::AppendIncludeDirectories(
  1795. std::vector<std::string>& includes, const char* includes_list,
  1796. const cmSourceFile& sourceFile) const
  1797. {
  1798. // Short-circuit if there are no includes.
  1799. if (!includes_list) {
  1800. return;
  1801. }
  1802. // Expand the list of includes.
  1803. std::vector<std::string> includes_vec;
  1804. cmSystemTools::ExpandListArgument(includes_list, includes_vec);
  1805. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  1806. }
  1807. void cmLocalGenerator::AppendIncludeDirectories(
  1808. std::vector<std::string>& includes,
  1809. const std::vector<std::string>& includes_vec,
  1810. const cmSourceFile& sourceFile) const
  1811. {
  1812. std::unordered_set<std::string> uniqueIncludes;
  1813. for (const std::string& include : includes_vec) {
  1814. if (!cmSystemTools::FileIsFullPath(include)) {
  1815. std::ostringstream e;
  1816. e << "Found relative path while evaluating include directories of "
  1817. "\""
  1818. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  1819. << "\"\n";
  1820. this->IssueMessage(cmake::FATAL_ERROR, e.str());
  1821. return;
  1822. }
  1823. std::string inc = include;
  1824. if (!cmSystemTools::IsOff(inc.c_str())) {
  1825. cmSystemTools::ConvertToUnixSlashes(inc);
  1826. }
  1827. if (uniqueIncludes.insert(inc).second) {
  1828. includes.push_back(std::move(inc));
  1829. }
  1830. }
  1831. }
  1832. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  1833. const char* defines_list) const
  1834. {
  1835. // Short-circuit if there are no definitions.
  1836. if (!defines_list) {
  1837. return;
  1838. }
  1839. // Expand the list of definitions.
  1840. std::vector<std::string> defines_vec;
  1841. cmSystemTools::ExpandListArgument(defines_list, defines_vec);
  1842. this->AppendDefines(defines, defines_vec);
  1843. }
  1844. void cmLocalGenerator::AppendDefines(
  1845. std::set<std::string>& defines,
  1846. const std::vector<std::string>& defines_vec) const
  1847. {
  1848. for (std::string const& d : defines_vec) {
  1849. // Skip unsupported definitions.
  1850. if (!this->CheckDefinition(d)) {
  1851. continue;
  1852. }
  1853. defines.insert(d);
  1854. }
  1855. }
  1856. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  1857. std::string& definesString,
  1858. const std::string& lang)
  1859. {
  1860. // Lookup the define flag for the current language.
  1861. std::string dflag = "-D";
  1862. if (!lang.empty()) {
  1863. std::string defineFlagVar = "CMAKE_";
  1864. defineFlagVar += lang;
  1865. defineFlagVar += "_DEFINE_FLAG";
  1866. const char* df = this->Makefile->GetDefinition(defineFlagVar);
  1867. if (df && *df) {
  1868. dflag = df;
  1869. }
  1870. }
  1871. std::set<std::string>::const_iterator defineIt = defines.begin();
  1872. const std::set<std::string>::const_iterator defineEnd = defines.end();
  1873. const char* itemSeparator = definesString.empty() ? "" : " ";
  1874. for (; defineIt != defineEnd; ++defineIt) {
  1875. // Append the definition with proper escaping.
  1876. std::string def = dflag;
  1877. if (this->GetState()->UseWatcomWMake()) {
  1878. // The Watcom compiler does its own command line parsing instead
  1879. // of using the windows shell rules. Definitions are one of
  1880. // -DNAME
  1881. // -DNAME=<cpp-token>
  1882. // -DNAME="c-string with spaces and other characters(?@#$)"
  1883. //
  1884. // Watcom will properly parse each of these cases from the
  1885. // command line without any escapes. However we still have to
  1886. // get the '$' and '#' characters through WMake as '$$' and
  1887. // '$#'.
  1888. for (const char* c = defineIt->c_str(); *c; ++c) {
  1889. if (*c == '$' || *c == '#') {
  1890. def += '$';
  1891. }
  1892. def += *c;
  1893. }
  1894. } else {
  1895. // Make the definition appear properly on the command line. Use
  1896. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  1897. std::string::size_type eq = defineIt->find("=");
  1898. def += defineIt->substr(0, eq);
  1899. if (eq != std::string::npos) {
  1900. def += "=";
  1901. def += this->EscapeForShell(defineIt->c_str() + eq + 1, true);
  1902. }
  1903. }
  1904. definesString += itemSeparator;
  1905. itemSeparator = " ";
  1906. definesString += def;
  1907. }
  1908. }
  1909. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  1910. const std::string& lang,
  1911. const char* feature)
  1912. {
  1913. std::string optVar = "CMAKE_";
  1914. optVar += lang;
  1915. optVar += "_COMPILE_OPTIONS_";
  1916. optVar += feature;
  1917. if (const char* optionList = this->Makefile->GetDefinition(optVar)) {
  1918. std::vector<std::string> options;
  1919. cmSystemTools::ExpandListArgument(optionList, options);
  1920. for (std::string const& o : options) {
  1921. this->AppendFlagEscape(flags, o);
  1922. }
  1923. }
  1924. }
  1925. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  1926. const std::string& config)
  1927. {
  1928. std::string featureName = feature;
  1929. // TODO: Define accumulation policy for features (prepend, append, replace).
  1930. // Currently we always replace.
  1931. if (!config.empty()) {
  1932. featureName += "_";
  1933. featureName += cmSystemTools::UpperCase(config);
  1934. }
  1935. cmStateSnapshot snp = this->StateSnapshot;
  1936. while (snp.IsValid()) {
  1937. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  1938. return value;
  1939. }
  1940. snp = snp.GetBuildsystemDirectoryParent();
  1941. }
  1942. return nullptr;
  1943. }
  1944. std::string cmLocalGenerator::GetProjectName() const
  1945. {
  1946. return this->StateSnapshot.GetProjectName();
  1947. }
  1948. std::string cmLocalGenerator::ConstructComment(
  1949. cmCustomCommandGenerator const& ccg, const char* default_comment)
  1950. {
  1951. // Check for a comment provided with the command.
  1952. if (ccg.GetComment()) {
  1953. return ccg.GetComment();
  1954. }
  1955. // Construct a reasonable default comment if possible.
  1956. if (!ccg.GetOutputs().empty()) {
  1957. std::string comment;
  1958. comment = "Generating ";
  1959. const char* sep = "";
  1960. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  1961. for (std::string const& o : ccg.GetOutputs()) {
  1962. comment += sep;
  1963. comment += this->ConvertToRelativePath(currentBinaryDir, o);
  1964. sep = ", ";
  1965. }
  1966. return comment;
  1967. }
  1968. // Otherwise use the provided default.
  1969. return default_comment;
  1970. }
  1971. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  1972. {
  1973. public:
  1974. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  1975. const char* dest, bool implib)
  1976. : cmInstallTargetGenerator(
  1977. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  1978. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  1979. false)
  1980. {
  1981. this->Compute(lg);
  1982. }
  1983. };
  1984. void cmLocalGenerator::GenerateTargetInstallRules(
  1985. std::ostream& os, const std::string& config,
  1986. std::vector<std::string> const& configurationTypes)
  1987. {
  1988. // Convert the old-style install specification from each target to
  1989. // an install generator and run it.
  1990. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  1991. for (cmGeneratorTarget* l : tgts) {
  1992. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1993. continue;
  1994. }
  1995. // Include the user-specified pre-install script for this target.
  1996. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  1997. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  1998. g.Generate(os, config, configurationTypes);
  1999. }
  2000. // Install this target if a destination is given.
  2001. if (!l->Target->GetInstallPath().empty()) {
  2002. // Compute the full install destination. Note that converting
  2003. // to unix slashes also removes any trailing slash.
  2004. // We also skip over the leading slash given by the user.
  2005. std::string destination = l->Target->GetInstallPath().substr(1);
  2006. cmSystemTools::ConvertToUnixSlashes(destination);
  2007. if (destination.empty()) {
  2008. destination = ".";
  2009. }
  2010. // Generate the proper install generator for this target type.
  2011. switch (l->GetType()) {
  2012. case cmStateEnums::EXECUTABLE:
  2013. case cmStateEnums::STATIC_LIBRARY:
  2014. case cmStateEnums::MODULE_LIBRARY: {
  2015. // Use a target install generator.
  2016. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2017. destination.c_str(), false);
  2018. g.Generate(os, config, configurationTypes);
  2019. } break;
  2020. case cmStateEnums::SHARED_LIBRARY: {
  2021. #if defined(_WIN32) || defined(__CYGWIN__)
  2022. // Special code to handle DLL. Install the import library
  2023. // to the normal destination and the DLL to the runtime
  2024. // destination.
  2025. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2026. destination.c_str(), true);
  2027. g1.Generate(os, config, configurationTypes);
  2028. // We also skip over the leading slash given by the user.
  2029. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2030. cmSystemTools::ConvertToUnixSlashes(destination);
  2031. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2032. destination.c_str(), false);
  2033. g2.Generate(os, config, configurationTypes);
  2034. #else
  2035. // Use a target install generator.
  2036. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2037. destination.c_str(), false);
  2038. g.Generate(os, config, configurationTypes);
  2039. #endif
  2040. } break;
  2041. default:
  2042. break;
  2043. }
  2044. }
  2045. // Include the user-specified post-install script for this target.
  2046. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2047. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2048. g.Generate(os, config, configurationTypes);
  2049. }
  2050. }
  2051. }
  2052. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2053. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2054. std::string::size_type max_len)
  2055. {
  2056. // Replace the beginning of the path portion of the object name with
  2057. // its own md5 sum.
  2058. std::string::size_type pos =
  2059. objName.find('/', objName.size() - max_len + 32);
  2060. if (pos != std::string::npos) {
  2061. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2062. std::string md5name = md5.HashString(objName.substr(0, pos));
  2063. md5name += objName.substr(pos);
  2064. objName = md5name;
  2065. // The object name is now short enough.
  2066. return true;
  2067. }
  2068. // The object name could not be shortened enough.
  2069. return false;
  2070. }
  2071. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2072. std::string::size_type dir_len,
  2073. std::string::size_type max_total_len)
  2074. {
  2075. // Enforce the maximum file name length if possible.
  2076. std::string::size_type max_obj_len = max_total_len;
  2077. if (dir_len < max_total_len) {
  2078. max_obj_len = max_total_len - dir_len;
  2079. if (objName.size() > max_obj_len) {
  2080. // The current object file name is too long. Try to shorten it.
  2081. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2082. }
  2083. // The object file name is short enough.
  2084. return true;
  2085. }
  2086. // The build directory in which the object will be stored is
  2087. // already too deep.
  2088. return false;
  2089. }
  2090. #endif
  2091. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2092. const std::string& sin, std::string const& dir_max)
  2093. {
  2094. // Look for an existing mapped name for this object file.
  2095. std::map<std::string, std::string>::iterator it =
  2096. this->UniqueObjectNamesMap.find(sin);
  2097. // If no entry exists create one.
  2098. if (it == this->UniqueObjectNamesMap.end()) {
  2099. // Start with the original name.
  2100. std::string ssin = sin;
  2101. // Avoid full paths by removing leading slashes.
  2102. ssin.erase(0, ssin.find_first_not_of('/'));
  2103. // Avoid full paths by removing colons.
  2104. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2105. // Avoid relative paths that go up the tree.
  2106. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2107. // Avoid spaces.
  2108. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2109. // Mangle the name if necessary.
  2110. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2111. bool done;
  2112. int cc = 0;
  2113. char rpstr[100];
  2114. sprintf(rpstr, "_p_");
  2115. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2116. std::string sssin = sin;
  2117. do {
  2118. done = true;
  2119. for (it = this->UniqueObjectNamesMap.begin();
  2120. it != this->UniqueObjectNamesMap.end(); ++it) {
  2121. if (it->second == ssin) {
  2122. done = false;
  2123. }
  2124. }
  2125. if (done) {
  2126. break;
  2127. }
  2128. sssin = ssin;
  2129. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2130. sprintf(rpstr, "_p%d_", cc++);
  2131. } while (!done);
  2132. }
  2133. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2134. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2135. this->ObjectPathMax)) {
  2136. // Warn if this is the first time the path has been seen.
  2137. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2138. std::ostringstream m;
  2139. /* clang-format off */
  2140. m << "The object file directory\n"
  2141. << " " << dir_max << "\n"
  2142. << "has " << dir_max.size() << " characters. "
  2143. << "The maximum full path to an object file is "
  2144. << this->ObjectPathMax << " characters "
  2145. << "(see CMAKE_OBJECT_PATH_MAX). "
  2146. << "Object file\n"
  2147. << " " << ssin << "\n"
  2148. << "cannot be safely placed under this directory. "
  2149. << "The build may not work correctly.";
  2150. /* clang-format on */
  2151. this->IssueMessage(cmake::WARNING, m.str());
  2152. }
  2153. }
  2154. #else
  2155. (void)dir_max;
  2156. #endif
  2157. // Insert the newly mapped object file name.
  2158. std::map<std::string, std::string>::value_type e(sin, ssin);
  2159. it = this->UniqueObjectNamesMap.insert(e).first;
  2160. }
  2161. // Return the map entry.
  2162. return it->second;
  2163. }
  2164. void cmLocalGenerator::ComputeObjectFilenames(
  2165. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2166. cmGeneratorTarget const* /*unused*/)
  2167. {
  2168. }
  2169. bool cmLocalGenerator::IsWindowsShell() const
  2170. {
  2171. return this->GetState()->UseWindowsShell();
  2172. }
  2173. bool cmLocalGenerator::IsWatcomWMake() const
  2174. {
  2175. return this->GetState()->UseWatcomWMake();
  2176. }
  2177. bool cmLocalGenerator::IsMinGWMake() const
  2178. {
  2179. return this->GetState()->UseMinGWMake();
  2180. }
  2181. bool cmLocalGenerator::IsNMake() const
  2182. {
  2183. return this->GetState()->UseNMake();
  2184. }
  2185. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2186. const cmSourceFile& source, std::string const& dir_max,
  2187. bool* hasSourceExtension, char const* customOutputExtension)
  2188. {
  2189. // Construct the object file name using the full path to the source
  2190. // file which is its only unique identification.
  2191. std::string const& fullPath = source.GetFullPath();
  2192. // Try referencing the source relative to the source tree.
  2193. std::string relFromSource =
  2194. this->ConvertToRelativePath(this->GetCurrentSourceDirectory(), fullPath);
  2195. assert(!relFromSource.empty());
  2196. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2197. bool subSource = relSource && relFromSource[0] != '.';
  2198. // Try referencing the source relative to the binary tree.
  2199. std::string relFromBinary =
  2200. this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), fullPath);
  2201. assert(!relFromBinary.empty());
  2202. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2203. bool subBinary = relBinary && relFromBinary[0] != '.';
  2204. // Select a nice-looking reference to the source file to construct
  2205. // the object file name.
  2206. std::string objectName;
  2207. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2208. objectName = relFromSource;
  2209. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2210. objectName = relFromBinary;
  2211. } else if (relFromBinary.length() < relFromSource.length()) {
  2212. objectName = relFromBinary;
  2213. } else {
  2214. objectName = relFromSource;
  2215. }
  2216. // if it is still a full path check for the try compile case
  2217. // try compile never have in source sources, and should not
  2218. // have conflicting source file names in the same target
  2219. if (cmSystemTools::FileIsFullPath(objectName)) {
  2220. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2221. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2222. }
  2223. }
  2224. // Replace the original source file extension with the object file
  2225. // extension.
  2226. bool keptSourceExtension = true;
  2227. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2228. // Decide whether this language wants to replace the source
  2229. // extension with the object extension. For CMake 2.4
  2230. // compatibility do this by default.
  2231. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2232. if (!replaceExt) {
  2233. std::string lang = source.GetLanguage();
  2234. if (!lang.empty()) {
  2235. std::string repVar = "CMAKE_";
  2236. repVar += lang;
  2237. repVar += "_OUTPUT_EXTENSION_REPLACE";
  2238. replaceExt = this->Makefile->IsOn(repVar);
  2239. }
  2240. }
  2241. // Remove the source extension if it is to be replaced.
  2242. if (replaceExt || customOutputExtension) {
  2243. keptSourceExtension = false;
  2244. std::string::size_type dot_pos = objectName.rfind('.');
  2245. if (dot_pos != std::string::npos) {
  2246. objectName = objectName.substr(0, dot_pos);
  2247. }
  2248. }
  2249. // Store the new extension.
  2250. if (customOutputExtension) {
  2251. objectName += customOutputExtension;
  2252. } else {
  2253. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2254. }
  2255. }
  2256. if (hasSourceExtension) {
  2257. *hasSourceExtension = keptSourceExtension;
  2258. }
  2259. // Convert to a safe name.
  2260. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2261. }
  2262. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2263. {
  2264. return source.GetLanguage();
  2265. }
  2266. cmake* cmLocalGenerator::GetCMakeInstance() const
  2267. {
  2268. return this->GlobalGenerator->GetCMakeInstance();
  2269. }
  2270. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2271. {
  2272. return this->GetCMakeInstance()->GetHomeDirectory();
  2273. }
  2274. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2275. {
  2276. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2277. }
  2278. const char* cmLocalGenerator::GetCurrentBinaryDirectory() const
  2279. {
  2280. return this->StateSnapshot.GetDirectory().GetCurrentBinary().c_str();
  2281. }
  2282. const char* cmLocalGenerator::GetCurrentSourceDirectory() const
  2283. {
  2284. return this->StateSnapshot.GetDirectory().GetCurrentSource().c_str();
  2285. }
  2286. std::string cmLocalGenerator::GetTargetDirectory(
  2287. const cmGeneratorTarget* /*unused*/) const
  2288. {
  2289. cmSystemTools::Error("GetTargetDirectory"
  2290. " called on cmLocalGenerator");
  2291. return "";
  2292. }
  2293. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2294. {
  2295. // The computed version may change until the project is fully
  2296. // configured.
  2297. if (!this->BackwardsCompatibilityFinal) {
  2298. unsigned int major = 0;
  2299. unsigned int minor = 0;
  2300. unsigned int patch = 0;
  2301. if (const char* value =
  2302. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2303. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2304. case 2:
  2305. patch = 0;
  2306. break;
  2307. case 1:
  2308. minor = 0;
  2309. patch = 0;
  2310. break;
  2311. default:
  2312. break;
  2313. }
  2314. }
  2315. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2316. this->BackwardsCompatibilityFinal = true;
  2317. }
  2318. return this->BackwardsCompatibility;
  2319. }
  2320. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2321. {
  2322. // Check the policy to decide whether to pay attention to this
  2323. // variable.
  2324. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2325. case cmPolicies::WARN:
  2326. // WARN is just OLD without warning because user code does not
  2327. // always affect whether this check is done.
  2328. case cmPolicies::OLD:
  2329. // Old behavior is to check the variable.
  2330. break;
  2331. case cmPolicies::NEW:
  2332. // New behavior is to ignore the variable.
  2333. return false;
  2334. case cmPolicies::REQUIRED_IF_USED:
  2335. case cmPolicies::REQUIRED_ALWAYS:
  2336. // This will never be the case because the only way to require
  2337. // the setting is to require the user to specify version policy
  2338. // 2.6 or higher. Once we add that requirement then this whole
  2339. // method can be removed anyway.
  2340. return false;
  2341. }
  2342. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2343. // equal to or lower than the given version.
  2344. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2345. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2346. }
  2347. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2348. cmPolicies::PolicyID id) const
  2349. {
  2350. return this->Makefile->GetPolicyStatus(id);
  2351. }
  2352. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2353. {
  2354. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2355. std::string::size_type pos = define.find_first_of("(=");
  2356. if (pos != std::string::npos) {
  2357. if (define[pos] == '(') {
  2358. std::ostringstream e;
  2359. /* clang-format off */
  2360. e << "WARNING: Function-style preprocessor definitions may not be "
  2361. << "passed on the compiler command line because many compilers "
  2362. << "do not support it.\n"
  2363. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2364. << "Consider defining the macro in a (configured) header file.\n";
  2365. /* clang-format on */
  2366. cmSystemTools::Message(e.str().c_str());
  2367. return false;
  2368. }
  2369. }
  2370. // Many compilers do not support # in the value so we disable it.
  2371. if (define.find_first_of('#') != std::string::npos) {
  2372. std::ostringstream e;
  2373. /* clang-format off */
  2374. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2375. << "passed on the compiler command line because many compilers "
  2376. << "do not support it.\n"
  2377. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2378. << "Consider defining the macro in a (configured) header file.\n";
  2379. /* clang-format on */
  2380. cmSystemTools::Message(e.str().c_str());
  2381. return false;
  2382. }
  2383. // Assume it is supported.
  2384. return true;
  2385. }
  2386. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2387. const std::string& prop)
  2388. {
  2389. if (const char* val = target->GetProperty(prop)) {
  2390. mf->AddDefinition(prop, val);
  2391. }
  2392. }
  2393. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2394. const std::string& targetName,
  2395. const char* fname)
  2396. {
  2397. // Find the Info.plist template.
  2398. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2399. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2400. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2401. std::string inMod = this->Makefile->GetModulesFile(inFile.c_str());
  2402. if (!inMod.empty()) {
  2403. inFile = inMod;
  2404. }
  2405. }
  2406. if (!cmSystemTools::FileExists(inFile, true)) {
  2407. std::ostringstream e;
  2408. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2409. << "\" could not be found.";
  2410. cmSystemTools::Error(e.str().c_str());
  2411. return;
  2412. }
  2413. // Convert target properties to variables in an isolated makefile
  2414. // scope to configure the file. If properties are set they will
  2415. // override user make variables. If not the configuration will fall
  2416. // back to the directory-level values set by the user.
  2417. cmMakefile* mf = this->Makefile;
  2418. cmMakefile::ScopePushPop varScope(mf);
  2419. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName.c_str());
  2420. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2421. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2422. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2423. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2424. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2425. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2426. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2427. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2428. mf->ConfigureFile(inFile.c_str(), fname, false, false, false);
  2429. }
  2430. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2431. cmGeneratorTarget* target, const std::string& targetName, const char* fname)
  2432. {
  2433. // Find the Info.plist template.
  2434. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2435. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2436. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2437. std::string inMod = this->Makefile->GetModulesFile(inFile.c_str());
  2438. if (!inMod.empty()) {
  2439. inFile = inMod;
  2440. }
  2441. }
  2442. if (!cmSystemTools::FileExists(inFile, true)) {
  2443. std::ostringstream e;
  2444. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2445. << "\" could not be found.";
  2446. cmSystemTools::Error(e.str().c_str());
  2447. return;
  2448. }
  2449. // Convert target properties to variables in an isolated makefile
  2450. // scope to configure the file. If properties are set they will
  2451. // override user make variables. If not the configuration will fall
  2452. // back to the directory-level values set by the user.
  2453. cmMakefile* mf = this->Makefile;
  2454. cmMakefile::ScopePushPop varScope(mf);
  2455. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName.c_str());
  2456. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  2457. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  2458. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  2459. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  2460. mf->ConfigureFile(inFile.c_str(), fname, false, false, false);
  2461. }