cmComputeLinkInformation.cxx 69 KB

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