cmLocalGenerator.cxx 89 KB

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