cmLocalGenerator.cxx 91 KB

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