cmComputeLinkInformation.cxx 66 KB

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