cmComputeLinkInformation.cxx 68 KB

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