cmComputeLinkInformation.cxx 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  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 "cmComputeLinkInformation.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmComputeLinkDepends.h"
  6. #include "cmGeneratorTarget.h"
  7. #include "cmGlobalGenerator.h"
  8. #include "cmLocalGenerator.h"
  9. #include "cmMakefile.h"
  10. #include "cmMessageType.h"
  11. #include "cmOrderDirectories.h"
  12. #include "cmOutputConverter.h"
  13. #include "cmPolicies.h"
  14. #include "cmState.h"
  15. #include "cmStateTypes.h"
  16. #include "cmStringAlgorithms.h"
  17. #include "cmSystemTools.h"
  18. #include "cmTarget.h"
  19. #include "cmake.h"
  20. #include <algorithm>
  21. #include <ctype.h>
  22. #include <sstream>
  23. #include <string.h>
  24. #include <utility>
  25. //#define CM_COMPUTE_LINK_INFO_DEBUG
  26. /*
  27. Notes about linking on various platforms:
  28. ------------------------------------------------------------------------------
  29. Linux, FreeBSD, macOS, Sun, Windows:
  30. Linking to libraries using the full path works fine.
  31. ------------------------------------------------------------------------------
  32. On AIX, more work is needed.
  33. The "-bnoipath" option is needed. From "man ld":
  34. Note: If you specify a shared object, or an archive file
  35. containing a shared object, with an absolute or relative path
  36. name, instead of with the -lName flag, the path name is
  37. included in the import file ID string in the loader section of
  38. the output file. You can override this behavior with the
  39. -bnoipath option.
  40. noipath
  41. For shared objects listed on the command-line, rather than
  42. specified with the -l flag, use a null path component when
  43. listing the shared object in the loader section of the
  44. output file. A null path component is always used for
  45. shared objects specified with the -l flag. This option
  46. does not affect the specification of a path component by
  47. using a line beginning with #! in an import file. The
  48. default is the ipath option.
  49. This prevents the full path specified on the compile line from being
  50. compiled directly into the binary.
  51. By default the linker places -L paths in the embedded runtime path.
  52. In order to implement CMake's RPATH interface correctly, we need the
  53. -blibpath:Path option. From "man ld":
  54. libpath:Path
  55. Uses Path as the library path when writing the loader section
  56. of the output file. Path is neither checked for validity nor
  57. used when searching for libraries specified by the -l flag.
  58. Path overrides any library paths generated when the -L flag is
  59. used.
  60. If you do not specify any -L flags, or if you specify the
  61. nolibpath option, the default library path information is
  62. written in the loader section of the output file. The default
  63. library path information is the value of the LIBPATH
  64. environment variable if it is defined, and /usr/lib:/lib,
  65. otherwise.
  66. We can pass -Wl,-blibpath:/usr/lib:/lib always to avoid the -L stuff
  67. and not break when the user sets LIBPATH. Then if we want to add an
  68. rpath we insert it into the option before /usr/lib.
  69. ------------------------------------------------------------------------------
  70. On HP-UX, more work is needed. There are differences between
  71. versions.
  72. ld: 92453-07 linker linker ld B.10.33 990520
  73. Linking with a full path works okay for static and shared libraries.
  74. The linker seems to always put the full path to where the library
  75. was found in the binary whether using a full path or -lfoo syntax.
  76. Transitive link dependencies work just fine due to the full paths.
  77. It has the "-l:libfoo.sl" option. The +nodefaultrpath is accepted
  78. but not documented and does not seem to do anything. There is no
  79. +forceload option.
  80. ld: 92453-07 linker ld HP Itanium(R) B.12.41 IPF/IPF
  81. Linking with a full path works okay for static libraries.
  82. Linking with a full path works okay for shared libraries. However
  83. dependent (transitive) libraries of those linked directly must be
  84. either found with an rpath stored in the direct dependencies or
  85. found in -L paths as if they were specified with "-l:libfoo.sl"
  86. (really "-l:<soname>"). The search matches that of the dynamic
  87. loader but only with -L paths. In other words, if we have an
  88. executable that links to shared library bar which links to shared
  89. library foo, the link line for the exe must contain
  90. /dir/with/bar/libbar.sl -L/dir/with/foo
  91. It does not matter whether the exe wants to link to foo directly or
  92. whether /dir/with/foo/libfoo.sl is listed. The -L path must still
  93. be present. It should match the runtime path computed for the
  94. executable taking all directly and transitively linked libraries
  95. into account.
  96. The "+nodefaultrpath" option should be used to avoid getting -L
  97. paths in the rpath unless we add our own rpath with +b. This means
  98. that skip-build-rpath should use this option.
  99. See documentation in "man ld", "man dld.so", and
  100. http://docs.hp.com/en/B2355-90968/creatingandusinglibraries.htm
  101. +[no]defaultrpath
  102. +defaultrpath is the default. Include any paths that are
  103. specified with -L in the embedded path, unless you specify the
  104. +b option. If you use +b, only the path list specified by +b is
  105. in the embedded path.
  106. The +nodefaultrpath option removes all library paths that were
  107. specified with the -L option from the embedded path. The linker
  108. searches the library paths specified by the -L option at link
  109. time. At run time, the only library paths searched are those
  110. specified by the environment variables LD_LIBRARY_PATH and
  111. SHLIB_PATH, library paths specified by the +b linker option, and
  112. finally the default library paths.
  113. +rpathfirst
  114. This option will cause the paths specified in RPATH (embedded
  115. path) to be used before the paths specified in LD_LIBRARY_PATH
  116. or SHLIB_PATH, in searching for shared libraries. This changes
  117. the default search order of LD_LIBRARY_PATH, SHLIB_PATH, and
  118. RPATH (embedded path).
  119. ------------------------------------------------------------------------------
  120. Notes about dependent (transitive) shared libraries:
  121. On non-Windows systems shared libraries may have transitive
  122. dependencies. In order to support LINK_INTERFACE_LIBRARIES we must
  123. support linking to a shared library without listing all the libraries
  124. to which it links. Some linkers want to be able to find the
  125. transitive dependencies (dependent libraries) of shared libraries
  126. listed on the command line.
  127. - On Windows, DLLs are not directly linked, and the import libraries
  128. have no transitive dependencies.
  129. - On Mac OS X 10.5 and above transitive dependencies are not needed.
  130. - On Mac OS X 10.4 and below we need to actually list the dependencies.
  131. Otherwise when using -isysroot for universal binaries it cannot
  132. find the dependent libraries. Listing them on the command line
  133. tells the linker where to find them, but unfortunately also links
  134. the library.
  135. - On HP-UX, the linker wants to find the transitive dependencies of
  136. shared libraries in the -L paths even if the dependent libraries
  137. are given on the link line.
  138. - On AIX the transitive dependencies are not needed.
  139. - On SGI, the linker wants to find the transitive dependencies of
  140. shared libraries in the -L paths if they are not given on the link
  141. line. Transitive linking can be disabled using the options
  142. -no_transitive_link -Wl,-no_transitive_link
  143. which disable it. Both options must be given when invoking the
  144. linker through the compiler.
  145. - On Sun, the linker wants to find the transitive dependencies of
  146. shared libraries in the -L paths if they are not given on the link
  147. line.
  148. - On Linux, FreeBSD, and QNX:
  149. The linker wants to find the transitive dependencies of shared
  150. libraries in the "-rpath-link" paths option if they have not been
  151. given on the link line. The option is like rpath but just for
  152. link time:
  153. -Wl,-rpath-link,"/path1:/path2"
  154. For -rpath-link, we need a separate runtime path ordering pass
  155. including just the dependent libraries that are not linked.
  156. For -L paths on non-HP, we can do the same thing as with rpath-link
  157. but put the results in -L paths. The paths should be listed at the
  158. end to avoid conflicting with user search paths (?).
  159. For -L paths on HP, we should do a runtime path ordering pass with
  160. all libraries, both linked and non-linked. Even dependent
  161. libraries that are also linked need to be listed in -L paths.
  162. In our implementation we add all dependent libraries to the runtime
  163. path computation. Then the auto-generated RPATH will find everything.
  164. ------------------------------------------------------------------------------
  165. Notes about shared libraries with not builtin soname:
  166. Some UNIX shared libraries may be created with no builtin soname. On
  167. some platforms such libraries cannot be linked using the path to their
  168. location because the linker will copy the path into the field used to
  169. find the library at runtime.
  170. Apple: ../libfoo.dylib ==> libfoo.dylib # ok, uses install_name
  171. SGI: ../libfoo.so ==> libfoo.so # ok
  172. AIX: ../libfoo.so ==> libfoo.so # ok
  173. Linux: ../libfoo.so ==> ../libfoo.so # bad
  174. HP-UX: ../libfoo.so ==> ../libfoo.so # bad
  175. Sun: ../libfoo.so ==> ../libfoo.so # bad
  176. FreeBSD: ../libfoo.so ==> ../libfoo.so # bad
  177. In order to link these libraries we need to use the old-style split
  178. into -L.. and -lfoo options. This should be fairly safe because most
  179. problems with -lfoo options were related to selecting shared libraries
  180. instead of static but in this case we want the shared lib. Link
  181. directory ordering needs to be done to make sure these shared
  182. libraries are found first. There should be very few restrictions
  183. because this need be done only for shared libraries without soname-s.
  184. */
  185. cmComputeLinkInformation::cmComputeLinkInformation(
  186. const cmGeneratorTarget* target, const std::string& config)
  187. // Store context information.
  188. : Target(target)
  189. , Makefile(target->Target->GetMakefile())
  190. , GlobalGenerator(target->GetLocalGenerator()->GetGlobalGenerator())
  191. , CMakeInstance(this->GlobalGenerator->GetCMakeInstance())
  192. // The configuration being linked.
  193. , Config(config)
  194. {
  195. // Check whether to recognize OpenBSD-style library versioned names.
  196. this->OpenBSD = this->Makefile->GetState()->GetGlobalPropertyAsBool(
  197. "FIND_LIBRARY_USE_OPENBSD_VERSIONING");
  198. // Allocate internals.
  199. this->OrderLinkerSearchPath = new cmOrderDirectories(
  200. this->GlobalGenerator, target, "linker search path");
  201. this->OrderRuntimeSearchPath = new cmOrderDirectories(
  202. this->GlobalGenerator, target, "runtime search path");
  203. this->OrderDependentRPath = nullptr;
  204. // Get the language used for linking this target.
  205. this->LinkLanguage = this->Target->GetLinkerLanguage(config);
  206. if (this->LinkLanguage.empty()) {
  207. // The Compute method will do nothing, so skip the rest of the
  208. // initialization.
  209. return;
  210. }
  211. // Check whether we should skip dependencies on shared library files.
  212. this->LinkDependsNoShared =
  213. this->Target->GetPropertyAsBool("LINK_DEPENDS_NO_SHARED");
  214. // On platforms without import libraries there may be a special flag
  215. // to use when creating a plugin (module) that obtains symbols from
  216. // the program that will load it.
  217. this->LoaderFlag = nullptr;
  218. if (!this->Target->IsDLLPlatform() &&
  219. this->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
  220. std::string loader_flag_var =
  221. cmStrCat("CMAKE_SHARED_MODULE_LOADER_", this->LinkLanguage, "_FLAG");
  222. this->LoaderFlag = this->Makefile->GetDefinition(loader_flag_var);
  223. }
  224. // Get options needed to link libraries.
  225. if (const char* flag = this->Makefile->GetDefinition(
  226. "CMAKE_" + this->LinkLanguage + "_LINK_LIBRARY_FLAG")) {
  227. this->LibLinkFlag = flag;
  228. } else {
  229. this->LibLinkFlag =
  230. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FLAG");
  231. }
  232. if (const char* flag = this->Makefile->GetDefinition(
  233. "CMAKE_" + this->LinkLanguage + "_LINK_LIBRARY_FILE_FLAG")) {
  234. this->LibLinkFileFlag = flag;
  235. } else {
  236. this->LibLinkFileFlag =
  237. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FILE_FLAG");
  238. }
  239. if (const char* suffix = this->Makefile->GetDefinition(
  240. "CMAKE_" + this->LinkLanguage + "_LINK_LIBRARY_SUFFIX")) {
  241. this->LibLinkSuffix = suffix;
  242. } else {
  243. this->LibLinkSuffix =
  244. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_SUFFIX");
  245. }
  246. // Get options needed to specify RPATHs.
  247. this->RuntimeUseChrpath = false;
  248. if (this->Target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  249. const char* tType = ((this->Target->GetType() == cmStateEnums::EXECUTABLE)
  250. ? "EXECUTABLE"
  251. : "SHARED_LIBRARY");
  252. std::string rtVar =
  253. cmStrCat("CMAKE_", tType, "_RUNTIME_", this->LinkLanguage, "_FLAG");
  254. std::string rtSepVar = rtVar + "_SEP";
  255. this->RuntimeFlag = this->Makefile->GetSafeDefinition(rtVar);
  256. this->RuntimeSep = this->Makefile->GetSafeDefinition(rtSepVar);
  257. this->RuntimeAlways = (this->Makefile->GetSafeDefinition(
  258. "CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH"));
  259. this->RuntimeUseChrpath = this->Target->IsChrpathUsed(config);
  260. // Get options needed to help find dependent libraries.
  261. std::string rlVar =
  262. cmStrCat("CMAKE_", tType, "_RPATH_LINK_", this->LinkLanguage, "_FLAG");
  263. this->RPathLinkFlag = this->Makefile->GetSafeDefinition(rlVar);
  264. }
  265. // Check if we need to include the runtime search path at link time.
  266. {
  267. std::string var = cmStrCat("CMAKE_SHARED_LIBRARY_LINK_",
  268. this->LinkLanguage, "_WITH_RUNTIME_PATH");
  269. this->LinkWithRuntimePath = this->Makefile->IsOn(var);
  270. }
  271. // Check the platform policy for missing soname case.
  272. this->NoSONameUsesPath =
  273. this->Makefile->IsOn("CMAKE_PLATFORM_USES_PATH_WHEN_NO_SONAME");
  274. // Get link type information.
  275. this->ComputeLinkTypeInfo();
  276. // Setup the link item parser.
  277. this->ComputeItemParserInfo();
  278. // Setup framework support.
  279. this->ComputeFrameworkInfo();
  280. // Choose a mode for dealing with shared library dependencies.
  281. this->SharedDependencyMode = SharedDepModeNone;
  282. if (this->Makefile->IsOn("CMAKE_LINK_DEPENDENT_LIBRARY_FILES")) {
  283. this->SharedDependencyMode = SharedDepModeLink;
  284. } else if (this->Makefile->IsOn("CMAKE_LINK_DEPENDENT_LIBRARY_DIRS")) {
  285. this->SharedDependencyMode = SharedDepModeLibDir;
  286. } else if (!this->RPathLinkFlag.empty()) {
  287. this->SharedDependencyMode = SharedDepModeDir;
  288. this->OrderDependentRPath = new cmOrderDirectories(
  289. this->GlobalGenerator, target, "dependent library path");
  290. }
  291. // Add the search path entries requested by the user to path ordering.
  292. std::vector<std::string> directories;
  293. this->Target->GetLinkDirectories(directories, config, this->LinkLanguage);
  294. this->OrderLinkerSearchPath->AddUserDirectories(directories);
  295. this->OrderRuntimeSearchPath->AddUserDirectories(directories);
  296. // Set up the implicit link directories.
  297. this->LoadImplicitLinkInfo();
  298. this->OrderLinkerSearchPath->SetImplicitDirectories(this->ImplicitLinkDirs);
  299. this->OrderRuntimeSearchPath->SetImplicitDirectories(this->ImplicitLinkDirs);
  300. if (this->OrderDependentRPath) {
  301. this->OrderDependentRPath->SetImplicitDirectories(this->ImplicitLinkDirs);
  302. this->OrderDependentRPath->AddLanguageDirectories(this->RuntimeLinkDirs);
  303. }
  304. // Decide whether to enable compatible library search path mode.
  305. // There exists code that effectively does
  306. //
  307. // /path/to/libA.so -lB
  308. //
  309. // where -lB is meant to link to /path/to/libB.so. This is broken
  310. // because it specified -lB without specifying a link directory (-L)
  311. // in which to search for B. This worked in CMake 2.4 and below
  312. // because -L/path/to would be added by the -L/-l split for A. In
  313. // order to support such projects we need to add the directories
  314. // containing libraries linked with a full path to the -L path.
  315. this->OldLinkDirMode =
  316. this->Target->GetPolicyStatusCMP0003() != cmPolicies::NEW;
  317. if (this->OldLinkDirMode) {
  318. // Construct a mask to not bother with this behavior for link
  319. // directories already specified by the user.
  320. this->OldLinkDirMask.insert(directories.begin(), directories.end());
  321. }
  322. this->CMP0060Warn = this->Makefile->PolicyOptionalWarningEnabled(
  323. "CMAKE_POLICY_WARNING_CMP0060");
  324. }
  325. cmComputeLinkInformation::~cmComputeLinkInformation()
  326. {
  327. delete this->OrderLinkerSearchPath;
  328. delete this->OrderRuntimeSearchPath;
  329. delete this->OrderDependentRPath;
  330. }
  331. cmComputeLinkInformation::ItemVector const&
  332. cmComputeLinkInformation::GetItems() const
  333. {
  334. return this->Items;
  335. }
  336. std::vector<std::string> const& cmComputeLinkInformation::GetDirectories()
  337. const
  338. {
  339. return this->OrderLinkerSearchPath->GetOrderedDirectories();
  340. }
  341. std::string cmComputeLinkInformation::GetRPathLinkString() const
  342. {
  343. // If there is no separate linker runtime search flag (-rpath-link)
  344. // there is no reason to compute a string.
  345. if (!this->OrderDependentRPath) {
  346. return "";
  347. }
  348. // Construct the linker runtime search path. These MUST NOT contain tokens
  349. // such as $ORIGIN, see https://sourceware.org/bugzilla/show_bug.cgi?id=16936
  350. return cmJoin(this->OrderDependentRPath->GetOrderedDirectories(), ":");
  351. }
  352. std::vector<std::string> const& cmComputeLinkInformation::GetDepends() const
  353. {
  354. return this->Depends;
  355. }
  356. std::vector<std::string> const& cmComputeLinkInformation::GetFrameworkPaths()
  357. const
  358. {
  359. return this->FrameworkPaths;
  360. }
  361. const std::set<const cmGeneratorTarget*>&
  362. cmComputeLinkInformation::GetSharedLibrariesLinked() const
  363. {
  364. return this->SharedLibrariesLinked;
  365. }
  366. bool cmComputeLinkInformation::Compute()
  367. {
  368. // Skip targets that do not link.
  369. if (!(this->Target->GetType() == cmStateEnums::EXECUTABLE ||
  370. this->Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  371. this->Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  372. this->Target->GetType() == cmStateEnums::STATIC_LIBRARY)) {
  373. return false;
  374. }
  375. // We require a link language for the target.
  376. if (this->LinkLanguage.empty()) {
  377. cmSystemTools::Error(
  378. "CMake can not determine linker language for target: " +
  379. this->Target->GetName());
  380. return false;
  381. }
  382. // Compute the ordered link line items.
  383. cmComputeLinkDepends cld(this->Target, this->Config);
  384. cld.SetOldLinkDirMode(this->OldLinkDirMode);
  385. cmComputeLinkDepends::EntryVector const& linkEntries = cld.Compute();
  386. // Add the link line items.
  387. for (cmComputeLinkDepends::LinkEntry const& linkEntry : linkEntries) {
  388. if (linkEntry.IsSharedDep) {
  389. this->AddSharedDepItem(linkEntry.Item, linkEntry.Target);
  390. } else {
  391. this->AddItem(linkEntry.Item, linkEntry.Target);
  392. }
  393. }
  394. // Restore the target link type so the correct system runtime
  395. // libraries are found.
  396. const char* lss = this->Target->GetProperty("LINK_SEARCH_END_STATIC");
  397. if (cmIsOn(lss)) {
  398. this->SetCurrentLinkType(LinkStatic);
  399. } else {
  400. this->SetCurrentLinkType(this->StartLinkType);
  401. }
  402. // Finish listing compatibility paths.
  403. if (this->OldLinkDirMode) {
  404. // For CMake 2.4 bug-compatibility we need to consider the output
  405. // directories of targets linked in another configuration as link
  406. // directories.
  407. std::set<cmGeneratorTarget const*> const& wrongItems =
  408. cld.GetOldWrongConfigItems();
  409. for (cmGeneratorTarget const* tgt : wrongItems) {
  410. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(this->Config)
  411. ? cmStateEnums::ImportLibraryArtifact
  412. : cmStateEnums::RuntimeBinaryArtifact;
  413. this->OldLinkDirItems.push_back(
  414. tgt->GetFullPath(this->Config, artifact, true));
  415. }
  416. }
  417. // Finish setting up linker search directories.
  418. if (!this->FinishLinkerSearchDirectories()) {
  419. return false;
  420. }
  421. // Add implicit language runtime libraries and directories.
  422. this->AddImplicitLinkInfo();
  423. if (!this->CMP0060WarnItems.empty()) {
  424. std::ostringstream w;
  425. /* clang-format off */
  426. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0060) << "\n"
  427. "Some library files are in directories implicitly searched by "
  428. "the linker when invoked for " << this->LinkLanguage << ":\n"
  429. " " << cmJoin(this->CMP0060WarnItems, "\n ") << "\n"
  430. "For compatibility with older versions of CMake, the generated "
  431. "link line will ask the linker to search for these by library "
  432. "name."
  433. ;
  434. /* clang-format on */
  435. this->CMakeInstance->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  436. this->Target->GetBacktrace());
  437. }
  438. return true;
  439. }
  440. void cmComputeLinkInformation::AddImplicitLinkInfo()
  441. {
  442. // The link closure lists all languages whose implicit info is needed.
  443. cmGeneratorTarget::LinkClosure const* lc =
  444. this->Target->GetLinkClosure(this->Config);
  445. for (std::string const& li : lc->Languages) {
  446. // Skip those of the linker language. They are implicit.
  447. if (li != this->LinkLanguage) {
  448. this->AddImplicitLinkInfo(li);
  449. }
  450. }
  451. }
  452. void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang)
  453. {
  454. // Add libraries for this language that are not implied by the
  455. // linker language.
  456. std::string libVar = cmStrCat("CMAKE_", lang, "_IMPLICIT_LINK_LIBRARIES");
  457. if (const char* libs = this->Makefile->GetDefinition(libVar)) {
  458. std::vector<std::string> libsVec = cmExpandedList(libs);
  459. for (std::string const& i : libsVec) {
  460. if (!cmContains(this->ImplicitLinkLibs, i)) {
  461. this->AddItem(i, nullptr);
  462. }
  463. }
  464. }
  465. // Add linker search paths for this language that are not
  466. // implied by the linker language.
  467. std::string dirVar = cmStrCat("CMAKE_", lang, "_IMPLICIT_LINK_DIRECTORIES");
  468. if (const char* dirs = this->Makefile->GetDefinition(dirVar)) {
  469. std::vector<std::string> dirsVec = cmExpandedList(dirs);
  470. this->OrderLinkerSearchPath->AddLanguageDirectories(dirsVec);
  471. }
  472. }
  473. void cmComputeLinkInformation::AddItem(std::string const& item,
  474. cmGeneratorTarget const* tgt)
  475. {
  476. // Compute the proper name to use to link this library.
  477. const std::string& config = this->Config;
  478. bool impexe = (tgt && tgt->IsExecutableWithExports());
  479. if (impexe && !tgt->HasImportLibrary(config) && !this->LoaderFlag) {
  480. // Skip linking to executables on platforms with no import
  481. // libraries or loader flags.
  482. return;
  483. }
  484. if (tgt && tgt->IsLinkable()) {
  485. // This is a CMake target. Ask the target for its real name.
  486. if (impexe && this->LoaderFlag) {
  487. // This link item is an executable that may provide symbols
  488. // used by this target. A special flag is needed on this
  489. // platform. Add it now.
  490. std::string linkItem;
  491. linkItem = this->LoaderFlag;
  492. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(config)
  493. ? cmStateEnums::ImportLibraryArtifact
  494. : cmStateEnums::RuntimeBinaryArtifact;
  495. std::string exe = tgt->GetFullPath(config, artifact, true);
  496. linkItem += exe;
  497. this->Items.emplace_back(linkItem, true, tgt);
  498. this->Depends.push_back(std::move(exe));
  499. } else if (tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  500. // Add the interface library as an item so it can be considered as part
  501. // of COMPATIBLE_INTERFACE_ enforcement. The generators will ignore
  502. // this for the actual link line.
  503. this->Items.emplace_back(std::string(), false, tgt);
  504. // Also add the item the interface specifies to be used in its place.
  505. std::string const& libName = tgt->GetImportedLibName(config);
  506. if (!libName.empty()) {
  507. this->AddItem(libName, nullptr);
  508. }
  509. } else if (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  510. // Ignore object library!
  511. // Its object-files should already have been extracted for linking.
  512. } else {
  513. // Decide whether to use an import library.
  514. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(config)
  515. ? cmStateEnums::ImportLibraryArtifact
  516. : cmStateEnums::RuntimeBinaryArtifact;
  517. // Pass the full path to the target file.
  518. std::string lib = tgt->GetFullPath(config, artifact, true);
  519. if (tgt->Target->IsAIX() && cmHasLiteralSuffix(lib, "-NOTFOUND") &&
  520. artifact == cmStateEnums::ImportLibraryArtifact) {
  521. // This is an imported executable on AIX that has ENABLE_EXPORTS
  522. // but not IMPORTED_IMPLIB. CMake used to produce and accept such
  523. // imported executables on AIX before we taught it to use linker
  524. // import files. For compatibility, simply skip linking to this
  525. // executable as we did before. It works with runtime linking.
  526. return;
  527. }
  528. if (!this->LinkDependsNoShared ||
  529. tgt->GetType() != cmStateEnums::SHARED_LIBRARY) {
  530. this->Depends.push_back(lib);
  531. }
  532. this->AddTargetItem(lib, tgt);
  533. this->AddLibraryRuntimeInfo(lib, tgt);
  534. }
  535. } else {
  536. // This is not a CMake target. Use the name given.
  537. if (cmSystemTools::FileIsFullPath(item)) {
  538. if (cmSystemTools::FileIsDirectory(item)) {
  539. // This is a directory.
  540. this->AddDirectoryItem(item);
  541. } else {
  542. // Use the full path given to the library file.
  543. this->Depends.push_back(item);
  544. this->AddFullItem(item);
  545. this->AddLibraryRuntimeInfo(item);
  546. }
  547. } else {
  548. // This is a library or option specified by the user.
  549. this->AddUserItem(item, true);
  550. }
  551. }
  552. }
  553. void cmComputeLinkInformation::AddSharedDepItem(std::string const& item,
  554. const cmGeneratorTarget* tgt)
  555. {
  556. // If dropping shared library dependencies, ignore them.
  557. if (this->SharedDependencyMode == SharedDepModeNone) {
  558. return;
  559. }
  560. // The user may have incorrectly named an item. Skip items that are
  561. // not full paths to shared libraries.
  562. if (tgt) {
  563. // The target will provide a full path. Make sure it is a shared
  564. // library.
  565. if (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) {
  566. return;
  567. }
  568. } else {
  569. // Skip items that are not full paths. We will not be able to
  570. // reliably specify them.
  571. if (!cmSystemTools::FileIsFullPath(item)) {
  572. return;
  573. }
  574. // Get the name of the library from the file name.
  575. std::string file = cmSystemTools::GetFilenameName(item);
  576. if (!this->ExtractSharedLibraryName.find(file)) {
  577. // This is not the name of a shared library.
  578. return;
  579. }
  580. }
  581. // If in linking mode, just link to the shared library.
  582. if (this->SharedDependencyMode == SharedDepModeLink) {
  583. this->AddItem(item, tgt);
  584. return;
  585. }
  586. // Get a full path to the dependent shared library.
  587. // Add it to the runtime path computation so that the target being
  588. // linked will be able to find it.
  589. std::string lib;
  590. if (tgt) {
  591. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(this->Config)
  592. ? cmStateEnums::ImportLibraryArtifact
  593. : cmStateEnums::RuntimeBinaryArtifact;
  594. lib = tgt->GetFullPath(this->Config, artifact);
  595. this->AddLibraryRuntimeInfo(lib, tgt);
  596. } else {
  597. lib = item;
  598. this->AddLibraryRuntimeInfo(lib);
  599. }
  600. // Check if we need to include the dependent shared library in other
  601. // path ordering.
  602. cmOrderDirectories* order = nullptr;
  603. if (this->SharedDependencyMode == SharedDepModeLibDir &&
  604. !this->LinkWithRuntimePath /* AddLibraryRuntimeInfo adds it */) {
  605. // Add the item to the linker search path.
  606. order = this->OrderLinkerSearchPath;
  607. } else if (this->SharedDependencyMode == SharedDepModeDir) {
  608. // Add the item to the separate dependent library search path.
  609. order = this->OrderDependentRPath;
  610. }
  611. if (order) {
  612. if (tgt) {
  613. std::string soName = tgt->GetSOName(this->Config);
  614. const char* soname = soName.empty() ? nullptr : soName.c_str();
  615. order->AddRuntimeLibrary(lib, soname);
  616. } else {
  617. order->AddRuntimeLibrary(lib);
  618. }
  619. }
  620. }
  621. void cmComputeLinkInformation::ComputeLinkTypeInfo()
  622. {
  623. // Check whether archives may actually be shared libraries.
  624. this->ArchivesMayBeShared =
  625. this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  626. "TARGET_ARCHIVES_MAY_BE_SHARED_LIBS");
  627. // First assume we cannot do link type stuff.
  628. this->LinkTypeEnabled = false;
  629. // Lookup link type selection flags.
  630. const char* static_link_type_flag = nullptr;
  631. const char* shared_link_type_flag = nullptr;
  632. const char* target_type_str = nullptr;
  633. switch (this->Target->GetType()) {
  634. case cmStateEnums::EXECUTABLE:
  635. target_type_str = "EXE";
  636. break;
  637. case cmStateEnums::SHARED_LIBRARY:
  638. target_type_str = "SHARED_LIBRARY";
  639. break;
  640. case cmStateEnums::MODULE_LIBRARY:
  641. target_type_str = "SHARED_MODULE";
  642. break;
  643. default:
  644. break;
  645. }
  646. if (target_type_str) {
  647. std::string static_link_type_flag_var =
  648. cmStrCat("CMAKE_", target_type_str, "_LINK_STATIC_", this->LinkLanguage,
  649. "_FLAGS");
  650. static_link_type_flag =
  651. this->Makefile->GetDefinition(static_link_type_flag_var);
  652. std::string shared_link_type_flag_var =
  653. cmStrCat("CMAKE_", target_type_str, "_LINK_DYNAMIC_", this->LinkLanguage,
  654. "_FLAGS");
  655. shared_link_type_flag =
  656. this->Makefile->GetDefinition(shared_link_type_flag_var);
  657. }
  658. // We can support link type switching only if all needed flags are
  659. // known.
  660. if (static_link_type_flag && *static_link_type_flag &&
  661. shared_link_type_flag && *shared_link_type_flag) {
  662. this->LinkTypeEnabled = true;
  663. this->StaticLinkTypeFlag = static_link_type_flag;
  664. this->SharedLinkTypeFlag = shared_link_type_flag;
  665. }
  666. // Lookup the starting link type from the target (linked statically?).
  667. const char* lss = this->Target->GetProperty("LINK_SEARCH_START_STATIC");
  668. this->StartLinkType = cmIsOn(lss) ? LinkStatic : LinkShared;
  669. this->CurrentLinkType = this->StartLinkType;
  670. }
  671. void cmComputeLinkInformation::ComputeItemParserInfo()
  672. {
  673. // Get possible library name prefixes.
  674. cmMakefile* mf = this->Makefile;
  675. this->AddLinkPrefix(mf->GetDefinition("CMAKE_STATIC_LIBRARY_PREFIX"));
  676. this->AddLinkPrefix(mf->GetDefinition("CMAKE_SHARED_LIBRARY_PREFIX"));
  677. // Import library names should be matched and treated as shared
  678. // libraries for the purposes of linking.
  679. this->AddLinkExtension(mf->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX"),
  680. LinkShared);
  681. this->AddLinkExtension(mf->GetDefinition("CMAKE_STATIC_LIBRARY_SUFFIX"),
  682. LinkStatic);
  683. this->AddLinkExtension(mf->GetDefinition("CMAKE_SHARED_LIBRARY_SUFFIX"),
  684. LinkShared);
  685. this->AddLinkExtension(mf->GetDefinition("CMAKE_LINK_LIBRARY_SUFFIX"),
  686. LinkUnknown);
  687. if (const char* linkSuffixes =
  688. mf->GetDefinition("CMAKE_EXTRA_LINK_EXTENSIONS")) {
  689. std::vector<std::string> linkSuffixVec = cmExpandedList(linkSuffixes);
  690. for (std::string const& i : linkSuffixVec) {
  691. this->AddLinkExtension(i.c_str(), LinkUnknown);
  692. }
  693. }
  694. if (const char* sharedSuffixes =
  695. mf->GetDefinition("CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES")) {
  696. std::vector<std::string> sharedSuffixVec = cmExpandedList(sharedSuffixes);
  697. for (std::string const& i : sharedSuffixVec) {
  698. this->AddLinkExtension(i.c_str(), LinkShared);
  699. }
  700. }
  701. // Compute a regex to match link extensions.
  702. std::string libext =
  703. this->CreateExtensionRegex(this->LinkExtensions, LinkUnknown);
  704. // Create regex to remove any library extension.
  705. std::string reg("(.*)");
  706. reg += libext;
  707. this->OrderLinkerSearchPath->SetLinkExtensionInfo(this->LinkExtensions, reg);
  708. // Create a regex to match a library name. Match index 1 will be
  709. // the prefix if it exists and empty otherwise. Match index 2 will
  710. // be the library name. Match index 3 will be the library
  711. // extension.
  712. reg = "^(";
  713. for (std::string const& p : this->LinkPrefixes) {
  714. reg += p;
  715. reg += "|";
  716. }
  717. reg += ")";
  718. reg += "([^/:]*)";
  719. // Create a regex to match any library name.
  720. std::string reg_any = cmStrCat(reg, libext);
  721. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  722. fprintf(stderr, "any regex [%s]\n", reg_any.c_str());
  723. #endif
  724. this->ExtractAnyLibraryName.compile(reg_any.c_str());
  725. // Create a regex to match static library names.
  726. if (!this->StaticLinkExtensions.empty()) {
  727. std::string reg_static = cmStrCat(
  728. reg, this->CreateExtensionRegex(this->StaticLinkExtensions, LinkStatic));
  729. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  730. fprintf(stderr, "static regex [%s]\n", reg_static.c_str());
  731. #endif
  732. this->ExtractStaticLibraryName.compile(reg_static.c_str());
  733. }
  734. // Create a regex to match shared library names.
  735. if (!this->SharedLinkExtensions.empty()) {
  736. std::string reg_shared = reg;
  737. this->SharedRegexString =
  738. this->CreateExtensionRegex(this->SharedLinkExtensions, LinkShared);
  739. reg_shared += this->SharedRegexString;
  740. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  741. fprintf(stderr, "shared regex [%s]\n", reg_shared.c_str());
  742. #endif
  743. this->ExtractSharedLibraryName.compile(reg_shared.c_str());
  744. }
  745. }
  746. void cmComputeLinkInformation::AddLinkPrefix(const char* p)
  747. {
  748. if (p && *p) {
  749. this->LinkPrefixes.insert(p);
  750. }
  751. }
  752. void cmComputeLinkInformation::AddLinkExtension(const char* e, LinkType type)
  753. {
  754. if (e && *e) {
  755. if (type == LinkStatic) {
  756. this->StaticLinkExtensions.emplace_back(e);
  757. }
  758. if (type == LinkShared) {
  759. this->SharedLinkExtensions.emplace_back(e);
  760. }
  761. this->LinkExtensions.emplace_back(e);
  762. }
  763. }
  764. std::string cmComputeLinkInformation::CreateExtensionRegex(
  765. std::vector<std::string> const& exts, LinkType type)
  766. {
  767. // Build a list of extension choices.
  768. std::string libext = "(";
  769. const char* sep = "";
  770. for (std::string const& i : exts) {
  771. // Separate this choice from the previous one.
  772. libext += sep;
  773. sep = "|";
  774. // Store this extension choice with the "." escaped.
  775. libext += "\\";
  776. #if defined(_WIN32) && !defined(__CYGWIN__)
  777. libext += this->NoCaseExpression(i.c_str());
  778. #else
  779. libext += i;
  780. #endif
  781. }
  782. // Finish the list.
  783. libext += ")";
  784. // Add an optional OpenBSD-style version or major.minor.version component.
  785. if (this->OpenBSD || type == LinkShared) {
  786. libext += "(\\.[0-9]+)*";
  787. }
  788. libext += "$";
  789. return libext;
  790. }
  791. std::string cmComputeLinkInformation::NoCaseExpression(const char* str)
  792. {
  793. std::string ret;
  794. const char* s = str;
  795. while (*s) {
  796. if (*s == '.') {
  797. ret += *s;
  798. } else {
  799. ret += "[";
  800. ret += static_cast<char>(tolower(*s));
  801. ret += static_cast<char>(toupper(*s));
  802. ret += "]";
  803. }
  804. s++;
  805. }
  806. return ret;
  807. }
  808. void cmComputeLinkInformation::SetCurrentLinkType(LinkType lt)
  809. {
  810. // If we are changing the current link type add the flag to tell the
  811. // linker about it.
  812. if (this->CurrentLinkType != lt) {
  813. this->CurrentLinkType = lt;
  814. if (this->LinkTypeEnabled) {
  815. switch (this->CurrentLinkType) {
  816. case LinkStatic:
  817. this->Items.emplace_back(this->StaticLinkTypeFlag, false);
  818. break;
  819. case LinkShared:
  820. this->Items.emplace_back(this->SharedLinkTypeFlag, false);
  821. break;
  822. default:
  823. break;
  824. }
  825. }
  826. }
  827. }
  828. void cmComputeLinkInformation::AddTargetItem(std::string const& item,
  829. cmGeneratorTarget const* target)
  830. {
  831. // This is called to handle a link item that is a full path to a target.
  832. // If the target is not a static library make sure the link type is
  833. // shared. This is because dynamic-mode linking can handle both
  834. // shared and static libraries but static-mode can handle only
  835. // static libraries. If a previous user item changed the link type
  836. // to static we need to make sure it is back to shared.
  837. if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  838. this->SetCurrentLinkType(LinkShared);
  839. }
  840. // Keep track of shared library targets linked.
  841. if (target->GetType() == cmStateEnums::SHARED_LIBRARY) {
  842. this->SharedLibrariesLinked.insert(target);
  843. }
  844. // Handle case of an imported shared library with no soname.
  845. if (this->NoSONameUsesPath &&
  846. target->IsImportedSharedLibWithoutSOName(this->Config)) {
  847. this->AddSharedLibNoSOName(item);
  848. return;
  849. }
  850. // For compatibility with CMake 2.4 include the item's directory in
  851. // the linker search path.
  852. if (this->OldLinkDirMode && !target->IsFrameworkOnApple() &&
  853. !cmContains(this->OldLinkDirMask,
  854. cmSystemTools::GetFilenamePath(item))) {
  855. this->OldLinkDirItems.push_back(item);
  856. }
  857. // Now add the full path to the library.
  858. this->Items.emplace_back(item, true, target);
  859. }
  860. void cmComputeLinkInformation::AddFullItem(std::string const& item)
  861. {
  862. // Check for the implicit link directory special case.
  863. if (this->CheckImplicitDirItem(item)) {
  864. return;
  865. }
  866. // Check for case of shared library with no builtin soname.
  867. if (this->NoSONameUsesPath && this->CheckSharedLibNoSOName(item)) {
  868. return;
  869. }
  870. // Full path libraries should specify a valid library file name.
  871. // See documentation of CMP0008.
  872. std::string generator = this->GlobalGenerator->GetName();
  873. if (this->Target->GetPolicyStatusCMP0008() != cmPolicies::NEW &&
  874. (generator.find("Visual Studio") != std::string::npos ||
  875. generator.find("Xcode") != std::string::npos)) {
  876. std::string file = cmSystemTools::GetFilenameName(item);
  877. if (!this->ExtractAnyLibraryName.find(file)) {
  878. this->HandleBadFullItem(item, file);
  879. return;
  880. }
  881. }
  882. // This is called to handle a link item that is a full path.
  883. // If the target is not a static library make sure the link type is
  884. // shared. This is because dynamic-mode linking can handle both
  885. // shared and static libraries but static-mode can handle only
  886. // static libraries. If a previous user item changed the link type
  887. // to static we need to make sure it is back to shared.
  888. if (this->LinkTypeEnabled) {
  889. std::string name = cmSystemTools::GetFilenameName(item);
  890. if (this->ExtractSharedLibraryName.find(name)) {
  891. this->SetCurrentLinkType(LinkShared);
  892. } else if (!this->ExtractStaticLibraryName.find(item)) {
  893. // We cannot determine the type. Assume it is the target's
  894. // default type.
  895. this->SetCurrentLinkType(this->StartLinkType);
  896. }
  897. }
  898. // For compatibility with CMake 2.4 include the item's directory in
  899. // the linker search path.
  900. if (this->OldLinkDirMode &&
  901. !cmContains(this->OldLinkDirMask,
  902. cmSystemTools::GetFilenamePath(item))) {
  903. this->OldLinkDirItems.push_back(item);
  904. }
  905. // Now add the full path to the library.
  906. this->Items.emplace_back(item, true);
  907. }
  908. bool cmComputeLinkInformation::CheckImplicitDirItem(std::string const& item)
  909. {
  910. // We only switch to a pathless item if the link type may be
  911. // enforced. Fortunately only platforms that support link types
  912. // seem to have magic per-architecture implicit link directories.
  913. if (!this->LinkTypeEnabled) {
  914. return false;
  915. }
  916. // Check if this item is in an implicit link directory.
  917. std::string dir = cmSystemTools::GetFilenamePath(item);
  918. if (!cmContains(this->ImplicitLinkDirs, dir)) {
  919. // Only libraries in implicit link directories are converted to
  920. // pathless items.
  921. return false;
  922. }
  923. // Only apply the policy below if the library file is one that can
  924. // be found by the linker.
  925. std::string file = cmSystemTools::GetFilenameName(item);
  926. if (!this->ExtractAnyLibraryName.find(file)) {
  927. return false;
  928. }
  929. // Check the policy for whether we should use the approach below.
  930. switch (this->Target->GetPolicyStatusCMP0060()) {
  931. case cmPolicies::WARN:
  932. if (this->CMP0060Warn) {
  933. // Print the warning at most once for this item.
  934. std::string const& wid = "CMP0060-WARNING-GIVEN-" + item;
  935. if (!this->CMakeInstance->GetPropertyAsBool(wid)) {
  936. this->CMakeInstance->SetProperty(wid, "1");
  937. this->CMP0060WarnItems.insert(item);
  938. }
  939. }
  940. case cmPolicies::OLD:
  941. break;
  942. case cmPolicies::REQUIRED_ALWAYS:
  943. case cmPolicies::REQUIRED_IF_USED:
  944. case cmPolicies::NEW:
  945. return false;
  946. }
  947. // Many system linkers support multiple architectures by
  948. // automatically selecting the implicit linker search path for the
  949. // current architecture. If the library appears in an implicit link
  950. // directory then just report the file name without the directory
  951. // portion. This will allow the system linker to locate the proper
  952. // library for the architecture at link time.
  953. this->AddUserItem(file, false);
  954. // Make sure the link directory ordering will find the library.
  955. this->OrderLinkerSearchPath->AddLinkLibrary(item);
  956. return true;
  957. }
  958. void cmComputeLinkInformation::AddUserItem(std::string const& item,
  959. bool pathNotKnown)
  960. {
  961. // This is called to handle a link item that does not match a CMake
  962. // target and is not a full path. We check here if it looks like a
  963. // library file name to automatically request the proper link type
  964. // from the linker. For example:
  965. //
  966. // foo ==> -lfoo
  967. // libfoo.a ==> -Wl,-Bstatic -lfoo
  968. // Pass flags through untouched.
  969. if (item[0] == '-' || item[0] == '$' || item[0] == '`') {
  970. // if this is a -l option then we might need to warn about
  971. // CMP0003 so put it in OldUserFlagItems, if it is not a -l
  972. // or -Wl,-l (-framework -pthread), then allow it without a
  973. // CMP0003 as -L will not affect those other linker flags
  974. if (item.find("-l") == 0 || item.find("-Wl,-l") == 0) {
  975. // This is a linker option provided by the user.
  976. this->OldUserFlagItems.push_back(item);
  977. }
  978. // Restore the target link type since this item does not specify
  979. // one.
  980. this->SetCurrentLinkType(this->StartLinkType);
  981. // Use the item verbatim.
  982. this->Items.emplace_back(item, false);
  983. return;
  984. }
  985. // Parse out the prefix, base, and suffix components of the
  986. // library name. If the name matches that of a shared or static
  987. // library then set the link type accordingly.
  988. //
  989. // Search for shared library names first because some platforms
  990. // have shared libraries with names that match the static library
  991. // pattern. For example cygwin and msys use the convention
  992. // libfoo.dll.a for import libraries and libfoo.a for static
  993. // libraries. On AIX a library with the name libfoo.a can be
  994. // shared!
  995. std::string lib;
  996. if (this->ExtractSharedLibraryName.find(item)) {
  997. // This matches a shared library file name.
  998. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  999. fprintf(stderr, "shared regex matched [%s] [%s] [%s]\n",
  1000. this->ExtractSharedLibraryName.match(1).c_str(),
  1001. this->ExtractSharedLibraryName.match(2).c_str(),
  1002. this->ExtractSharedLibraryName.match(3).c_str());
  1003. #endif
  1004. // Set the link type to shared.
  1005. this->SetCurrentLinkType(LinkShared);
  1006. // Use just the library name so the linker will search.
  1007. lib = this->ExtractSharedLibraryName.match(2);
  1008. } else if (this->ExtractStaticLibraryName.find(item)) {
  1009. // This matches a static library file name.
  1010. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1011. fprintf(stderr, "static regex matched [%s] [%s] [%s]\n",
  1012. this->ExtractStaticLibraryName.match(1).c_str(),
  1013. this->ExtractStaticLibraryName.match(2).c_str(),
  1014. this->ExtractStaticLibraryName.match(3).c_str());
  1015. #endif
  1016. // Set the link type to static.
  1017. this->SetCurrentLinkType(LinkStatic);
  1018. // Use just the library name so the linker will search.
  1019. lib = this->ExtractStaticLibraryName.match(2);
  1020. } else if (this->ExtractAnyLibraryName.find(item)) {
  1021. // This matches a library file name.
  1022. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1023. fprintf(stderr, "any regex matched [%s] [%s] [%s]\n",
  1024. this->ExtractAnyLibraryName.match(1).c_str(),
  1025. this->ExtractAnyLibraryName.match(2).c_str(),
  1026. this->ExtractAnyLibraryName.match(3).c_str());
  1027. #endif
  1028. // Restore the target link type since this item does not specify
  1029. // one.
  1030. this->SetCurrentLinkType(this->StartLinkType);
  1031. // Use just the library name so the linker will search.
  1032. lib = this->ExtractAnyLibraryName.match(2);
  1033. } else {
  1034. // This is a name specified by the user.
  1035. if (pathNotKnown) {
  1036. this->OldUserFlagItems.push_back(item);
  1037. }
  1038. // We must ask the linker to search for a library with this name.
  1039. // Restore the target link type since this item does not specify
  1040. // one.
  1041. this->SetCurrentLinkType(this->StartLinkType);
  1042. lib = item;
  1043. }
  1044. // Create an option to ask the linker to search for the library.
  1045. std::string out = cmStrCat(this->LibLinkFlag, lib, this->LibLinkSuffix);
  1046. this->Items.emplace_back(out, false);
  1047. // Here we could try to find the library the linker will find and
  1048. // add a runtime information entry for it. It would probably not be
  1049. // reliable and we want to encourage use of full paths for library
  1050. // specification.
  1051. }
  1052. void cmComputeLinkInformation::AddFrameworkItem(std::string const& item)
  1053. {
  1054. // Try to separate the framework name and path.
  1055. if (!this->SplitFramework.find(item)) {
  1056. std::ostringstream e;
  1057. e << "Could not parse framework path \"" << item << "\" "
  1058. << "linked by target " << this->Target->GetName() << ".";
  1059. cmSystemTools::Error(e.str());
  1060. return;
  1061. }
  1062. std::string fw_path = this->SplitFramework.match(1);
  1063. std::string fw = this->SplitFramework.match(2);
  1064. std::string full_fw = cmStrCat(fw_path, '/', fw, ".framework/", fw);
  1065. // Add the directory portion to the framework search path.
  1066. this->AddFrameworkPath(fw_path);
  1067. // add runtime information
  1068. this->AddLibraryRuntimeInfo(full_fw);
  1069. // Add the item using the -framework option.
  1070. this->Items.emplace_back("-framework", false);
  1071. cmOutputConverter converter(this->Makefile->GetStateSnapshot());
  1072. fw = converter.EscapeForShell(fw);
  1073. this->Items.emplace_back(fw, false);
  1074. }
  1075. void cmComputeLinkInformation::AddDirectoryItem(std::string const& item)
  1076. {
  1077. if (this->Makefile->IsOn("APPLE") &&
  1078. cmSystemTools::IsPathToFramework(item)) {
  1079. this->AddFrameworkItem(item);
  1080. } else {
  1081. this->DropDirectoryItem(item);
  1082. }
  1083. }
  1084. void cmComputeLinkInformation::DropDirectoryItem(std::string const& item)
  1085. {
  1086. // A full path to a directory was found as a link item. Warn the
  1087. // user.
  1088. std::ostringstream e;
  1089. e << "WARNING: Target \"" << this->Target->GetName()
  1090. << "\" requests linking to directory \"" << item << "\". "
  1091. << "Targets may link only to libraries. "
  1092. << "CMake is dropping the item.";
  1093. cmSystemTools::Message(e.str());
  1094. }
  1095. void cmComputeLinkInformation::ComputeFrameworkInfo()
  1096. {
  1097. // Avoid adding implicit framework paths.
  1098. std::vector<std::string> implicitDirVec;
  1099. // Get platform-wide implicit directories.
  1100. if (const char* implicitLinks = this->Makefile->GetDefinition(
  1101. "CMAKE_PLATFORM_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES")) {
  1102. cmExpandList(implicitLinks, implicitDirVec);
  1103. }
  1104. // Get language-specific implicit directories.
  1105. std::string implicitDirVar = cmStrCat(
  1106. "CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES");
  1107. if (const char* implicitDirs =
  1108. this->Makefile->GetDefinition(implicitDirVar)) {
  1109. cmExpandList(implicitDirs, implicitDirVec);
  1110. }
  1111. this->FrameworkPathsEmmitted.insert(implicitDirVec.begin(),
  1112. implicitDirVec.end());
  1113. // Regular expression to extract a framework path and name.
  1114. this->SplitFramework.compile("(.*)/(.*)\\.framework$");
  1115. }
  1116. void cmComputeLinkInformation::AddFrameworkPath(std::string const& p)
  1117. {
  1118. if (this->FrameworkPathsEmmitted.insert(p).second) {
  1119. this->FrameworkPaths.push_back(p);
  1120. }
  1121. }
  1122. bool cmComputeLinkInformation::CheckSharedLibNoSOName(std::string const& item)
  1123. {
  1124. // This platform will use the path to a library as its soname if the
  1125. // library is given via path and was not built with an soname. If
  1126. // this is a shared library that might be the case.
  1127. std::string file = cmSystemTools::GetFilenameName(item);
  1128. if (this->ExtractSharedLibraryName.find(file)) {
  1129. // If we can guess the soname fairly reliably then assume the
  1130. // library has one. Otherwise assume the library has no builtin
  1131. // soname.
  1132. std::string soname;
  1133. if (!cmSystemTools::GuessLibrarySOName(item, soname)) {
  1134. this->AddSharedLibNoSOName(item);
  1135. return true;
  1136. }
  1137. }
  1138. return false;
  1139. }
  1140. void cmComputeLinkInformation::AddSharedLibNoSOName(std::string const& item)
  1141. {
  1142. // We have a full path to a shared library with no soname. We need
  1143. // to ask the linker to locate the item because otherwise the path
  1144. // we give to it will be embedded in the target linked. Then at
  1145. // runtime the dynamic linker will search for the library using the
  1146. // path instead of just the name.
  1147. std::string file = cmSystemTools::GetFilenameName(item);
  1148. this->AddUserItem(file, false);
  1149. // Make sure the link directory ordering will find the library.
  1150. this->OrderLinkerSearchPath->AddLinkLibrary(item);
  1151. }
  1152. void cmComputeLinkInformation::HandleBadFullItem(std::string const& item,
  1153. std::string const& file)
  1154. {
  1155. // Do not depend on things that do not exist.
  1156. auto i = std::find(this->Depends.begin(), this->Depends.end(), item);
  1157. if (i != this->Depends.end()) {
  1158. this->Depends.erase(i);
  1159. }
  1160. // Tell the linker to search for the item and provide the proper
  1161. // path for it. Do not contribute to any CMP0003 warning (do not
  1162. // put in OldLinkDirItems or OldUserFlagItems).
  1163. this->AddUserItem(file, false);
  1164. this->OrderLinkerSearchPath->AddLinkLibrary(item);
  1165. // Produce any needed message.
  1166. switch (this->Target->GetPolicyStatusCMP0008()) {
  1167. case cmPolicies::WARN: {
  1168. // Print the warning at most once for this item.
  1169. std::string wid = cmStrCat("CMP0008-WARNING-GIVEN-", item);
  1170. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(wid)) {
  1171. this->CMakeInstance->GetState()->SetGlobalProperty(wid, "1");
  1172. std::ostringstream w;
  1173. /* clang-format off */
  1174. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0008) << "\n"
  1175. << "Target \"" << this->Target->GetName() << "\" links to item\n"
  1176. << " " << item << "\n"
  1177. << "which is a full-path but not a valid library file name.";
  1178. /* clang-format on */
  1179. this->CMakeInstance->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  1180. this->Target->GetBacktrace());
  1181. }
  1182. }
  1183. case cmPolicies::OLD:
  1184. // OLD behavior does not warn.
  1185. break;
  1186. case cmPolicies::NEW:
  1187. // NEW behavior will not get here.
  1188. break;
  1189. case cmPolicies::REQUIRED_IF_USED:
  1190. case cmPolicies::REQUIRED_ALWAYS: {
  1191. std::ostringstream e;
  1192. /* clang-format off */
  1193. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0008) << "\n"
  1194. << "Target \"" << this->Target->GetName() << "\" links to item\n"
  1195. << " " << item << "\n"
  1196. << "which is a full-path but not a valid library file name.";
  1197. /* clang-format on */
  1198. this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1199. this->Target->GetBacktrace());
  1200. } break;
  1201. }
  1202. }
  1203. bool cmComputeLinkInformation::FinishLinkerSearchDirectories()
  1204. {
  1205. // Support broken projects if necessary.
  1206. if (this->OldLinkDirItems.empty() || this->OldUserFlagItems.empty() ||
  1207. !this->OldLinkDirMode) {
  1208. return true;
  1209. }
  1210. // Enforce policy constraints.
  1211. switch (this->Target->GetPolicyStatusCMP0003()) {
  1212. case cmPolicies::WARN:
  1213. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  1214. "CMP0003-WARNING-GIVEN")) {
  1215. this->CMakeInstance->GetState()->SetGlobalProperty(
  1216. "CMP0003-WARNING-GIVEN", "1");
  1217. std::ostringstream w;
  1218. this->PrintLinkPolicyDiagnosis(w);
  1219. this->CMakeInstance->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  1220. this->Target->GetBacktrace());
  1221. }
  1222. case cmPolicies::OLD:
  1223. // OLD behavior is to add the paths containing libraries with
  1224. // known full paths as link directories.
  1225. break;
  1226. case cmPolicies::NEW:
  1227. // Should never happen due to assignment of OldLinkDirMode
  1228. return true;
  1229. case cmPolicies::REQUIRED_IF_USED:
  1230. case cmPolicies::REQUIRED_ALWAYS: {
  1231. std::ostringstream e;
  1232. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0003) << "\n";
  1233. this->PrintLinkPolicyDiagnosis(e);
  1234. this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1235. this->Target->GetBacktrace());
  1236. return false;
  1237. }
  1238. }
  1239. // Add the link directories for full path items.
  1240. for (std::string const& i : this->OldLinkDirItems) {
  1241. this->OrderLinkerSearchPath->AddLinkLibrary(i);
  1242. }
  1243. return true;
  1244. }
  1245. void cmComputeLinkInformation::PrintLinkPolicyDiagnosis(std::ostream& os)
  1246. {
  1247. // Tell the user what to do.
  1248. /* clang-format off */
  1249. os << "Policy CMP0003 should be set before this line. "
  1250. << "Add code such as\n"
  1251. << " if(COMMAND cmake_policy)\n"
  1252. << " cmake_policy(SET CMP0003 NEW)\n"
  1253. << " endif(COMMAND cmake_policy)\n"
  1254. << "as early as possible but after the most recent call to "
  1255. << "cmake_minimum_required or cmake_policy(VERSION). ";
  1256. /* clang-format on */
  1257. // List the items that might need the old-style paths.
  1258. os << "This warning appears because target \"" << this->Target->GetName()
  1259. << "\" "
  1260. << "links to some libraries for which the linker must search:\n";
  1261. {
  1262. // Format the list of unknown items to be as short as possible while
  1263. // still fitting in the allowed width (a true solution would be the
  1264. // bin packing problem if we were allowed to change the order).
  1265. std::string::size_type max_size = 76;
  1266. std::string line;
  1267. const char* sep = " ";
  1268. for (std::string const& i : this->OldUserFlagItems) {
  1269. // If the addition of another item will exceed the limit then
  1270. // output the current line and reset it. Note that the separator
  1271. // is either " " or ", " which is always 2 characters.
  1272. if (!line.empty() && (line.size() + i.size() + 2) > max_size) {
  1273. os << line << "\n";
  1274. sep = " ";
  1275. line.clear();
  1276. }
  1277. line += sep;
  1278. line += i;
  1279. // Convert to the other separator.
  1280. sep = ", ";
  1281. }
  1282. if (!line.empty()) {
  1283. os << line << "\n";
  1284. }
  1285. }
  1286. // List the paths old behavior is adding.
  1287. os << "and other libraries with known full path:\n";
  1288. std::set<std::string> emitted;
  1289. for (std::string const& i : this->OldLinkDirItems) {
  1290. if (emitted.insert(cmSystemTools::GetFilenamePath(i)).second) {
  1291. os << " " << i << "\n";
  1292. }
  1293. }
  1294. // Explain.
  1295. os << "CMake is adding directories in the second list to the linker "
  1296. << "search path in case they are needed to find libraries from the "
  1297. << "first list (for backwards compatibility with CMake 2.4). "
  1298. << "Set policy CMP0003 to OLD or NEW to enable or disable this "
  1299. << "behavior explicitly. "
  1300. << "Run \"cmake --help-policy CMP0003\" for more information.";
  1301. }
  1302. void cmComputeLinkInformation::LoadImplicitLinkInfo()
  1303. {
  1304. std::vector<std::string> implicitDirVec;
  1305. // Get platform-wide implicit directories.
  1306. if (const char* implicitLinks = (this->Makefile->GetDefinition(
  1307. "CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES"))) {
  1308. cmExpandList(implicitLinks, implicitDirVec);
  1309. }
  1310. // Append library architecture to all implicit platform directories
  1311. // and add them to the set
  1312. if (const char* libraryArch =
  1313. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  1314. for (std::string const& i : implicitDirVec) {
  1315. this->ImplicitLinkDirs.insert(i + "/" + libraryArch);
  1316. }
  1317. }
  1318. // Get language-specific implicit directories.
  1319. std::string implicitDirVar =
  1320. cmStrCat("CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_DIRECTORIES");
  1321. if (const char* implicitDirs =
  1322. this->Makefile->GetDefinition(implicitDirVar)) {
  1323. cmExpandList(implicitDirs, implicitDirVec);
  1324. }
  1325. // Store implicit link directories.
  1326. this->ImplicitLinkDirs.insert(implicitDirVec.begin(), implicitDirVec.end());
  1327. // Get language-specific implicit libraries.
  1328. std::vector<std::string> implicitLibVec;
  1329. std::string implicitLibVar =
  1330. cmStrCat("CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_LIBRARIES");
  1331. if (const char* implicitLibs =
  1332. this->Makefile->GetDefinition(implicitLibVar)) {
  1333. cmExpandList(implicitLibs, implicitLibVec);
  1334. }
  1335. // Store implicit link libraries.
  1336. for (std::string const& item : implicitLibVec) {
  1337. // Items starting in '-' but not '-l' are flags, not libraries,
  1338. // and should not be filtered by this implicit list.
  1339. if (item[0] != '-' || item[1] == 'l') {
  1340. this->ImplicitLinkLibs.insert(item);
  1341. }
  1342. }
  1343. // Get platform specific rpath link directories
  1344. if (const char* rpathDirs =
  1345. (this->Makefile->GetDefinition("CMAKE_PLATFORM_RUNTIME_PATH"))) {
  1346. cmExpandList(rpathDirs, this->RuntimeLinkDirs);
  1347. }
  1348. }
  1349. std::vector<std::string> const&
  1350. cmComputeLinkInformation::GetRuntimeSearchPath() const
  1351. {
  1352. return this->OrderRuntimeSearchPath->GetOrderedDirectories();
  1353. }
  1354. void cmComputeLinkInformation::AddLibraryRuntimeInfo(
  1355. std::string const& fullPath, cmGeneratorTarget const* target)
  1356. {
  1357. // Ignore targets on Apple where install_name is not @rpath.
  1358. // The dependenty library can be found with other means such as
  1359. // @loader_path or full paths.
  1360. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1361. if (!target->HasMacOSXRpathInstallNameDir(this->Config)) {
  1362. return;
  1363. }
  1364. }
  1365. // Libraries with unknown type must be handled using just the file
  1366. // on disk.
  1367. if (target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  1368. this->AddLibraryRuntimeInfo(fullPath);
  1369. return;
  1370. }
  1371. // Skip targets that are not shared libraries (modules cannot be linked).
  1372. if (target->GetType() != cmStateEnums::SHARED_LIBRARY) {
  1373. return;
  1374. }
  1375. // Try to get the soname of the library. Only files with this name
  1376. // could possibly conflict.
  1377. std::string soName = target->GetSOName(this->Config);
  1378. const char* soname = soName.empty() ? nullptr : soName.c_str();
  1379. // Include this library in the runtime path ordering.
  1380. this->OrderRuntimeSearchPath->AddRuntimeLibrary(fullPath, soname);
  1381. if (this->LinkWithRuntimePath) {
  1382. this->OrderLinkerSearchPath->AddRuntimeLibrary(fullPath, soname);
  1383. }
  1384. }
  1385. void cmComputeLinkInformation::AddLibraryRuntimeInfo(
  1386. std::string const& fullPath)
  1387. {
  1388. // Get the name of the library from the file name.
  1389. bool is_shared_library = false;
  1390. std::string file = cmSystemTools::GetFilenameName(fullPath);
  1391. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1392. // Check that @rpath is part of the install name.
  1393. // If it isn't, return.
  1394. std::string soname;
  1395. if (!cmSystemTools::GuessLibraryInstallName(fullPath, soname)) {
  1396. return;
  1397. }
  1398. if (soname.find("@rpath") == std::string::npos) {
  1399. return;
  1400. }
  1401. }
  1402. is_shared_library = this->ExtractSharedLibraryName.find(file);
  1403. if (!is_shared_library) {
  1404. // On some platforms (AIX) a shared library may look static.
  1405. if (this->ArchivesMayBeShared) {
  1406. if (this->ExtractStaticLibraryName.find(file)) {
  1407. // This is the name of a shared library or archive.
  1408. is_shared_library = true;
  1409. }
  1410. }
  1411. }
  1412. // It could be an Apple framework
  1413. if (!is_shared_library) {
  1414. if (fullPath.find(".framework") != std::string::npos) {
  1415. static cmsys::RegularExpression splitFramework(
  1416. "^(.*)/(.*).framework/(.*)$");
  1417. if (splitFramework.find(fullPath) &&
  1418. (std::string::npos !=
  1419. splitFramework.match(3).find(splitFramework.match(2)))) {
  1420. is_shared_library = true;
  1421. }
  1422. }
  1423. }
  1424. if (!is_shared_library) {
  1425. return;
  1426. }
  1427. // Include this library in the runtime path ordering.
  1428. this->OrderRuntimeSearchPath->AddRuntimeLibrary(fullPath);
  1429. if (this->LinkWithRuntimePath) {
  1430. this->OrderLinkerSearchPath->AddRuntimeLibrary(fullPath);
  1431. }
  1432. }
  1433. static void cmCLI_ExpandListUnique(const char* str,
  1434. std::vector<std::string>& out,
  1435. std::set<std::string>& emitted)
  1436. {
  1437. std::vector<std::string> tmp = cmExpandedList(str);
  1438. for (std::string const& i : tmp) {
  1439. if (emitted.insert(i).second) {
  1440. out.push_back(i);
  1441. }
  1442. }
  1443. }
  1444. void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs,
  1445. bool for_install) const
  1446. {
  1447. // Select whether to generate runtime search directories.
  1448. bool outputRuntime =
  1449. !this->Makefile->IsOn("CMAKE_SKIP_RPATH") && !this->RuntimeFlag.empty();
  1450. // Select whether to generate an rpath for the install tree or the
  1451. // build tree.
  1452. bool linking_for_install =
  1453. (for_install ||
  1454. this->Target->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH"));
  1455. bool use_install_rpath =
  1456. (outputRuntime && this->Target->HaveInstallTreeRPATH(this->Config) &&
  1457. linking_for_install);
  1458. bool use_build_rpath =
  1459. (outputRuntime && this->Target->HaveBuildTreeRPATH(this->Config) &&
  1460. !linking_for_install);
  1461. bool use_link_rpath = outputRuntime && linking_for_install &&
  1462. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH") &&
  1463. this->Target->GetPropertyAsBool("INSTALL_RPATH_USE_LINK_PATH");
  1464. // Select whether to use $ORIGIN in RPATHs for artifacts in the build tree.
  1465. std::string const& originToken = this->Makefile->GetSafeDefinition(
  1466. "CMAKE_SHARED_LIBRARY_RPATH_ORIGIN_TOKEN");
  1467. std::string targetOutputDir = this->Target->GetDirectory(this->Config);
  1468. bool use_relative_build_rpath =
  1469. this->Target->GetPropertyAsBool("BUILD_RPATH_USE_ORIGIN") &&
  1470. !originToken.empty() && !targetOutputDir.empty();
  1471. // Construct the RPATH.
  1472. std::set<std::string> emitted;
  1473. if (use_install_rpath) {
  1474. std::string install_rpath;
  1475. this->Target->GetInstallRPATH(this->Config, install_rpath);
  1476. cmCLI_ExpandListUnique(install_rpath.c_str(), runtimeDirs, emitted);
  1477. }
  1478. if (use_build_rpath) {
  1479. // Add directories explicitly specified by user
  1480. std::string build_rpath;
  1481. if (this->Target->GetBuildRPATH(this->Config, build_rpath)) {
  1482. // This will not resolve entries to use $ORIGIN, the user is expected to
  1483. // do that if necessary.
  1484. cmCLI_ExpandListUnique(build_rpath.c_str(), runtimeDirs, emitted);
  1485. }
  1486. }
  1487. if (use_build_rpath || use_link_rpath) {
  1488. std::string rootPath;
  1489. if (const char* sysrootLink =
  1490. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  1491. rootPath = sysrootLink;
  1492. } else {
  1493. rootPath = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  1494. }
  1495. const char* stagePath =
  1496. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX");
  1497. std::string const& installPrefix =
  1498. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
  1499. cmSystemTools::ConvertToUnixSlashes(rootPath);
  1500. std::vector<std::string> const& rdirs = this->GetRuntimeSearchPath();
  1501. std::string const& topBinaryDir =
  1502. this->CMakeInstance->GetHomeOutputDirectory();
  1503. for (std::string const& ri : rdirs) {
  1504. // Put this directory in the rpath if using build-tree rpath
  1505. // support or if using the link path as an rpath.
  1506. if (use_build_rpath) {
  1507. std::string d = ri;
  1508. if (!rootPath.empty() && d.find(rootPath) == 0) {
  1509. d = d.substr(rootPath.size());
  1510. } else if (stagePath && *stagePath && d.find(stagePath) == 0) {
  1511. std::string suffix = d.substr(strlen(stagePath));
  1512. d = cmStrCat(installPrefix, '/', suffix);
  1513. cmSystemTools::ConvertToUnixSlashes(d);
  1514. } else if (use_relative_build_rpath) {
  1515. // If expansion of the $ORIGIN token is supported and permitted per
  1516. // policy, use relative paths in the RPATH.
  1517. if (cmSystemTools::ComparePath(d, topBinaryDir) ||
  1518. cmSystemTools::IsSubDirectory(d, topBinaryDir)) {
  1519. d = cmSystemTools::RelativePath(targetOutputDir, d);
  1520. if (!d.empty()) {
  1521. d = cmStrCat(originToken, "/", d);
  1522. } else {
  1523. d = originToken;
  1524. }
  1525. }
  1526. }
  1527. if (emitted.insert(d).second) {
  1528. runtimeDirs.push_back(std::move(d));
  1529. }
  1530. } else if (use_link_rpath) {
  1531. // Do not add any path inside the source or build tree.
  1532. std::string const& topSourceDir =
  1533. this->CMakeInstance->GetHomeDirectory();
  1534. if (!cmSystemTools::ComparePath(ri, topSourceDir) &&
  1535. !cmSystemTools::ComparePath(ri, topBinaryDir) &&
  1536. !cmSystemTools::IsSubDirectory(ri, topSourceDir) &&
  1537. !cmSystemTools::IsSubDirectory(ri, topBinaryDir)) {
  1538. std::string d = ri;
  1539. if (!rootPath.empty() && d.find(rootPath) == 0) {
  1540. d = d.substr(rootPath.size());
  1541. } else if (stagePath && *stagePath && d.find(stagePath) == 0) {
  1542. std::string suffix = d.substr(strlen(stagePath));
  1543. d = cmStrCat(installPrefix, '/', suffix);
  1544. cmSystemTools::ConvertToUnixSlashes(d);
  1545. }
  1546. if (emitted.insert(d).second) {
  1547. runtimeDirs.push_back(std::move(d));
  1548. }
  1549. }
  1550. }
  1551. }
  1552. }
  1553. // Add runtime paths required by the languages to always be
  1554. // present. This is done even when skipping rpath support.
  1555. {
  1556. cmGeneratorTarget::LinkClosure const* lc =
  1557. this->Target->GetLinkClosure(this->Config);
  1558. for (std::string const& li : lc->Languages) {
  1559. std::string useVar =
  1560. "CMAKE_" + li + "_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH";
  1561. if (this->Makefile->IsOn(useVar)) {
  1562. std::string dirVar = "CMAKE_" + li + "_IMPLICIT_LINK_DIRECTORIES";
  1563. if (const char* dirs = this->Makefile->GetDefinition(dirVar)) {
  1564. cmCLI_ExpandListUnique(dirs, runtimeDirs, emitted);
  1565. }
  1566. }
  1567. }
  1568. }
  1569. // Add runtime paths required by the platform to always be
  1570. // present. This is done even when skipping rpath support.
  1571. cmCLI_ExpandListUnique(this->RuntimeAlways.c_str(), runtimeDirs, emitted);
  1572. }
  1573. std::string cmComputeLinkInformation::GetRPathString(bool for_install) const
  1574. {
  1575. // Get the directories to use.
  1576. std::vector<std::string> runtimeDirs;
  1577. this->GetRPath(runtimeDirs, for_install);
  1578. // Concatenate the paths.
  1579. std::string rpath = cmJoin(runtimeDirs, this->GetRuntimeSep());
  1580. // If the rpath will be replaced at install time, prepare space.
  1581. if (!for_install && this->RuntimeUseChrpath) {
  1582. if (!rpath.empty()) {
  1583. // Add one trailing separator so the linker does not re-use the
  1584. // rpath .dynstr entry for a symbol name that happens to match
  1585. // the end of the rpath string.
  1586. rpath += this->GetRuntimeSep();
  1587. }
  1588. // Make sure it is long enough to hold the replacement value.
  1589. std::string::size_type minLength = this->GetChrpathString().length();
  1590. while (rpath.length() < minLength) {
  1591. rpath += this->GetRuntimeSep();
  1592. }
  1593. }
  1594. return rpath;
  1595. }
  1596. std::string cmComputeLinkInformation::GetChrpathString() const
  1597. {
  1598. if (!this->RuntimeUseChrpath) {
  1599. return "";
  1600. }
  1601. return this->GetRPathString(true);
  1602. }