cmComputeLinkInformation.cxx 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617
  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 <cm/optional>
  10. #include <cmext/algorithm>
  11. #include <cmext/string_view>
  12. #include "cmComputeLinkDepends.h"
  13. #include "cmGeneratorTarget.h"
  14. #include "cmGlobalGenerator.h"
  15. #include "cmLinkItem.h"
  16. #include "cmList.h"
  17. #include "cmListFileCache.h"
  18. #include "cmLocalGenerator.h"
  19. #include "cmMakefile.h"
  20. #include "cmMessageType.h"
  21. #include "cmOrderDirectories.h"
  22. #include "cmPlaceholderExpander.h"
  23. #include "cmPolicies.h"
  24. #include "cmSourceFile.h"
  25. #include "cmState.h"
  26. #include "cmStateTypes.h"
  27. #include "cmStringAlgorithms.h"
  28. #include "cmSystemTools.h"
  29. #include "cmTarget.h"
  30. #include "cmValue.h"
  31. #include "cmXcFramework.h"
  32. #include "cmake.h"
  33. // #define CM_COMPUTE_LINK_INFO_DEBUG
  34. /*
  35. Notes about linking on various platforms:
  36. ------------------------------------------------------------------------------
  37. Linux, FreeBSD, macOS, Sun, Windows:
  38. Linking to libraries using the full path works fine.
  39. ------------------------------------------------------------------------------
  40. On AIX, more work is needed.
  41. The "-bnoipath" option is needed. From "man ld":
  42. Note: If you specify a shared object, or an archive file
  43. containing a shared object, with an absolute or relative path
  44. name, instead of with the -lName flag, the path name is
  45. included in the import file ID string in the loader section of
  46. the output file. You can override this behavior with the
  47. -bnoipath option.
  48. noipath
  49. For shared objects listed on the command-line, rather than
  50. specified with the -l flag, use a null path component when
  51. listing the shared object in the loader section of the
  52. output file. A null path component is always used for
  53. shared objects specified with the -l flag. This option
  54. does not affect the specification of a path component by
  55. using a line beginning with #! in an import file. The
  56. default is the ipath option.
  57. This prevents the full path specified on the compile line from being
  58. compiled directly into the binary.
  59. By default the linker places -L paths in the embedded runtime path.
  60. In order to implement CMake's RPATH interface correctly, we need the
  61. -blibpath:Path option. From "man ld":
  62. libpath:Path
  63. Uses Path as the library path when writing the loader section
  64. of the output file. Path is neither checked for validity nor
  65. used when searching for libraries specified by the -l flag.
  66. Path overrides any library paths generated when the -L flag is
  67. used.
  68. If you do not specify any -L flags, or if you specify the
  69. nolibpath option, the default library path information is
  70. written in the loader section of the output file. The default
  71. library path information is the value of the LIBPATH
  72. environment variable if it is defined, and /usr/lib:/lib,
  73. otherwise.
  74. We can pass -Wl,-blibpath:/usr/lib:/lib always to avoid the -L stuff
  75. and not break when the user sets LIBPATH. Then if we want to add an
  76. rpath we insert it into the option before /usr/lib.
  77. ------------------------------------------------------------------------------
  78. On HP-UX, more work is needed. There are differences between
  79. versions.
  80. ld: 92453-07 linker linker ld B.10.33 990520
  81. Linking with a full path works okay for static and shared libraries.
  82. The linker seems to always put the full path to where the library
  83. was found in the binary whether using a full path or -lfoo syntax.
  84. Transitive link dependencies work just fine due to the full paths.
  85. It has the "-l:libfoo.sl" option. The +nodefaultrpath is accepted
  86. but not documented and does not seem to do anything. There is no
  87. +forceload option.
  88. ld: 92453-07 linker ld HP Itanium(R) B.12.41 IPF/IPF
  89. Linking with a full path works okay for static libraries.
  90. Linking with a full path works okay for shared libraries. However
  91. dependent (transitive) libraries of those linked directly must be
  92. either found with an rpath stored in the direct dependencies or
  93. found in -L paths as if they were specified with "-l:libfoo.sl"
  94. (really "-l:<soname>"). The search matches that of the dynamic
  95. loader but only with -L paths. In other words, if we have an
  96. executable that links to shared library bar which links to shared
  97. library foo, the link line for the exe must contain
  98. /dir/with/bar/libbar.sl -L/dir/with/foo
  99. It does not matter whether the exe wants to link to foo directly or
  100. whether /dir/with/foo/libfoo.sl is listed. The -L path must still
  101. be present. It should match the runtime path computed for the
  102. executable taking all directly and transitively linked libraries
  103. into account.
  104. The "+nodefaultrpath" option should be used to avoid getting -L
  105. paths in the rpath unless we add our own rpath with +b. This means
  106. that skip-build-rpath should use this option.
  107. See documentation in "man ld", "man dld.so", and
  108. http://docs.hp.com/en/B2355-90968/creatingandusinglibraries.htm
  109. +[no]defaultrpath
  110. +defaultrpath is the default. Include any paths that are
  111. specified with -L in the embedded path, unless you specify the
  112. +b option. If you use +b, only the path list specified by +b is
  113. in the embedded path.
  114. The +nodefaultrpath option removes all library paths that were
  115. specified with the -L option from the embedded path. The linker
  116. searches the library paths specified by the -L option at link
  117. time. At run time, the only library paths searched are those
  118. specified by the environment variables LD_LIBRARY_PATH and
  119. SHLIB_PATH, library paths specified by the +b linker option, and
  120. finally the default library paths.
  121. +rpathfirst
  122. This option will cause the paths specified in RPATH (embedded
  123. path) to be used before the paths specified in LD_LIBRARY_PATH
  124. or SHLIB_PATH, in searching for shared libraries. This changes
  125. the default search order of LD_LIBRARY_PATH, SHLIB_PATH, and
  126. RPATH (embedded path).
  127. ------------------------------------------------------------------------------
  128. Notes about dependent (transitive) shared libraries:
  129. On non-Windows systems shared libraries may have transitive
  130. dependencies. In order to support LINK_INTERFACE_LIBRARIES we must
  131. support linking to a shared library without listing all the libraries
  132. to which it links. Some linkers want to be able to find the
  133. transitive dependencies (dependent libraries) of shared libraries
  134. listed on the command line.
  135. - On Windows, DLLs are not directly linked, and the import libraries
  136. have no transitive dependencies.
  137. - On Mac OS X 10.5 and above transitive dependencies are not needed.
  138. - On Mac OS X 10.4 and below we need to actually list the dependencies.
  139. Otherwise when using -isysroot for universal binaries it cannot
  140. find the dependent libraries. Listing them on the command line
  141. tells the linker where to find them, but unfortunately also links
  142. the library.
  143. - On HP-UX, the linker wants to find the transitive dependencies of
  144. shared libraries in the -L paths even if the dependent libraries
  145. are given on the link line.
  146. - On AIX the transitive dependencies are not needed.
  147. - On SGI, 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. Transitive linking can be disabled using the options
  150. -no_transitive_link -Wl,-no_transitive_link
  151. which disable it. Both options must be given when invoking the
  152. linker through the compiler.
  153. - On Sun, the linker wants to find the transitive dependencies of
  154. shared libraries in the -L paths if they are not given on the link
  155. line.
  156. - On Linux, FreeBSD, and QNX:
  157. The linker wants to find the transitive dependencies of shared
  158. libraries in the "-rpath-link" paths option if they have not been
  159. given on the link line. The option is like rpath but just for
  160. link time:
  161. -Wl,-rpath-link,"/path1:/path2"
  162. For -rpath-link, we need a separate runtime path ordering pass
  163. including just the dependent libraries that are not linked.
  164. For -L paths on non-HP, we can do the same thing as with rpath-link
  165. but put the results in -L paths. The paths should be listed at the
  166. end to avoid conflicting with user search paths (?).
  167. For -L paths on HP, we should do a runtime path ordering pass with
  168. all libraries, both linked and non-linked. Even dependent
  169. libraries that are also linked need to be listed in -L paths.
  170. In our implementation we add all dependent libraries to the runtime
  171. path computation. Then the auto-generated RPATH will find everything.
  172. ------------------------------------------------------------------------------
  173. Notes about shared libraries with not builtin soname:
  174. Some UNIX shared libraries may be created with no builtin soname. On
  175. some platforms such libraries cannot be linked using the path to their
  176. location because the linker will copy the path into the field used to
  177. find the library at runtime.
  178. Apple: ../libfoo.dylib ==> libfoo.dylib # ok, uses install_name
  179. SGI: ../libfoo.so ==> libfoo.so # ok
  180. AIX: ../libfoo.so ==> libfoo.so # ok
  181. Linux: ../libfoo.so ==> ../libfoo.so # bad
  182. HP-UX: ../libfoo.so ==> ../libfoo.so # bad
  183. Sun: ../libfoo.so ==> ../libfoo.so # bad
  184. FreeBSD: ../libfoo.so ==> ../libfoo.so # bad
  185. In order to link these libraries we need to use the old-style split
  186. into -L.. and -lfoo options. This should be fairly safe because most
  187. problems with -lfoo options were related to selecting shared libraries
  188. instead of static but in this case we want the shared lib. Link
  189. directory ordering needs to be done to make sure these shared
  190. libraries are found first. There should be very few restrictions
  191. because this need be done only for shared libraries without soname-s.
  192. */
  193. cmComputeLinkInformation::cmComputeLinkInformation(
  194. const cmGeneratorTarget* target, const std::string& config)
  195. // Store context information.
  196. : Target(target)
  197. , Makefile(target->Target->GetMakefile())
  198. , GlobalGenerator(target->GetLocalGenerator()->GetGlobalGenerator())
  199. , CMakeInstance(this->GlobalGenerator->GetCMakeInstance())
  200. // The configuration being linked.
  201. , Config(config)
  202. {
  203. // Check whether to recognize OpenBSD-style library versioned names.
  204. this->OpenBSD = this->Makefile->GetState()->GetGlobalPropertyAsBool(
  205. "FIND_LIBRARY_USE_OPENBSD_VERSIONING");
  206. // Allocate internals.
  207. this->OrderLinkerSearchPath = cm::make_unique<cmOrderDirectories>(
  208. this->GlobalGenerator, target, "linker search path");
  209. this->OrderRuntimeSearchPath = cm::make_unique<cmOrderDirectories>(
  210. this->GlobalGenerator, target, "runtime search path");
  211. // Get the language used for linking this target.
  212. this->LinkLanguage = this->Target->GetLinkerLanguage(config);
  213. if (this->LinkLanguage.empty()) {
  214. // The Compute method will do nothing, so skip the rest of the
  215. // initialization.
  216. return;
  217. }
  218. // Check whether we should skip dependencies on shared library files.
  219. this->LinkDependsNoShared =
  220. this->Target->GetPropertyAsBool("LINK_DEPENDS_NO_SHARED");
  221. // On platforms without import libraries there may be a special flag
  222. // to use when creating a plugin (module) that obtains symbols from
  223. // the program that will load it.
  224. if (!this->Target->IsDLLPlatform() &&
  225. this->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
  226. std::string loader_flag_var =
  227. cmStrCat("CMAKE_SHARED_MODULE_LOADER_", this->LinkLanguage, "_FLAG");
  228. this->LoaderFlag = this->Makefile->GetDefinition(loader_flag_var);
  229. }
  230. // Get options needed to link libraries.
  231. if (cmValue flag = this->Makefile->GetDefinition(
  232. cmStrCat("CMAKE_", this->LinkLanguage, "_LINK_LIBRARY_FLAG"))) {
  233. this->LibLinkFlag = *flag;
  234. } else {
  235. this->LibLinkFlag =
  236. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FLAG");
  237. }
  238. if (cmValue flag = this->Makefile->GetDefinition(
  239. cmStrCat("CMAKE_", this->LinkLanguage, "_LINK_LIBRARY_FILE_FLAG"))) {
  240. this->LibLinkFileFlag = *flag;
  241. } else {
  242. this->LibLinkFileFlag =
  243. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FILE_FLAG");
  244. }
  245. if (cmValue suffix = this->Makefile->GetDefinition(
  246. cmStrCat("CMAKE_", this->LinkLanguage, "_LINK_LIBRARY_SUFFIX"))) {
  247. this->LibLinkSuffix = *suffix;
  248. } else {
  249. this->LibLinkSuffix =
  250. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_SUFFIX");
  251. }
  252. if (cmValue flag = this->Makefile->GetDefinition(
  253. cmStrCat("CMAKE_", this->LinkLanguage, "_LINK_OBJECT_FILE_FLAG"))) {
  254. this->ObjLinkFileFlag = *flag;
  255. } else {
  256. this->ObjLinkFileFlag =
  257. this->Makefile->GetSafeDefinition("CMAKE_LINK_OBJECT_FILE_FLAG");
  258. }
  259. // Get options needed to specify RPATHs.
  260. this->RuntimeUseChrpath = false;
  261. if (this->Target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  262. const char* tType = ((this->Target->GetType() == cmStateEnums::EXECUTABLE)
  263. ? "EXECUTABLE"
  264. : "SHARED_LIBRARY");
  265. std::string rtVar =
  266. cmStrCat("CMAKE_", tType, "_RUNTIME_", this->LinkLanguage, "_FLAG");
  267. std::string rtSepVar = cmStrCat(rtVar, "_SEP");
  268. this->RuntimeFlag = this->Makefile->GetSafeDefinition(rtVar);
  269. this->RuntimeSep = this->Makefile->GetSafeDefinition(rtSepVar);
  270. this->RuntimeAlways = (this->Makefile->GetSafeDefinition(
  271. "CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH"));
  272. this->RuntimeUseChrpath = this->Target->IsChrpathUsed(config);
  273. // Get options needed to help find dependent libraries.
  274. std::string rlVar =
  275. cmStrCat("CMAKE_", tType, "_RPATH_LINK_", this->LinkLanguage, "_FLAG");
  276. this->RPathLinkFlag = this->Makefile->GetSafeDefinition(rlVar);
  277. }
  278. // Check if we need to include the runtime search path at link time.
  279. {
  280. std::string var = cmStrCat("CMAKE_SHARED_LIBRARY_LINK_",
  281. this->LinkLanguage, "_WITH_RUNTIME_PATH");
  282. this->LinkWithRuntimePath = this->Makefile->IsOn(var);
  283. }
  284. // Define some Feature descriptors to handle standard library and object link
  285. if (!this->GetLibLinkFileFlag().empty()) {
  286. this->LibraryFeatureDescriptors.emplace(
  287. "__CMAKE_LINK_LIBRARY",
  288. LibraryFeatureDescriptor{
  289. "__CMAKE_LINK_LIBRARY",
  290. cmStrCat(this->GetLibLinkFileFlag(), "<LIBRARY>") });
  291. }
  292. if (!this->GetObjLinkFileFlag().empty()) {
  293. this->LibraryFeatureDescriptors.emplace(
  294. "__CMAKE_LINK_OBJECT",
  295. LibraryFeatureDescriptor{
  296. "__CMAKE_LINK_OBJECT",
  297. cmStrCat(this->GetObjLinkFileFlag(), "<LIBRARY>") });
  298. }
  299. if (!this->LoaderFlag->empty()) {
  300. // Define a Feature descriptor for the link of an executable with exports
  301. this->LibraryFeatureDescriptors.emplace(
  302. "__CMAKE_LINK_EXECUTABLE",
  303. LibraryFeatureDescriptor{ "__CMAKE_LINK_EXECUTABLE",
  304. cmStrCat(*this->LoaderFlag, "<LIBRARY>") });
  305. }
  306. // To link framework using a full path
  307. this->LibraryFeatureDescriptors.emplace(
  308. "__CMAKE_LINK_FRAMEWORK",
  309. LibraryFeatureDescriptor{ "__CMAKE_LINK_FRAMEWORK", "<LIBRARY>" });
  310. // To link xcframework using a full path
  311. this->LibraryFeatureDescriptors.emplace(
  312. "__CMAKE_LINK_XCFRAMEWORK",
  313. LibraryFeatureDescriptor{ "__CMAKE_LINK_XCFRAMEWORK", "<LIBRARY>" });
  314. // Check the platform policy for missing soname case.
  315. this->NoSONameUsesPath =
  316. this->Makefile->IsOn("CMAKE_PLATFORM_USES_PATH_WHEN_NO_SONAME");
  317. // Get link type information.
  318. this->ComputeLinkTypeInfo();
  319. // Setup the link item parser.
  320. this->ComputeItemParserInfo();
  321. // Setup framework support.
  322. this->ComputeFrameworkInfo();
  323. // Choose a mode for dealing with shared library dependencies.
  324. this->SharedDependencyMode = SharedDepModeNone;
  325. if (this->Makefile->IsOn("CMAKE_LINK_DEPENDENT_LIBRARY_FILES")) {
  326. this->SharedDependencyMode = SharedDepModeLink;
  327. } else if (this->Makefile->IsOn("CMAKE_LINK_DEPENDENT_LIBRARY_DIRS")) {
  328. this->SharedDependencyMode = SharedDepModeLibDir;
  329. } else if (!this->RPathLinkFlag.empty()) {
  330. this->SharedDependencyMode = SharedDepModeDir;
  331. this->OrderDependentRPath = cm::make_unique<cmOrderDirectories>(
  332. this->GlobalGenerator, target, "dependent library path");
  333. }
  334. // Add the search path entries requested by the user to path ordering.
  335. std::vector<std::string> directories;
  336. this->Target->GetLinkDirectories(directories, config, this->LinkLanguage);
  337. this->OrderLinkerSearchPath->AddUserDirectories(directories);
  338. this->OrderRuntimeSearchPath->AddUserDirectories(directories);
  339. // Set up the implicit link directories.
  340. this->LoadImplicitLinkInfo();
  341. this->OrderLinkerSearchPath->SetImplicitDirectories(this->ImplicitLinkDirs);
  342. this->OrderRuntimeSearchPath->SetImplicitDirectories(this->ImplicitLinkDirs);
  343. if (this->OrderDependentRPath) {
  344. this->OrderDependentRPath->SetImplicitDirectories(this->ImplicitLinkDirs);
  345. this->OrderDependentRPath->AddLanguageDirectories(this->RuntimeLinkDirs);
  346. }
  347. // Decide whether to enable compatible library search path mode.
  348. // There exists code that effectively does
  349. //
  350. // /path/to/libA.so -lB
  351. //
  352. // where -lB is meant to link to /path/to/libB.so. This is broken
  353. // because it specified -lB without specifying a link directory (-L)
  354. // in which to search for B. This worked in CMake 2.4 and below
  355. // because -L/path/to would be added by the -L/-l split for A. In
  356. // order to support such projects we need to add the directories
  357. // containing libraries linked with a full path to the -L path.
  358. this->OldLinkDirMode =
  359. this->Target->GetPolicyStatusCMP0003() != cmPolicies::NEW;
  360. if (this->OldLinkDirMode) {
  361. // Construct a mask to not bother with this behavior for link
  362. // directories already specified by the user.
  363. this->OldLinkDirMask.insert(directories.begin(), directories.end());
  364. }
  365. this->CMP0060Warn = this->Makefile->PolicyOptionalWarningEnabled(
  366. "CMAKE_POLICY_WARNING_CMP0060");
  367. }
  368. cmComputeLinkInformation::~cmComputeLinkInformation() = default;
  369. namespace {
  370. const std::string& DEFAULT = cmComputeLinkDepends::LinkEntry::DEFAULT;
  371. }
  372. void cmComputeLinkInformation::AppendValues(
  373. std::string& result, std::vector<BT<std::string>>& values)
  374. {
  375. for (BT<std::string>& p : values) {
  376. if (result.empty()) {
  377. result.append(" ");
  378. }
  379. result.append(p.Value);
  380. }
  381. }
  382. cmComputeLinkInformation::ItemVector const&
  383. cmComputeLinkInformation::GetItems() const
  384. {
  385. return this->Items;
  386. }
  387. std::vector<std::string> const& cmComputeLinkInformation::GetDirectories()
  388. const
  389. {
  390. return this->OrderLinkerSearchPath->GetOrderedDirectories();
  391. }
  392. std::vector<BT<std::string>>
  393. cmComputeLinkInformation::GetDirectoriesWithBacktraces()
  394. {
  395. std::vector<BT<std::string>> directoriesWithBacktraces;
  396. std::vector<BT<std::string>> targetLinkDirectores =
  397. this->Target->GetLinkDirectories(this->Config, this->LinkLanguage);
  398. const std::vector<std::string>& orderedDirectories = this->GetDirectories();
  399. for (const std::string& dir : orderedDirectories) {
  400. auto result =
  401. std::find(targetLinkDirectores.begin(), targetLinkDirectores.end(), dir);
  402. if (result != targetLinkDirectores.end()) {
  403. directoriesWithBacktraces.emplace_back(std::move(*result));
  404. } else {
  405. directoriesWithBacktraces.emplace_back(dir);
  406. }
  407. }
  408. return directoriesWithBacktraces;
  409. }
  410. std::string cmComputeLinkInformation::GetRPathLinkString() const
  411. {
  412. // If there is no separate linker runtime search flag (-rpath-link)
  413. // there is no reason to compute a string.
  414. if (!this->OrderDependentRPath) {
  415. return "";
  416. }
  417. // Construct the linker runtime search path. These MUST NOT contain tokens
  418. // such as $ORIGIN, see https://sourceware.org/bugzilla/show_bug.cgi?id=16936
  419. return cmJoin(this->OrderDependentRPath->GetOrderedDirectories(), ":");
  420. }
  421. std::vector<std::string> const& cmComputeLinkInformation::GetDepends() const
  422. {
  423. return this->Depends;
  424. }
  425. std::vector<std::string> const& cmComputeLinkInformation::GetFrameworkPaths()
  426. const
  427. {
  428. return this->FrameworkPaths;
  429. }
  430. std::set<std::string> const&
  431. cmComputeLinkInformation::GetFrameworkPathsEmitted() const
  432. {
  433. return this->FrameworkPathsEmitted;
  434. }
  435. std::vector<std::string> const&
  436. cmComputeLinkInformation::GetXcFrameworkHeaderPaths() const
  437. {
  438. return this->XcFrameworkHeaderPaths;
  439. }
  440. const std::set<const cmGeneratorTarget*>&
  441. cmComputeLinkInformation::GetSharedLibrariesLinked() const
  442. {
  443. return this->SharedLibrariesLinked;
  444. }
  445. const std::vector<const cmGeneratorTarget*>&
  446. cmComputeLinkInformation::GetExternalObjectTargets() const
  447. {
  448. return this->ExternalObjectTargets;
  449. }
  450. bool cmComputeLinkInformation::Compute()
  451. {
  452. // Skip targets that do not link or have link-like information consumers may
  453. // need (namely modules).
  454. if (!(this->Target->GetType() == cmStateEnums::EXECUTABLE ||
  455. this->Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  456. this->Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  457. this->Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  458. (this->Target->CanCompileSources() &&
  459. (this->Target->HaveCxx20ModuleSources() ||
  460. this->Target->HaveFortranSources())))) {
  461. return false;
  462. }
  463. // We require a link language for the target.
  464. if (this->LinkLanguage.empty()) {
  465. cmSystemTools::Error(
  466. "CMake can not determine linker language for target: " +
  467. this->Target->GetName());
  468. return false;
  469. }
  470. // Compute the ordered link line items.
  471. cmComputeLinkDepends cld(this->Target, this->Config, this->LinkLanguage);
  472. cld.SetOldLinkDirMode(this->OldLinkDirMode);
  473. cmComputeLinkDepends::EntryVector const& linkEntries = cld.Compute();
  474. FeatureDescriptor const* currentFeature = nullptr;
  475. // Add the link line items.
  476. for (cmComputeLinkDepends::LinkEntry const& linkEntry : linkEntries) {
  477. if (linkEntry.Kind == cmComputeLinkDepends::LinkEntry::Group) {
  478. const auto& groupFeature = this->GetGroupFeature(linkEntry.Feature);
  479. if (groupFeature.Supported) {
  480. if (linkEntry.Item.Value == "</LINK_GROUP>" &&
  481. currentFeature != nullptr) {
  482. // emit feature suffix, if any
  483. if (!currentFeature->Suffix.empty()) {
  484. this->Items.emplace_back(
  485. BT<std::string>{ currentFeature->Suffix,
  486. this->Items.back().Value.Backtrace },
  487. ItemIsPath::No);
  488. }
  489. currentFeature = nullptr;
  490. }
  491. this->Items.emplace_back(
  492. BT<std::string>{ linkEntry.Item.Value == "<LINK_GROUP>"
  493. ? groupFeature.Prefix
  494. : groupFeature.Suffix,
  495. linkEntry.Item.Backtrace },
  496. ItemIsPath::No);
  497. }
  498. continue;
  499. }
  500. if (currentFeature != nullptr &&
  501. linkEntry.Feature != currentFeature->Name) {
  502. // emit feature suffix, if any
  503. if (!currentFeature->Suffix.empty()) {
  504. this->Items.emplace_back(
  505. BT<std::string>{ currentFeature->Suffix,
  506. this->Items.back().Value.Backtrace },
  507. ItemIsPath::No);
  508. }
  509. currentFeature = nullptr;
  510. }
  511. if (linkEntry.Feature != DEFAULT &&
  512. (currentFeature == nullptr ||
  513. linkEntry.Feature != currentFeature->Name)) {
  514. if (!this->AddLibraryFeature(linkEntry.Feature)) {
  515. continue;
  516. }
  517. currentFeature = this->FindLibraryFeature(linkEntry.Feature);
  518. // emit feature prefix, if any
  519. if (!currentFeature->Prefix.empty()) {
  520. this->Items.emplace_back(
  521. BT<std::string>{ currentFeature->Prefix, linkEntry.Item.Backtrace },
  522. ItemIsPath::No);
  523. }
  524. }
  525. if (linkEntry.Kind == cmComputeLinkDepends::LinkEntry::SharedDep) {
  526. this->AddSharedDepItem(linkEntry);
  527. } else {
  528. this->AddItem(linkEntry);
  529. }
  530. }
  531. if (currentFeature != nullptr) {
  532. // emit feature suffix, if any
  533. if (!currentFeature->Suffix.empty()) {
  534. this->Items.emplace_back(
  535. BT<std::string>{ currentFeature->Suffix,
  536. this->Items.back().Value.Backtrace },
  537. ItemIsPath::No);
  538. }
  539. }
  540. // Restore the target link type so the correct system runtime
  541. // libraries are found.
  542. cmValue lss = this->Target->GetProperty("LINK_SEARCH_END_STATIC");
  543. if (cmIsOn(lss)) {
  544. this->SetCurrentLinkType(LinkStatic);
  545. } else {
  546. this->SetCurrentLinkType(this->StartLinkType);
  547. }
  548. // Finish listing compatibility paths.
  549. if (this->OldLinkDirMode) {
  550. // For CMake 2.4 bug-compatibility we need to consider the output
  551. // directories of targets linked in another configuration as link
  552. // directories.
  553. std::set<cmGeneratorTarget const*> const& wrongItems =
  554. cld.GetOldWrongConfigItems();
  555. for (cmGeneratorTarget const* tgt : wrongItems) {
  556. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(this->Config)
  557. ? cmStateEnums::ImportLibraryArtifact
  558. : cmStateEnums::RuntimeBinaryArtifact;
  559. this->OldLinkDirItems.push_back(
  560. tgt->GetFullPath(this->Config, artifact, true));
  561. }
  562. }
  563. // Finish setting up linker search directories.
  564. if (!this->FinishLinkerSearchDirectories()) {
  565. return false;
  566. }
  567. // Add implicit language runtime libraries and directories.
  568. this->AddImplicitLinkInfo();
  569. if (!this->CMP0060WarnItems.empty()) {
  570. std::ostringstream w;
  571. /* clang-format off */
  572. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0060) << "\n"
  573. "Some library files are in directories implicitly searched by "
  574. "the linker when invoked for " << this->LinkLanguage << ":\n"
  575. " " << cmJoin(this->CMP0060WarnItems, "\n ") << "\n"
  576. "For compatibility with older versions of CMake, the generated "
  577. "link line will ask the linker to search for these by library "
  578. "name."
  579. ;
  580. /* clang-format on */
  581. this->CMakeInstance->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  582. this->Target->GetBacktrace());
  583. }
  584. // Record targets referenced by $<TARGET_OBJECTS:...> sources.
  585. this->AddExternalObjectTargets();
  586. return true;
  587. }
  588. namespace {
  589. void FinalizeFeatureFormat(std::string& format, const std::string& activeTag,
  590. const std::string& otherTag)
  591. {
  592. auto pos = format.find(otherTag);
  593. if (pos != std::string::npos) {
  594. format.erase(pos, format.find('}', pos) - pos + 1);
  595. }
  596. pos = format.find(activeTag);
  597. if (pos != std::string::npos) {
  598. format.erase(pos, activeTag.length());
  599. pos = format.find('}', pos);
  600. if (pos != std::string::npos) {
  601. format.erase(pos, 1);
  602. }
  603. }
  604. }
  605. bool IsValidFeatureFormat(const std::string& format)
  606. {
  607. return format.find("<LIBRARY>") != std::string::npos ||
  608. format.find("<LIB_ITEM>") != std::string::npos ||
  609. format.find("<LINK_ITEM>") != std::string::npos;
  610. }
  611. class FeaturePlaceHolderExpander : public cmPlaceholderExpander
  612. {
  613. public:
  614. FeaturePlaceHolderExpander(const std::string* library,
  615. const std::string* libItem = nullptr,
  616. const std::string* linkItem = nullptr)
  617. : Library(library)
  618. , LibItem(libItem)
  619. , LinkItem(linkItem)
  620. {
  621. }
  622. private:
  623. std::string ExpandVariable(std::string const& variable) override
  624. {
  625. if (this->Library != nullptr && variable == "LIBRARY") {
  626. return *this->Library;
  627. }
  628. if (this->LibItem != nullptr && variable == "LIB_ITEM") {
  629. return *this->LibItem;
  630. }
  631. if (this->LinkItem != nullptr && variable == "LINK_ITEM") {
  632. return *this->LinkItem;
  633. }
  634. return variable;
  635. }
  636. const std::string* Library = nullptr;
  637. const std::string* LibItem = nullptr;
  638. const std::string* LinkItem = nullptr;
  639. };
  640. }
  641. cmComputeLinkInformation::FeatureDescriptor::FeatureDescriptor(
  642. std::string name, std::string itemFormat)
  643. : Name(std::move(name))
  644. , Supported(true)
  645. , ItemPathFormat(std::move(itemFormat))
  646. , ItemNameFormat(this->ItemPathFormat)
  647. {
  648. }
  649. cmComputeLinkInformation::FeatureDescriptor::FeatureDescriptor(
  650. std::string name, std::string itemPathFormat, std::string itemNameFormat)
  651. : Name(std::move(name))
  652. , Supported(true)
  653. , ItemPathFormat(std::move(itemPathFormat))
  654. , ItemNameFormat(std::move(itemNameFormat))
  655. {
  656. }
  657. cmComputeLinkInformation::FeatureDescriptor::FeatureDescriptor(
  658. std::string name, std::string prefix, std::string itemPathFormat,
  659. std::string itemNameFormat, std::string suffix)
  660. : Name(std::move(name))
  661. , Supported(true)
  662. , Prefix(std::move(prefix))
  663. , Suffix(std::move(suffix))
  664. , ItemPathFormat(std::move(itemPathFormat))
  665. , ItemNameFormat(std::move(itemNameFormat))
  666. {
  667. }
  668. cmComputeLinkInformation::FeatureDescriptor::FeatureDescriptor(
  669. std::string name, std::string prefix, std::string suffix, bool)
  670. : Name(std::move(name))
  671. , Supported(true)
  672. , Prefix(std::move(prefix))
  673. , Suffix(std::move(suffix))
  674. {
  675. }
  676. std::string cmComputeLinkInformation::FeatureDescriptor::GetDecoratedItem(
  677. std::string const& library, ItemIsPath isPath) const
  678. {
  679. auto format =
  680. isPath == ItemIsPath::Yes ? this->ItemPathFormat : this->ItemNameFormat;
  681. // replace <LIBRARY>, <LIB_ITEM> and <LINK_ITEM> patterns with library path
  682. FeaturePlaceHolderExpander expander(&library, &library, &library);
  683. return expander.ExpandVariables(format);
  684. }
  685. std::string cmComputeLinkInformation::FeatureDescriptor::GetDecoratedItem(
  686. std::string const& library, std::string const& libItem,
  687. std::string const& linkItem, ItemIsPath isPath) const
  688. {
  689. auto format =
  690. isPath == ItemIsPath::Yes ? this->ItemPathFormat : this->ItemNameFormat;
  691. // replace <LIBRARY>, <LIB_ITEM> and <LINK_ITEM> patterns
  692. FeaturePlaceHolderExpander expander(&library, &libItem, &linkItem);
  693. return expander.ExpandVariables(format);
  694. }
  695. cmComputeLinkInformation::LibraryFeatureDescriptor::LibraryFeatureDescriptor(
  696. std::string name, std::string itemFormat)
  697. : FeatureDescriptor(std::move(name), std::move(itemFormat))
  698. {
  699. }
  700. cmComputeLinkInformation::LibraryFeatureDescriptor::LibraryFeatureDescriptor(
  701. std::string name, std::string itemPathFormat, std::string itemNameFormat)
  702. : FeatureDescriptor(std::move(name), std::move(itemPathFormat),
  703. std::move(itemNameFormat))
  704. {
  705. }
  706. cmComputeLinkInformation::LibraryFeatureDescriptor::LibraryFeatureDescriptor(
  707. std::string name, std::string prefix, std::string itemPathFormat,
  708. std::string itemNameFormat, std::string suffix)
  709. : FeatureDescriptor(std::move(name), std::move(prefix),
  710. std::move(itemPathFormat), std::move(itemNameFormat),
  711. std::move(suffix))
  712. {
  713. }
  714. bool cmComputeLinkInformation::AddLibraryFeature(std::string const& feature)
  715. {
  716. auto it = this->LibraryFeatureDescriptors.find(feature);
  717. if (it != this->LibraryFeatureDescriptors.end()) {
  718. return it->second.Supported;
  719. }
  720. auto featureName =
  721. cmStrCat("CMAKE_", this->LinkLanguage, "_LINK_LIBRARY_USING_", feature);
  722. cmValue featureSupported =
  723. this->Makefile->GetDefinition(cmStrCat(featureName, "_SUPPORTED"));
  724. if (!featureSupported) {
  725. // language specific variable is not defined, fallback to the more generic
  726. // one
  727. featureName = cmStrCat("CMAKE_LINK_LIBRARY_USING_", feature);
  728. featureSupported =
  729. this->Makefile->GetDefinition(cmStrCat(featureName, "_SUPPORTED"));
  730. }
  731. if (!featureSupported.IsOn()) {
  732. this->LibraryFeatureDescriptors.emplace(feature, FeatureDescriptor{});
  733. this->CMakeInstance->IssueMessage(
  734. MessageType::FATAL_ERROR,
  735. cmStrCat(
  736. "Feature '", feature,
  737. "', specified through generator-expression '$<LINK_LIBRARY>' to "
  738. "link target '",
  739. this->Target->GetName(), "', is not supported for the '",
  740. this->LinkLanguage, "' link language."),
  741. this->Target->GetBacktrace());
  742. return false;
  743. }
  744. cmValue langFeature = this->Makefile->GetDefinition(featureName);
  745. if (!langFeature) {
  746. this->LibraryFeatureDescriptors.emplace(feature, FeatureDescriptor{});
  747. this->CMakeInstance->IssueMessage(
  748. MessageType::FATAL_ERROR,
  749. cmStrCat(
  750. "Feature '", feature,
  751. "', specified through generator-expression '$<LINK_LIBRARY>' to "
  752. "link target '",
  753. this->Target->GetName(), "', is not defined for the '",
  754. this->LinkLanguage, "' link language."),
  755. this->Target->GetBacktrace());
  756. return false;
  757. }
  758. auto items = cmExpandListWithBacktrace(
  759. *langFeature, this->Target->GetBacktrace(), cmList::EmptyElements::Yes);
  760. if ((items.size() == 1 && !IsValidFeatureFormat(items.front().Value)) ||
  761. (items.size() == 3 && !IsValidFeatureFormat(items[1].Value))) {
  762. this->LibraryFeatureDescriptors.emplace(feature, FeatureDescriptor{});
  763. this->CMakeInstance->IssueMessage(
  764. MessageType::FATAL_ERROR,
  765. cmStrCat("Feature '", feature, "', specified by variable '", featureName,
  766. "', is malformed (\"<LIBRARY>\", \"<LIB_ITEM>\", or "
  767. "\"<LINK_ITEM>\" patterns "
  768. "are missing) and cannot be used to link target '",
  769. this->Target->GetName(), "'."),
  770. this->Target->GetBacktrace());
  771. return false;
  772. }
  773. // now, handle possible "PATH{}" and "NAME{}" patterns
  774. if (items.size() == 1) {
  775. items.push_back(items.front());
  776. FinalizeFeatureFormat(items[0].Value, "PATH{", "NAME{");
  777. FinalizeFeatureFormat(items[1].Value, "NAME{", "PATH{");
  778. } else if (items.size() == 3) {
  779. items.insert(items.begin() + 1, items[1]);
  780. FinalizeFeatureFormat(items[1].Value, "PATH{", "NAME{");
  781. FinalizeFeatureFormat(items[2].Value, "NAME{", "PATH{");
  782. } else {
  783. this->LibraryFeatureDescriptors.emplace(feature, FeatureDescriptor{});
  784. this->CMakeInstance->IssueMessage(
  785. MessageType::FATAL_ERROR,
  786. cmStrCat("Feature '", feature, "', specified by variable '", featureName,
  787. "', is malformed (wrong number of elements) and cannot be used "
  788. "to link target '",
  789. this->Target->GetName(), "'."),
  790. this->Target->GetBacktrace());
  791. return false;
  792. }
  793. if ((items.size() == 2 && !IsValidFeatureFormat(items[0].Value)) ||
  794. (items.size() == 4 && !IsValidFeatureFormat(items[1].Value))) {
  795. // PATH{} has wrong format
  796. this->LibraryFeatureDescriptors.emplace(feature, FeatureDescriptor{});
  797. this->CMakeInstance->IssueMessage(
  798. MessageType::FATAL_ERROR,
  799. cmStrCat("Feature '", feature, "', specified by variable '", featureName,
  800. "', is malformed (\"<LIBRARY>\", \"<LIB_ITEM>\", or "
  801. "\"<LINK_ITEM>\" patterns "
  802. "are missing for \"PATH{}\" alternative) and cannot be used to "
  803. "link target '",
  804. this->Target->GetName(), "'."),
  805. this->Target->GetBacktrace());
  806. return false;
  807. }
  808. if ((items.size() == 2 && !IsValidFeatureFormat(items[1].Value)) ||
  809. (items.size() == 4 && !IsValidFeatureFormat(items[2].Value))) {
  810. // NAME{} has wrong format
  811. this->LibraryFeatureDescriptors.emplace(feature, FeatureDescriptor{});
  812. this->CMakeInstance->IssueMessage(
  813. MessageType::FATAL_ERROR,
  814. cmStrCat("Feature '", feature, "', specified by variable '", featureName,
  815. "', is malformed (\"<LIBRARY>\", \"<LIB_ITEM>\", or "
  816. "\"<LINK_ITEM>\" patterns "
  817. "are missing for \"NAME{}\" alternative) and cannot be used to "
  818. "link target '",
  819. this->Target->GetName(), "'."),
  820. this->Target->GetBacktrace());
  821. return false;
  822. }
  823. // replace LINKER: pattern
  824. this->Target->ResolveLinkerWrapper(items, this->LinkLanguage, true);
  825. if (items.size() == 2) {
  826. this->LibraryFeatureDescriptors.emplace(
  827. feature,
  828. LibraryFeatureDescriptor{ feature, items[0].Value, items[1].Value });
  829. } else {
  830. this->LibraryFeatureDescriptors.emplace(
  831. feature,
  832. LibraryFeatureDescriptor{ feature, items[0].Value, items[1].Value,
  833. items[2].Value, items[3].Value });
  834. }
  835. return true;
  836. }
  837. cmComputeLinkInformation::FeatureDescriptor const&
  838. cmComputeLinkInformation::GetLibraryFeature(std::string const& feature) const
  839. {
  840. return this->LibraryFeatureDescriptors.find(feature)->second;
  841. }
  842. cmComputeLinkInformation::FeatureDescriptor const*
  843. cmComputeLinkInformation::FindLibraryFeature(std::string const& feature) const
  844. {
  845. auto it = this->LibraryFeatureDescriptors.find(feature);
  846. if (it == this->LibraryFeatureDescriptors.end()) {
  847. return nullptr;
  848. }
  849. return &it->second;
  850. }
  851. cmComputeLinkInformation::GroupFeatureDescriptor::GroupFeatureDescriptor(
  852. std::string name, std::string prefix, std::string suffix)
  853. : FeatureDescriptor(std::move(name), std::move(prefix), std::move(suffix),
  854. true)
  855. {
  856. }
  857. cmComputeLinkInformation::FeatureDescriptor const&
  858. cmComputeLinkInformation::GetGroupFeature(std::string const& feature)
  859. {
  860. auto it = this->GroupFeatureDescriptors.find(feature);
  861. if (it != this->GroupFeatureDescriptors.end()) {
  862. return it->second;
  863. }
  864. auto featureName =
  865. cmStrCat("CMAKE_", this->LinkLanguage, "_LINK_GROUP_USING_", feature);
  866. cmValue featureSupported =
  867. this->Makefile->GetDefinition(cmStrCat(featureName, "_SUPPORTED"));
  868. if (!featureSupported) {
  869. // language specific variable is not defined, fallback to the more generic
  870. // one
  871. featureName = cmStrCat("CMAKE_LINK_GROUP_USING_", feature);
  872. featureSupported =
  873. this->Makefile->GetDefinition(cmStrCat(featureName, "_SUPPORTED"));
  874. }
  875. if (!featureSupported.IsOn()) {
  876. this->CMakeInstance->IssueMessage(
  877. MessageType::FATAL_ERROR,
  878. cmStrCat("Feature '", feature,
  879. "', specified through generator-expression '$<LINK_GROUP>' to "
  880. "link target '",
  881. this->Target->GetName(), "', is not supported for the '",
  882. this->LinkLanguage, "' link language."),
  883. this->Target->GetBacktrace());
  884. return this->GroupFeatureDescriptors.emplace(feature, FeatureDescriptor{})
  885. .first->second;
  886. }
  887. cmValue langFeature = this->Makefile->GetDefinition(featureName);
  888. if (!langFeature) {
  889. this->CMakeInstance->IssueMessage(
  890. MessageType::FATAL_ERROR,
  891. cmStrCat("Feature '", feature,
  892. "', specified through generator-expression '$<LINK_GROUP>' to "
  893. "link target '",
  894. this->Target->GetName(), "', is not defined for the '",
  895. this->LinkLanguage, "' link language."),
  896. this->Target->GetBacktrace());
  897. return this->GroupFeatureDescriptors.emplace(feature, FeatureDescriptor{})
  898. .first->second;
  899. }
  900. auto items = cmExpandListWithBacktrace(
  901. *langFeature, this->Target->GetBacktrace(), cmList::EmptyElements::Yes);
  902. // replace LINKER: pattern
  903. this->Target->ResolveLinkerWrapper(items, this->LinkLanguage, true);
  904. if (items.size() == 2) {
  905. return this->GroupFeatureDescriptors
  906. .emplace(
  907. feature,
  908. GroupFeatureDescriptor{ feature, items[0].Value, items[1].Value })
  909. .first->second;
  910. }
  911. this->CMakeInstance->IssueMessage(
  912. MessageType::FATAL_ERROR,
  913. cmStrCat("Feature '", feature, "', specified by variable '", featureName,
  914. "', is malformed (wrong number of elements) and cannot be used "
  915. "to link target '",
  916. this->Target->GetName(), "'."),
  917. this->Target->GetBacktrace());
  918. return this->GroupFeatureDescriptors.emplace(feature, FeatureDescriptor{})
  919. .first->second;
  920. }
  921. void cmComputeLinkInformation::AddExternalObjectTargets()
  922. {
  923. std::vector<cmSourceFile const*> externalObjects;
  924. this->Target->GetExternalObjects(externalObjects, this->Config);
  925. std::set<std::string> emitted;
  926. for (auto const* externalObject : externalObjects) {
  927. std::string const& objLib = externalObject->GetObjectLibrary();
  928. if (objLib.empty()) {
  929. continue;
  930. }
  931. if (emitted.insert(objLib).second) {
  932. cmLinkItem const& objItem =
  933. this->Target->ResolveLinkItem(BT<std::string>(objLib));
  934. if (objItem.Target) {
  935. this->ExternalObjectTargets.emplace_back(objItem.Target);
  936. }
  937. }
  938. }
  939. }
  940. void cmComputeLinkInformation::AddImplicitLinkInfo()
  941. {
  942. // The link closure lists all languages whose implicit info is needed.
  943. cmGeneratorTarget::LinkClosure const* lc =
  944. this->Target->GetLinkClosure(this->Config);
  945. for (std::string const& li : lc->Languages) {
  946. if (li == "CUDA" || li == "HIP") {
  947. // These need to go before the other implicit link information
  948. // as they could require symbols from those other library
  949. // Currently restricted as CUDA and HIP are the only languages
  950. // we have documented runtime behavior controls for
  951. this->AddRuntimeLinkLibrary(li);
  952. }
  953. // Skip those of the linker language. They are implicit.
  954. if (li != this->LinkLanguage) {
  955. this->AddImplicitLinkInfo(li);
  956. }
  957. }
  958. }
  959. void cmComputeLinkInformation::AddRuntimeLinkLibrary(std::string const& lang)
  960. {
  961. std::string const& runtimeLibrary =
  962. this->Target->GetRuntimeLinkLibrary(lang, this->Config);
  963. if (runtimeLibrary.empty()) {
  964. return;
  965. }
  966. if (cmValue runtimeLinkOptions = this->Makefile->GetDefinition(cmStrCat(
  967. "CMAKE_", lang, "_RUNTIME_LIBRARY_LINK_OPTIONS_", runtimeLibrary))) {
  968. cmList libs{ *runtimeLinkOptions };
  969. for (auto const& i : libs) {
  970. if (!cm::contains(this->ImplicitLinkLibs, i)) {
  971. this->AddItem({ i });
  972. }
  973. }
  974. }
  975. }
  976. void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang)
  977. {
  978. // Add libraries for this language that are not implied by the
  979. // linker language.
  980. std::string libVar = cmStrCat("CMAKE_", lang, "_IMPLICIT_LINK_LIBRARIES");
  981. if (cmValue libs = this->Makefile->GetDefinition(libVar)) {
  982. cmList libsList{ *libs };
  983. for (auto const& i : libsList) {
  984. if (!cm::contains(this->ImplicitLinkLibs, i)) {
  985. this->AddItem({ i });
  986. }
  987. }
  988. }
  989. // Add linker search paths for this language that are not
  990. // implied by the linker language.
  991. std::string dirVar = cmStrCat("CMAKE_", lang, "_IMPLICIT_LINK_DIRECTORIES");
  992. if (cmValue dirs = this->Makefile->GetDefinition(dirVar)) {
  993. cmList dirsList{ *dirs };
  994. this->OrderLinkerSearchPath->AddLanguageDirectories(dirsList);
  995. }
  996. }
  997. void cmComputeLinkInformation::AddItem(LinkEntry const& entry)
  998. {
  999. cmGeneratorTarget const* tgt = entry.Target;
  1000. BT<std::string> const& item = entry.Item;
  1001. // Compute the proper name to use to link this library.
  1002. const std::string& config = this->Config;
  1003. bool impexe = (tgt && tgt->IsExecutableWithExports());
  1004. if (impexe && !tgt->HasImportLibrary(config) && !this->LoaderFlag) {
  1005. // Skip linking to executables on platforms with no import
  1006. // libraries or loader flags.
  1007. return;
  1008. }
  1009. if (tgt && tgt->IsLinkable()) {
  1010. // This is a CMake target. Ask the target for its real name.
  1011. if (impexe && this->LoaderFlag) {
  1012. // This link item is an executable that may provide symbols
  1013. // used by this target. A special flag is needed on this
  1014. // platform. Add it now using a special feature.
  1015. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(config)
  1016. ? cmStateEnums::ImportLibraryArtifact
  1017. : cmStateEnums::RuntimeBinaryArtifact;
  1018. std::string exe = tgt->GetFullPath(config, artifact, true);
  1019. this->Items.emplace_back(
  1020. BT<std::string>(exe, item.Backtrace), ItemIsPath::Yes, tgt,
  1021. this->FindLibraryFeature(entry.Feature == DEFAULT
  1022. ? "__CMAKE_LINK_EXECUTABLE"
  1023. : entry.Feature));
  1024. this->Depends.push_back(std::move(exe));
  1025. } else if (tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1026. // Add the interface library as an item so it can be considered as part
  1027. // of COMPATIBLE_INTERFACE_ enforcement. The generators will ignore
  1028. // this for the actual link line.
  1029. this->Items.emplace_back(std::string(), ItemIsPath::No, tgt);
  1030. // Also add the item the interface specifies to be used in its place.
  1031. std::string const& libName = tgt->GetImportedLibName(config);
  1032. if (!libName.empty()) {
  1033. this->AddItem(BT<std::string>(libName, item.Backtrace));
  1034. }
  1035. } else if (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1036. this->Items.emplace_back(item, ItemIsPath::No, tgt);
  1037. } else if (this->GlobalGenerator->IsXcode() &&
  1038. !tgt->GetImportedXcFrameworkPath(config).empty()) {
  1039. this->Items.emplace_back(
  1040. tgt->GetImportedXcFrameworkPath(config), ItemIsPath::Yes, tgt,
  1041. this->FindLibraryFeature(entry.Feature == DEFAULT
  1042. ? "__CMAKE_LINK_XCFRAMEWORK"
  1043. : entry.Feature));
  1044. } else {
  1045. // Decide whether to use an import library.
  1046. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(config)
  1047. ? cmStateEnums::ImportLibraryArtifact
  1048. : cmStateEnums::RuntimeBinaryArtifact;
  1049. // Pass the full path to the target file.
  1050. BT<std::string> lib = BT<std::string>(
  1051. tgt->GetFullPath(config, artifact, true), item.Backtrace);
  1052. if (tgt->IsAIX() && cmHasLiteralSuffix(lib.Value, "-NOTFOUND") &&
  1053. artifact == cmStateEnums::ImportLibraryArtifact) {
  1054. // This is an imported executable on AIX that has ENABLE_EXPORTS
  1055. // but not IMPORTED_IMPLIB. CMake used to produce and accept such
  1056. // imported executables on AIX before we taught it to use linker
  1057. // import files. For compatibility, simply skip linking to this
  1058. // executable as we did before. It works with runtime linking.
  1059. return;
  1060. }
  1061. if (!this->LinkDependsNoShared ||
  1062. tgt->GetType() != cmStateEnums::SHARED_LIBRARY) {
  1063. this->Depends.push_back(lib.Value);
  1064. }
  1065. LinkEntry libEntry{ entry };
  1066. libEntry.Item = lib;
  1067. this->AddTargetItem(libEntry);
  1068. if (tgt->IsApple() && tgt->HasImportLibrary(config)) {
  1069. // Use the library rather than the tbd file for runpath computation
  1070. this->AddLibraryRuntimeInfo(
  1071. tgt->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact, true),
  1072. tgt);
  1073. } else {
  1074. this->AddLibraryRuntimeInfo(lib.Value, tgt);
  1075. }
  1076. if (tgt && tgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1077. this->Target->IsDLLPlatform()) {
  1078. this->AddRuntimeDLL(tgt);
  1079. }
  1080. }
  1081. auto xcFrameworkPath = tgt->GetImportedXcFrameworkPath(config);
  1082. if (!xcFrameworkPath.empty()) {
  1083. auto plist = cmParseXcFrameworkPlist(xcFrameworkPath, *this->Makefile,
  1084. item.Backtrace);
  1085. if (!plist) {
  1086. return;
  1087. }
  1088. if (auto const* library =
  1089. plist->SelectSuitableLibrary(*this->Makefile, item.Backtrace)) {
  1090. if (!library->HeadersPath.empty()) {
  1091. this->AddXcFrameworkHeaderPath(cmStrCat(xcFrameworkPath, '/',
  1092. library->LibraryIdentifier,
  1093. '/', library->HeadersPath));
  1094. }
  1095. } else {
  1096. return;
  1097. }
  1098. }
  1099. } else {
  1100. // This is not a CMake target. Use the name given.
  1101. if (cmHasSuffix(entry.Feature, "FRAMEWORK"_s) ||
  1102. (entry.Feature == DEFAULT &&
  1103. cmSystemTools::IsPathToFramework(item.Value) &&
  1104. this->Target->IsApple())) {
  1105. // This is a framework.
  1106. this->AddFrameworkItem(entry);
  1107. } else if (cmHasSuffix(entry.Feature, "XCFRAMEWORK"_s) ||
  1108. (entry.Feature == DEFAULT &&
  1109. cmSystemTools::IsPathToXcFramework(item.Value) &&
  1110. this->Target->IsApple())) {
  1111. // This is a framework.
  1112. this->AddXcFrameworkItem(entry);
  1113. } else if (cmSystemTools::FileIsFullPath(item.Value)) {
  1114. if (cmSystemTools::FileIsDirectory(item.Value)) {
  1115. // This is a directory.
  1116. this->DropDirectoryItem(item);
  1117. } else {
  1118. // Use the full path given to the library file.
  1119. this->Depends.push_back(item.Value);
  1120. this->AddFullItem(entry);
  1121. this->AddLibraryRuntimeInfo(item.Value);
  1122. }
  1123. } else if (entry.Kind != cmComputeLinkDepends::LinkEntry::Object) {
  1124. // This is a library or option specified by the user.
  1125. this->AddUserItem(entry, true);
  1126. }
  1127. }
  1128. }
  1129. void cmComputeLinkInformation::AddSharedDepItem(LinkEntry const& entry)
  1130. {
  1131. BT<std::string> const& item = entry.Item;
  1132. const cmGeneratorTarget* tgt = entry.Target;
  1133. // Record dependencies on DLLs.
  1134. if (tgt && tgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1135. this->Target->IsDLLPlatform() &&
  1136. this->SharedDependencyMode != SharedDepModeLink) {
  1137. this->AddRuntimeDLL(tgt);
  1138. }
  1139. // If dropping shared library dependencies, ignore them.
  1140. if (this->SharedDependencyMode == SharedDepModeNone) {
  1141. return;
  1142. }
  1143. // The user may have incorrectly named an item. Skip items that are
  1144. // not full paths to shared libraries.
  1145. if (tgt) {
  1146. // The target will provide a full path. Make sure it is a shared
  1147. // library.
  1148. if (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) {
  1149. return;
  1150. }
  1151. } else {
  1152. // Skip items that are not full paths. We will not be able to
  1153. // reliably specify them.
  1154. if (!cmSystemTools::FileIsFullPath(item.Value)) {
  1155. return;
  1156. }
  1157. // Get the name of the library from the file name.
  1158. std::string file = cmSystemTools::GetFilenameName(item.Value);
  1159. if (!this->ExtractSharedLibraryName.find(file)) {
  1160. // This is not the name of a shared library.
  1161. return;
  1162. }
  1163. }
  1164. // If in linking mode, just link to the shared library.
  1165. if (this->SharedDependencyMode == SharedDepModeLink) {
  1166. this->AddItem(entry);
  1167. return;
  1168. }
  1169. // Get a full path to the dependent shared library.
  1170. // Add it to the runtime path computation so that the target being
  1171. // linked will be able to find it.
  1172. std::string lib;
  1173. if (tgt) {
  1174. cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(this->Config)
  1175. ? cmStateEnums::ImportLibraryArtifact
  1176. : cmStateEnums::RuntimeBinaryArtifact;
  1177. lib = tgt->GetFullPath(this->Config, artifact);
  1178. if (tgt->IsApple() && tgt->HasImportLibrary(this->Config)) {
  1179. // Use the library rather than the tbd file for runpath computation
  1180. this->AddLibraryRuntimeInfo(
  1181. tgt->GetFullPath(this->Config, cmStateEnums::RuntimeBinaryArtifact,
  1182. true),
  1183. tgt);
  1184. } else {
  1185. this->AddLibraryRuntimeInfo(lib, tgt);
  1186. }
  1187. } else {
  1188. lib = item.Value;
  1189. this->AddLibraryRuntimeInfo(lib);
  1190. }
  1191. // Check if we need to include the dependent shared library in other
  1192. // path ordering.
  1193. cmOrderDirectories* order = nullptr;
  1194. if (this->SharedDependencyMode == SharedDepModeLibDir &&
  1195. !this->LinkWithRuntimePath /* AddLibraryRuntimeInfo adds it */) {
  1196. // Add the item to the linker search path.
  1197. order = this->OrderLinkerSearchPath.get();
  1198. } else if (this->SharedDependencyMode == SharedDepModeDir) {
  1199. // Add the item to the separate dependent library search path.
  1200. order = this->OrderDependentRPath.get();
  1201. }
  1202. if (order) {
  1203. if (tgt) {
  1204. std::string soName = tgt->GetSOName(this->Config);
  1205. const char* soname = soName.empty() ? nullptr : soName.c_str();
  1206. order->AddRuntimeLibrary(lib, soname);
  1207. } else {
  1208. order->AddRuntimeLibrary(lib);
  1209. }
  1210. }
  1211. }
  1212. void cmComputeLinkInformation::AddRuntimeDLL(cmGeneratorTarget const* tgt)
  1213. {
  1214. if (std::find(this->RuntimeDLLs.begin(), this->RuntimeDLLs.end(), tgt) ==
  1215. this->RuntimeDLLs.end()) {
  1216. this->RuntimeDLLs.emplace_back(tgt);
  1217. }
  1218. }
  1219. void cmComputeLinkInformation::ComputeLinkTypeInfo()
  1220. {
  1221. // Check whether archives may actually be shared libraries.
  1222. this->ArchivesMayBeShared =
  1223. this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  1224. "TARGET_ARCHIVES_MAY_BE_SHARED_LIBS");
  1225. // First assume we cannot do link type stuff.
  1226. this->LinkTypeEnabled = false;
  1227. // Lookup link type selection flags.
  1228. cmValue static_link_type_flag = nullptr;
  1229. cmValue shared_link_type_flag = nullptr;
  1230. const char* target_type_str = nullptr;
  1231. switch (this->Target->GetType()) {
  1232. case cmStateEnums::EXECUTABLE:
  1233. target_type_str = "EXE";
  1234. break;
  1235. case cmStateEnums::SHARED_LIBRARY:
  1236. target_type_str = "SHARED_LIBRARY";
  1237. break;
  1238. case cmStateEnums::MODULE_LIBRARY:
  1239. target_type_str = "SHARED_MODULE";
  1240. break;
  1241. default:
  1242. break;
  1243. }
  1244. if (target_type_str) {
  1245. std::string static_link_type_flag_var =
  1246. cmStrCat("CMAKE_", target_type_str, "_LINK_STATIC_", this->LinkLanguage,
  1247. "_FLAGS");
  1248. static_link_type_flag =
  1249. this->Makefile->GetDefinition(static_link_type_flag_var);
  1250. std::string shared_link_type_flag_var =
  1251. cmStrCat("CMAKE_", target_type_str, "_LINK_DYNAMIC_", this->LinkLanguage,
  1252. "_FLAGS");
  1253. shared_link_type_flag =
  1254. this->Makefile->GetDefinition(shared_link_type_flag_var);
  1255. }
  1256. // We can support link type switching only if all needed flags are
  1257. // known.
  1258. if (cmNonempty(static_link_type_flag) && cmNonempty(shared_link_type_flag)) {
  1259. this->LinkTypeEnabled = true;
  1260. this->StaticLinkTypeFlag = *static_link_type_flag;
  1261. this->SharedLinkTypeFlag = *shared_link_type_flag;
  1262. }
  1263. // Lookup the starting link type from the target (linked statically?).
  1264. cmValue lss = this->Target->GetProperty("LINK_SEARCH_START_STATIC");
  1265. this->StartLinkType = cmIsOn(lss) ? LinkStatic : LinkShared;
  1266. this->CurrentLinkType = this->StartLinkType;
  1267. }
  1268. void cmComputeLinkInformation::ComputeItemParserInfo()
  1269. {
  1270. // Get possible library name prefixes.
  1271. cmMakefile* mf = this->Makefile;
  1272. this->AddLinkPrefix(mf->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX"));
  1273. this->AddLinkPrefix(mf->GetSafeDefinition("CMAKE_SHARED_LIBRARY_PREFIX"));
  1274. // Import library names should be matched and treated as shared
  1275. // libraries for the purposes of linking.
  1276. this->AddLinkExtension(mf->GetSafeDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX"),
  1277. LinkShared);
  1278. this->AddLinkExtension(mf->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX"),
  1279. LinkStatic);
  1280. this->AddLinkExtension(mf->GetSafeDefinition("CMAKE_SHARED_LIBRARY_SUFFIX"),
  1281. LinkShared);
  1282. this->AddLinkExtension(mf->GetSafeDefinition("CMAKE_LINK_LIBRARY_SUFFIX"),
  1283. LinkUnknown);
  1284. if (cmValue linkSuffixes =
  1285. mf->GetDefinition("CMAKE_EXTRA_LINK_EXTENSIONS")) {
  1286. cmList linkSuffixList{ *linkSuffixes };
  1287. for (auto const& i : linkSuffixList) {
  1288. this->AddLinkExtension(i, LinkUnknown);
  1289. }
  1290. }
  1291. if (cmValue sharedSuffixes =
  1292. mf->GetDefinition("CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES")) {
  1293. cmList sharedSuffixList{ *sharedSuffixes };
  1294. for (std::string const& i : sharedSuffixList) {
  1295. this->AddLinkExtension(i, LinkShared);
  1296. }
  1297. }
  1298. // Compute a regex to match link extensions.
  1299. std::string libext =
  1300. this->CreateExtensionRegex(this->LinkExtensions, LinkUnknown);
  1301. // Create regex to remove any library extension.
  1302. std::string reg("(.*)");
  1303. reg += libext;
  1304. this->OrderLinkerSearchPath->SetLinkExtensionInfo(this->LinkExtensions, reg);
  1305. // Create a regex to match a library name. Match index 1 will be
  1306. // the prefix if it exists and empty otherwise. Match index 2 will
  1307. // be the library name. Match index 3 will be the library
  1308. // extension.
  1309. reg = "^(";
  1310. for (std::string const& p : this->LinkPrefixes) {
  1311. reg += p;
  1312. reg += '|';
  1313. }
  1314. reg += ")([^/:]*)";
  1315. // Create a regex to match any library name.
  1316. std::string reg_any = cmStrCat(reg, libext);
  1317. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1318. fprintf(stderr, "any regex [%s]\n", reg_any.c_str());
  1319. #endif
  1320. this->ExtractAnyLibraryName.compile(reg_any);
  1321. // Create a regex to match static library names.
  1322. if (!this->StaticLinkExtensions.empty()) {
  1323. std::string reg_static = cmStrCat(
  1324. reg, this->CreateExtensionRegex(this->StaticLinkExtensions, LinkStatic));
  1325. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1326. fprintf(stderr, "static regex [%s]\n", reg_static.c_str());
  1327. #endif
  1328. this->ExtractStaticLibraryName.compile(reg_static);
  1329. }
  1330. // Create a regex to match shared library names.
  1331. if (!this->SharedLinkExtensions.empty()) {
  1332. std::string reg_shared = reg;
  1333. this->SharedRegexString =
  1334. this->CreateExtensionRegex(this->SharedLinkExtensions, LinkShared);
  1335. reg_shared += this->SharedRegexString;
  1336. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1337. fprintf(stderr, "shared regex [%s]\n", reg_shared.c_str());
  1338. #endif
  1339. this->ExtractSharedLibraryName.compile(reg_shared);
  1340. }
  1341. }
  1342. void cmComputeLinkInformation::AddLinkPrefix(std::string const& p)
  1343. {
  1344. if (!p.empty()) {
  1345. this->LinkPrefixes.insert(p);
  1346. }
  1347. }
  1348. void cmComputeLinkInformation::AddLinkExtension(std::string const& e,
  1349. LinkType type)
  1350. {
  1351. if (!e.empty()) {
  1352. if (type == LinkStatic) {
  1353. this->StaticLinkExtensions.emplace_back(e);
  1354. }
  1355. if (type == LinkShared) {
  1356. this->SharedLinkExtensions.emplace_back(e);
  1357. }
  1358. this->LinkExtensions.emplace_back(e);
  1359. }
  1360. }
  1361. // XXX(clang-tidy): This method's const-ness is platform dependent, so we
  1362. // cannot make it `const` as `clang-tidy` wants us to.
  1363. // NOLINTNEXTLINE(readability-make-member-function-const)
  1364. std::string cmComputeLinkInformation::CreateExtensionRegex(
  1365. std::vector<std::string> const& exts, LinkType type)
  1366. {
  1367. // Build a list of extension choices.
  1368. std::string libext = "(";
  1369. const char* sep = "";
  1370. for (std::string const& i : exts) {
  1371. // Separate this choice from the previous one.
  1372. libext += sep;
  1373. sep = "|";
  1374. // Store this extension choice with the "." escaped.
  1375. libext += "\\";
  1376. #if defined(_WIN32) && !defined(__CYGWIN__)
  1377. libext += this->NoCaseExpression(i);
  1378. #else
  1379. libext += i;
  1380. #endif
  1381. }
  1382. // Finish the list.
  1383. libext += ')';
  1384. // Add an optional OpenBSD-style version or major.minor.version component.
  1385. if (this->OpenBSD || type == LinkShared) {
  1386. libext += "(\\.[0-9]+)*";
  1387. }
  1388. libext += '$';
  1389. return libext;
  1390. }
  1391. std::string cmComputeLinkInformation::NoCaseExpression(std::string const& str)
  1392. {
  1393. std::string ret;
  1394. ret.reserve(str.size() * 4);
  1395. for (char c : str) {
  1396. if (c == '.') {
  1397. ret += c;
  1398. } else {
  1399. ret += '[';
  1400. ret += static_cast<char>(tolower(c));
  1401. ret += static_cast<char>(toupper(c));
  1402. ret += ']';
  1403. }
  1404. }
  1405. return ret;
  1406. }
  1407. void cmComputeLinkInformation::SetCurrentLinkType(LinkType lt)
  1408. {
  1409. // If we are changing the current link type add the flag to tell the
  1410. // linker about it.
  1411. if (this->CurrentLinkType != lt) {
  1412. this->CurrentLinkType = lt;
  1413. if (this->LinkTypeEnabled) {
  1414. switch (this->CurrentLinkType) {
  1415. case LinkStatic:
  1416. this->Items.emplace_back(this->StaticLinkTypeFlag, ItemIsPath::No);
  1417. break;
  1418. case LinkShared:
  1419. this->Items.emplace_back(this->SharedLinkTypeFlag, ItemIsPath::No);
  1420. break;
  1421. default:
  1422. break;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. void cmComputeLinkInformation::AddTargetItem(LinkEntry const& entry)
  1428. {
  1429. // This is called to handle a link item that is a full path to a target.
  1430. // If the target is not a static library make sure the link type is
  1431. // shared. This is because dynamic-mode linking can handle both
  1432. // shared and static libraries but static-mode can handle only
  1433. // static libraries. If a previous user item changed the link type
  1434. // to static we need to make sure it is back to shared.
  1435. BT<std::string> const& item = entry.Item;
  1436. cmGeneratorTarget const* target = entry.Target;
  1437. if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
  1438. this->SetCurrentLinkType(LinkShared);
  1439. }
  1440. // Keep track of shared library targets linked.
  1441. if (target->GetType() == cmStateEnums::SHARED_LIBRARY) {
  1442. this->SharedLibrariesLinked.insert(target);
  1443. }
  1444. // Handle case of an imported shared library with no soname.
  1445. if (this->NoSONameUsesPath &&
  1446. target->IsImportedSharedLibWithoutSOName(this->Config)) {
  1447. this->AddSharedLibNoSOName(entry);
  1448. return;
  1449. }
  1450. // For compatibility with CMake 2.4 include the item's directory in
  1451. // the linker search path.
  1452. if (this->OldLinkDirMode && !target->IsFrameworkOnApple() &&
  1453. !cm::contains(this->OldLinkDirMask,
  1454. cmSystemTools::GetFilenamePath(item.Value))) {
  1455. this->OldLinkDirItems.push_back(item.Value);
  1456. }
  1457. const bool isImportedFrameworkFolderOnApple =
  1458. target->IsImportedFrameworkFolderOnApple(this->Config);
  1459. if (target->IsFrameworkOnApple() || isImportedFrameworkFolderOnApple) {
  1460. // Add the framework directory and the framework item itself
  1461. auto fwDescriptor = this->GlobalGenerator->SplitFrameworkPath(
  1462. item.Value, cmGlobalGenerator::FrameworkFormat::Extended);
  1463. if (!fwDescriptor) {
  1464. this->CMakeInstance->IssueMessage(
  1465. MessageType::FATAL_ERROR,
  1466. cmStrCat("Could not parse framework path \"", item.Value,
  1467. "\" linked by target ", this->Target->GetName(), '.'),
  1468. item.Backtrace);
  1469. return;
  1470. }
  1471. if (!fwDescriptor->Directory.empty()) {
  1472. // Add the directory portion to the framework search path.
  1473. this->AddFrameworkPath(fwDescriptor->Directory);
  1474. }
  1475. if (this->GlobalGenerator->IsXcode()) {
  1476. if (isImportedFrameworkFolderOnApple) {
  1477. if (entry.Feature == DEFAULT) {
  1478. this->AddLibraryFeature("FRAMEWORK");
  1479. this->Items.emplace_back(item, ItemIsPath::Yes, target,
  1480. this->FindLibraryFeature("FRAMEWORK"));
  1481. } else {
  1482. this->Items.emplace_back(item, ItemIsPath::Yes, target,
  1483. this->FindLibraryFeature(entry.Feature));
  1484. }
  1485. } else {
  1486. this->Items.emplace_back(
  1487. item, ItemIsPath::Yes, target,
  1488. this->FindLibraryFeature(entry.Feature == DEFAULT
  1489. ? "__CMAKE_LINK_FRAMEWORK"
  1490. : entry.Feature));
  1491. }
  1492. } else {
  1493. if (cmHasSuffix(entry.Feature, "FRAMEWORK"_s)) {
  1494. this->Items.emplace_back(fwDescriptor->GetLinkName(), ItemIsPath::Yes,
  1495. target,
  1496. this->FindLibraryFeature(entry.Feature));
  1497. } else if (entry.Feature == DEFAULT &&
  1498. isImportedFrameworkFolderOnApple) {
  1499. this->AddLibraryFeature("FRAMEWORK");
  1500. this->Items.emplace_back(fwDescriptor->GetLinkName(), ItemIsPath::Yes,
  1501. target,
  1502. this->FindLibraryFeature("FRAMEWORK"));
  1503. } else {
  1504. this->Items.emplace_back(
  1505. item, ItemIsPath::Yes, target,
  1506. this->FindLibraryFeature(entry.Feature == DEFAULT
  1507. ? "__CMAKE_LINK_LIBRARY"
  1508. : entry.Feature));
  1509. }
  1510. }
  1511. } else {
  1512. // Now add the full path to the library.
  1513. this->Items.emplace_back(
  1514. item, ItemIsPath::Yes, target,
  1515. this->FindLibraryFeature(
  1516. entry.Feature == DEFAULT ? "__CMAKE_LINK_LIBRARY" : entry.Feature));
  1517. }
  1518. }
  1519. void cmComputeLinkInformation::AddFullItem(LinkEntry const& entry)
  1520. {
  1521. BT<std::string> const& item = entry.Item;
  1522. // Check for the implicit link directory special case.
  1523. if (this->CheckImplicitDirItem(entry)) {
  1524. return;
  1525. }
  1526. // Check for case of shared library with no builtin soname.
  1527. if (this->NoSONameUsesPath && this->CheckSharedLibNoSOName(entry)) {
  1528. return;
  1529. }
  1530. // Full path libraries should specify a valid library file name.
  1531. // See documentation of CMP0008.
  1532. std::string generator = this->GlobalGenerator->GetName();
  1533. if (this->Target->GetPolicyStatusCMP0008() != cmPolicies::NEW &&
  1534. (generator.find("Visual Studio") != std::string::npos ||
  1535. generator.find("Xcode") != std::string::npos)) {
  1536. std::string file = cmSystemTools::GetFilenameName(item.Value);
  1537. if (!this->ExtractAnyLibraryName.find(file)) {
  1538. this->HandleBadFullItem(entry, file);
  1539. return;
  1540. }
  1541. }
  1542. // This is called to handle a link item that is a full path.
  1543. // If the target is not a static library make sure the link type is
  1544. // shared. This is because dynamic-mode linking can handle both
  1545. // shared and static libraries but static-mode can handle only
  1546. // static libraries. If a previous user item changed the link type
  1547. // to static we need to make sure it is back to shared.
  1548. if (this->LinkTypeEnabled) {
  1549. std::string name = cmSystemTools::GetFilenameName(item.Value);
  1550. if (this->ExtractSharedLibraryName.find(name)) {
  1551. this->SetCurrentLinkType(LinkShared);
  1552. } else if (!this->ExtractStaticLibraryName.find(item.Value)) {
  1553. // We cannot determine the type. Assume it is the target's
  1554. // default type.
  1555. this->SetCurrentLinkType(this->StartLinkType);
  1556. }
  1557. }
  1558. // For compatibility with CMake 2.4 include the item's directory in
  1559. // the linker search path.
  1560. if (this->OldLinkDirMode &&
  1561. !cm::contains(this->OldLinkDirMask,
  1562. cmSystemTools::GetFilenamePath(item.Value))) {
  1563. this->OldLinkDirItems.push_back(item.Value);
  1564. }
  1565. // Now add the full path to the library.
  1566. this->Items.emplace_back(
  1567. item, ItemIsPath::Yes, nullptr,
  1568. this->FindLibraryFeature(
  1569. entry.Feature == DEFAULT
  1570. ? (entry.Kind == cmComputeLinkDepends::LinkEntry::Object
  1571. ? "__CMAKE_LINK_OBJECT"
  1572. : "__CMAKE_LINK_LIBRARY")
  1573. : entry.Feature));
  1574. }
  1575. bool cmComputeLinkInformation::CheckImplicitDirItem(LinkEntry const& entry)
  1576. {
  1577. BT<std::string> const& item = entry.Item;
  1578. // We only switch to a pathless item if the link type may be
  1579. // enforced. Fortunately only platforms that support link types
  1580. // seem to have magic per-architecture implicit link directories.
  1581. if (!this->LinkTypeEnabled) {
  1582. return false;
  1583. }
  1584. // Check if this item is in an implicit link directory.
  1585. std::string dir = cmSystemTools::GetFilenamePath(item.Value);
  1586. if (!cm::contains(this->ImplicitLinkDirs, dir)) {
  1587. // Only libraries in implicit link directories are converted to
  1588. // pathless items.
  1589. return false;
  1590. }
  1591. // Only apply the policy below if the library file is one that can
  1592. // be found by the linker.
  1593. std::string file = cmSystemTools::GetFilenameName(item.Value);
  1594. if (!this->ExtractAnyLibraryName.find(file)) {
  1595. return false;
  1596. }
  1597. // Check the policy for whether we should use the approach below.
  1598. switch (this->Target->GetPolicyStatusCMP0060()) {
  1599. case cmPolicies::WARN:
  1600. if (this->CMP0060Warn) {
  1601. // Print the warning at most once for this item.
  1602. std::string const& wid =
  1603. cmStrCat("CMP0060-WARNING-GIVEN-", item.Value);
  1604. if (!this->CMakeInstance->GetPropertyAsBool(wid)) {
  1605. this->CMakeInstance->SetProperty(wid, "1");
  1606. this->CMP0060WarnItems.insert(item.Value);
  1607. }
  1608. }
  1609. CM_FALLTHROUGH;
  1610. case cmPolicies::OLD:
  1611. break;
  1612. case cmPolicies::REQUIRED_ALWAYS:
  1613. case cmPolicies::REQUIRED_IF_USED:
  1614. case cmPolicies::NEW:
  1615. return false;
  1616. }
  1617. // Many system linkers support multiple architectures by
  1618. // automatically selecting the implicit linker search path for the
  1619. // current architecture. If the library appears in an implicit link
  1620. // directory then just report the file name without the directory
  1621. // portion. This will allow the system linker to locate the proper
  1622. // library for the architecture at link time.
  1623. LinkEntry fileEntry{ entry };
  1624. fileEntry.Item = file;
  1625. this->AddUserItem(fileEntry, false);
  1626. // Make sure the link directory ordering will find the library.
  1627. this->OrderLinkerSearchPath->AddLinkLibrary(item.Value);
  1628. return true;
  1629. }
  1630. void cmComputeLinkInformation::AddUserItem(LinkEntry const& entry,
  1631. bool pathNotKnown)
  1632. {
  1633. // This is called to handle a link item that does not match a CMake
  1634. // target and is not a full path. We check here if it looks like a
  1635. // library file name to automatically request the proper link type
  1636. // from the linker. For example:
  1637. //
  1638. // foo ==> -lfoo
  1639. // libfoo.a ==> -Wl,-Bstatic -lfoo
  1640. BT<std::string> const& item = entry.Item;
  1641. if (item.Value[0] == '-' || item.Value[0] == '$' || item.Value[0] == '`') {
  1642. // Pass flags through untouched.
  1643. // if this is a -l option then we might need to warn about
  1644. // CMP0003 so put it in OldUserFlagItems, if it is not a -l
  1645. // or -Wl,-l (-framework -pthread), then allow it without a
  1646. // CMP0003 as -L will not affect those other linker flags
  1647. if (cmHasLiteralPrefix(item.Value, "-l") ||
  1648. cmHasLiteralPrefix(item.Value, "-Wl,-l")) {
  1649. // This is a linker option provided by the user.
  1650. this->OldUserFlagItems.push_back(item.Value);
  1651. }
  1652. // Restore the target link type since this item does not specify
  1653. // one.
  1654. this->SetCurrentLinkType(this->StartLinkType);
  1655. // Use the item verbatim.
  1656. this->Items.emplace_back(item, ItemIsPath::No);
  1657. return;
  1658. }
  1659. // Parse out the prefix, base, and suffix components of the
  1660. // library name. If the name matches that of a shared or static
  1661. // library then set the link type accordingly.
  1662. //
  1663. // Search for shared library names first because some platforms
  1664. // have shared libraries with names that match the static library
  1665. // pattern. For example cygwin and msys use the convention
  1666. // libfoo.dll.a for import libraries and libfoo.a for static
  1667. // libraries. On AIX a library with the name libfoo.a can be
  1668. // shared!
  1669. std::string lib;
  1670. if (this->ExtractSharedLibraryName.find(item.Value)) {
  1671. // This matches a shared library file name.
  1672. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1673. fprintf(stderr, "shared regex matched [%s] [%s] [%s]\n",
  1674. this->ExtractSharedLibraryName.match(1).c_str(),
  1675. this->ExtractSharedLibraryName.match(2).c_str(),
  1676. this->ExtractSharedLibraryName.match(3).c_str());
  1677. #endif
  1678. // Set the link type to shared.
  1679. this->SetCurrentLinkType(LinkShared);
  1680. // Use just the library name so the linker will search.
  1681. lib = this->ExtractSharedLibraryName.match(2);
  1682. } else if (this->ExtractStaticLibraryName.find(item.Value)) {
  1683. // This matches a static library file name.
  1684. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1685. fprintf(stderr, "static regex matched [%s] [%s] [%s]\n",
  1686. this->ExtractStaticLibraryName.match(1).c_str(),
  1687. this->ExtractStaticLibraryName.match(2).c_str(),
  1688. this->ExtractStaticLibraryName.match(3).c_str());
  1689. #endif
  1690. // Set the link type to static.
  1691. this->SetCurrentLinkType(LinkStatic);
  1692. // Use just the library name so the linker will search.
  1693. lib = this->ExtractStaticLibraryName.match(2);
  1694. } else if (this->ExtractAnyLibraryName.find(item.Value)) {
  1695. // This matches a library file name.
  1696. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  1697. fprintf(stderr, "any regex matched [%s] [%s] [%s]\n",
  1698. this->ExtractAnyLibraryName.match(1).c_str(),
  1699. this->ExtractAnyLibraryName.match(2).c_str(),
  1700. this->ExtractAnyLibraryName.match(3).c_str());
  1701. #endif
  1702. // Restore the target link type since this item does not specify
  1703. // one.
  1704. this->SetCurrentLinkType(this->StartLinkType);
  1705. // Use just the library name so the linker will search.
  1706. lib = this->ExtractAnyLibraryName.match(2);
  1707. } else {
  1708. // This is a name specified by the user.
  1709. if (pathNotKnown) {
  1710. this->OldUserFlagItems.push_back(item.Value);
  1711. }
  1712. // We must ask the linker to search for a library with this name.
  1713. // Restore the target link type since this item does not specify
  1714. // one.
  1715. this->SetCurrentLinkType(this->StartLinkType);
  1716. lib = item.Value;
  1717. }
  1718. // Create an option to ask the linker to search for the library.
  1719. auto out = cmStrCat(this->LibLinkFlag, lib, this->LibLinkSuffix);
  1720. if (entry.Feature != DEFAULT) {
  1721. auto const& feature = this->GetLibraryFeature(entry.Feature);
  1722. this->Items.emplace_back(
  1723. BT<std::string>(
  1724. feature.GetDecoratedItem(cmStrCat(lib, this->LibLinkSuffix),
  1725. item.Value, out, ItemIsPath::No),
  1726. item.Backtrace),
  1727. ItemIsPath::No);
  1728. } else {
  1729. this->Items.emplace_back(BT<std::string>(out, item.Backtrace),
  1730. ItemIsPath::No);
  1731. }
  1732. // Here we could try to find the library the linker will find and
  1733. // add a runtime information entry for it. It would probably not be
  1734. // reliable and we want to encourage use of full paths for library
  1735. // specification.
  1736. }
  1737. void cmComputeLinkInformation::AddFrameworkItem(LinkEntry const& entry)
  1738. {
  1739. std::string const& item = entry.Item.Value;
  1740. // Try to separate the framework name and path.
  1741. auto fwDescriptor = this->GlobalGenerator->SplitFrameworkPath(
  1742. item,
  1743. entry.Feature == DEFAULT ? cmGlobalGenerator::FrameworkFormat::Relaxed
  1744. : cmGlobalGenerator::FrameworkFormat::Extended);
  1745. if (!fwDescriptor) {
  1746. std::ostringstream e;
  1747. e << "Could not parse framework path \"" << item << "\" linked by target "
  1748. << this->Target->GetName() << '.';
  1749. cmSystemTools::Error(e.str());
  1750. return;
  1751. }
  1752. const std::string& fw_path = fwDescriptor->Directory;
  1753. if (!fw_path.empty()) {
  1754. // Add the directory portion to the framework search path.
  1755. this->AddFrameworkPath(fw_path);
  1756. }
  1757. // add runtime information
  1758. this->AddLibraryRuntimeInfo(fwDescriptor->GetFullPath());
  1759. if (entry.Feature == DEFAULT) {
  1760. // ensure FRAMEWORK feature is loaded
  1761. this->AddLibraryFeature("FRAMEWORK");
  1762. }
  1763. if (this->GlobalGenerator->IsXcode()) {
  1764. // Add framework path - it will be handled by Xcode after it's added to
  1765. // "Link Binary With Libraries" build phase
  1766. this->Items.emplace_back(item, ItemIsPath::Yes, nullptr,
  1767. this->FindLibraryFeature(entry.Feature == DEFAULT
  1768. ? "FRAMEWORK"
  1769. : entry.Feature));
  1770. } else {
  1771. this->Items.emplace_back(
  1772. fwDescriptor->GetLinkName(), ItemIsPath::Yes, nullptr,
  1773. this->FindLibraryFeature(entry.Feature == DEFAULT ? "FRAMEWORK"
  1774. : entry.Feature));
  1775. }
  1776. }
  1777. void cmComputeLinkInformation::AddXcFrameworkItem(LinkEntry const& entry)
  1778. {
  1779. auto plist = cmParseXcFrameworkPlist(entry.Item.Value, *this->Makefile,
  1780. entry.Item.Backtrace);
  1781. if (!plist) {
  1782. return;
  1783. }
  1784. if (auto const* lib =
  1785. plist->SelectSuitableLibrary(*this->Makefile, entry.Item.Backtrace)) {
  1786. if (this->GlobalGenerator->IsXcode()) {
  1787. this->Items.emplace_back(
  1788. entry.Item.Value, ItemIsPath::Yes, nullptr,
  1789. this->FindLibraryFeature(entry.Feature == DEFAULT
  1790. ? "__CMAKE_LINK_XCFRAMEWORK"
  1791. : entry.Feature));
  1792. } else {
  1793. auto libraryPath = cmStrCat(
  1794. entry.Item.Value, '/', lib->LibraryIdentifier, '/', lib->LibraryPath);
  1795. LinkEntry libraryEntry(
  1796. BT<std::string>(libraryPath, entry.Item.Backtrace), entry.Target);
  1797. if (cmSystemTools::IsPathToFramework(libraryPath) &&
  1798. this->Target->IsApple()) {
  1799. // This is a framework.
  1800. this->AddFrameworkItem(libraryEntry);
  1801. } else {
  1802. this->Depends.push_back(libraryPath);
  1803. this->AddFullItem(libraryEntry);
  1804. this->AddLibraryRuntimeInfo(libraryPath);
  1805. if (!lib->HeadersPath.empty()) {
  1806. this->AddXcFrameworkHeaderPath(cmStrCat(entry.Item.Value, '/',
  1807. lib->LibraryIdentifier, '/',
  1808. lib->HeadersPath));
  1809. }
  1810. }
  1811. }
  1812. }
  1813. }
  1814. void cmComputeLinkInformation::DropDirectoryItem(BT<std::string> const& item)
  1815. {
  1816. // A full path to a directory was found as a link item. Warn the
  1817. // user.
  1818. this->CMakeInstance->IssueMessage(
  1819. MessageType::WARNING,
  1820. cmStrCat("Target \"", this->Target->GetName(),
  1821. "\" requests linking to directory \"", item.Value,
  1822. "\". Targets may link only to libraries. CMake is dropping "
  1823. "the item."),
  1824. item.Backtrace);
  1825. }
  1826. void cmComputeLinkInformation::ComputeFrameworkInfo()
  1827. {
  1828. // Avoid adding implicit framework paths.
  1829. cmList implicitDirs;
  1830. // Get platform-wide implicit directories.
  1831. implicitDirs.assign(this->Makefile->GetDefinition(
  1832. "CMAKE_PLATFORM_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES"));
  1833. // Get language-specific implicit directories.
  1834. std::string implicitDirVar = cmStrCat(
  1835. "CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES");
  1836. implicitDirs.append(this->Makefile->GetDefinition(implicitDirVar));
  1837. this->FrameworkPathsEmitted.insert(implicitDirs.begin(), implicitDirs.end());
  1838. }
  1839. void cmComputeLinkInformation::AddFrameworkPath(std::string const& p)
  1840. {
  1841. if (this->FrameworkPathsEmitted.insert(p).second) {
  1842. this->FrameworkPaths.push_back(p);
  1843. }
  1844. }
  1845. void cmComputeLinkInformation::AddXcFrameworkHeaderPath(std::string const& p)
  1846. {
  1847. this->XcFrameworkHeaderPaths.push_back(p);
  1848. }
  1849. bool cmComputeLinkInformation::CheckSharedLibNoSOName(LinkEntry const& entry)
  1850. {
  1851. // This platform will use the path to a library as its soname if the
  1852. // library is given via path and was not built with an soname. If
  1853. // this is a shared library that might be the case.
  1854. std::string file = cmSystemTools::GetFilenameName(entry.Item.Value);
  1855. if (this->ExtractSharedLibraryName.find(file)) {
  1856. // If we can guess the soname fairly reliably then assume the
  1857. // library has one. Otherwise assume the library has no builtin
  1858. // soname.
  1859. std::string soname;
  1860. if (!cmSystemTools::GuessLibrarySOName(entry.Item.Value, soname)) {
  1861. this->AddSharedLibNoSOName(entry);
  1862. return true;
  1863. }
  1864. }
  1865. return false;
  1866. }
  1867. void cmComputeLinkInformation::AddSharedLibNoSOName(LinkEntry const& entry)
  1868. {
  1869. // We have a full path to a shared library with no soname. We need
  1870. // to ask the linker to locate the item because otherwise the path
  1871. // we give to it will be embedded in the target linked. Then at
  1872. // runtime the dynamic linker will search for the library using the
  1873. // path instead of just the name.
  1874. LinkEntry fileEntry{ entry };
  1875. fileEntry.Item = cmSystemTools::GetFilenameName(entry.Item.Value);
  1876. this->AddUserItem(fileEntry, false);
  1877. // Make sure the link directory ordering will find the library.
  1878. this->OrderLinkerSearchPath->AddLinkLibrary(entry.Item.Value);
  1879. }
  1880. void cmComputeLinkInformation::HandleBadFullItem(LinkEntry const& entry,
  1881. std::string const& file)
  1882. {
  1883. std::string const& item = entry.Item.Value;
  1884. // Do not depend on things that do not exist.
  1885. auto i = std::find(this->Depends.begin(), this->Depends.end(), item);
  1886. if (i != this->Depends.end()) {
  1887. this->Depends.erase(i);
  1888. }
  1889. // Tell the linker to search for the item and provide the proper
  1890. // path for it. Do not contribute to any CMP0003 warning (do not
  1891. // put in OldLinkDirItems or OldUserFlagItems).
  1892. LinkEntry fileEntry{ entry };
  1893. fileEntry.Item = file;
  1894. this->AddUserItem(fileEntry, false);
  1895. this->OrderLinkerSearchPath->AddLinkLibrary(item);
  1896. // Produce any needed message.
  1897. switch (this->Target->GetPolicyStatusCMP0008()) {
  1898. case cmPolicies::WARN: {
  1899. // Print the warning at most once for this item.
  1900. std::string wid = cmStrCat("CMP0008-WARNING-GIVEN-", item);
  1901. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(wid)) {
  1902. this->CMakeInstance->GetState()->SetGlobalProperty(wid, "1");
  1903. std::ostringstream w;
  1904. /* clang-format off */
  1905. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0008) << "\n"
  1906. "Target \"" << this->Target->GetName() << "\" links to item\n"
  1907. " " << item << "\n"
  1908. "which is a full-path but not a valid library file name.";
  1909. /* clang-format on */
  1910. this->CMakeInstance->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  1911. this->Target->GetBacktrace());
  1912. }
  1913. }
  1914. CM_FALLTHROUGH;
  1915. case cmPolicies::OLD: // NOLINT(bugprone-branch-clone)
  1916. // OLD behavior does not warn.
  1917. break;
  1918. case cmPolicies::NEW:
  1919. // NEW behavior will not get here.
  1920. break;
  1921. case cmPolicies::REQUIRED_IF_USED:
  1922. case cmPolicies::REQUIRED_ALWAYS: {
  1923. std::ostringstream e;
  1924. /* clang-format off */
  1925. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0008) << "\n"
  1926. "Target \"" << this->Target->GetName() << "\" links to item\n"
  1927. " " << item << "\n"
  1928. "which is a full-path but not a valid library file name.";
  1929. /* clang-format on */
  1930. this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1931. this->Target->GetBacktrace());
  1932. } break;
  1933. }
  1934. }
  1935. bool cmComputeLinkInformation::FinishLinkerSearchDirectories()
  1936. {
  1937. // Support broken projects if necessary.
  1938. if (this->OldLinkDirItems.empty() || this->OldUserFlagItems.empty() ||
  1939. !this->OldLinkDirMode) {
  1940. return true;
  1941. }
  1942. // Enforce policy constraints.
  1943. switch (this->Target->GetPolicyStatusCMP0003()) {
  1944. case cmPolicies::WARN:
  1945. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  1946. "CMP0003-WARNING-GIVEN")) {
  1947. this->CMakeInstance->GetState()->SetGlobalProperty(
  1948. "CMP0003-WARNING-GIVEN", "1");
  1949. std::ostringstream w;
  1950. this->PrintLinkPolicyDiagnosis(w);
  1951. this->CMakeInstance->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  1952. this->Target->GetBacktrace());
  1953. }
  1954. CM_FALLTHROUGH;
  1955. case cmPolicies::OLD:
  1956. // OLD behavior is to add the paths containing libraries with
  1957. // known full paths as link directories.
  1958. break;
  1959. case cmPolicies::NEW:
  1960. // Should never happen due to assignment of OldLinkDirMode
  1961. return true;
  1962. case cmPolicies::REQUIRED_IF_USED:
  1963. case cmPolicies::REQUIRED_ALWAYS: {
  1964. std::ostringstream e;
  1965. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0003) << '\n';
  1966. this->PrintLinkPolicyDiagnosis(e);
  1967. this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1968. this->Target->GetBacktrace());
  1969. return false;
  1970. }
  1971. }
  1972. // Add the link directories for full path items.
  1973. for (std::string const& i : this->OldLinkDirItems) {
  1974. this->OrderLinkerSearchPath->AddLinkLibrary(i);
  1975. }
  1976. return true;
  1977. }
  1978. void cmComputeLinkInformation::PrintLinkPolicyDiagnosis(std::ostream& os)
  1979. {
  1980. // Tell the user what to do.
  1981. /* clang-format off */
  1982. os << "Policy CMP0003 should be set before this line. "
  1983. "Add code such as\n"
  1984. " if(COMMAND cmake_policy)\n"
  1985. " cmake_policy(SET CMP0003 NEW)\n"
  1986. " endif(COMMAND cmake_policy)\n"
  1987. "as early as possible but after the most recent call to "
  1988. "cmake_minimum_required or cmake_policy(VERSION). ";
  1989. /* clang-format on */
  1990. // List the items that might need the old-style paths.
  1991. os << "This warning appears because target \"" << this->Target->GetName()
  1992. << "\" links to some libraries for which the linker must search:\n";
  1993. {
  1994. // Format the list of unknown items to be as short as possible while
  1995. // still fitting in the allowed width (a true solution would be the
  1996. // bin packing problem if we were allowed to change the order).
  1997. std::string::size_type max_size = 76;
  1998. std::string line;
  1999. const char* sep = " ";
  2000. for (std::string const& i : this->OldUserFlagItems) {
  2001. // If the addition of another item will exceed the limit then
  2002. // output the current line and reset it. Note that the separator
  2003. // is either " " or ", " which is always 2 characters.
  2004. if (!line.empty() && (line.size() + i.size() + 2) > max_size) {
  2005. os << line << '\n';
  2006. sep = " ";
  2007. line.clear();
  2008. }
  2009. line += sep;
  2010. line += i;
  2011. // Convert to the other separator.
  2012. sep = ", ";
  2013. }
  2014. if (!line.empty()) {
  2015. os << line << '\n';
  2016. }
  2017. }
  2018. // List the paths old behavior is adding.
  2019. os << "and other libraries with known full path:\n";
  2020. std::set<std::string> emitted;
  2021. for (std::string const& i : this->OldLinkDirItems) {
  2022. if (emitted.insert(cmSystemTools::GetFilenamePath(i)).second) {
  2023. os << " " << i << '\n';
  2024. }
  2025. }
  2026. // Explain.
  2027. os << "CMake is adding directories in the second list to the linker "
  2028. "search path in case they are needed to find libraries from the "
  2029. "first list (for backwards compatibility with CMake 2.4). "
  2030. "Set policy CMP0003 to OLD or NEW to enable or disable this "
  2031. "behavior explicitly. "
  2032. "Run \"cmake --help-policy CMP0003\" for more information.";
  2033. }
  2034. void cmComputeLinkInformation::LoadImplicitLinkInfo()
  2035. {
  2036. // Get platform-wide implicit directories.
  2037. cmList implicitDirs{ this->Makefile->GetDefinition(
  2038. "CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES") };
  2039. // Append library architecture to all implicit platform directories
  2040. // and add them to the set
  2041. if (cmValue libraryArch =
  2042. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  2043. for (auto const& i : implicitDirs) {
  2044. this->ImplicitLinkDirs.insert(cmStrCat(i, '/', *libraryArch));
  2045. }
  2046. }
  2047. // Get language-specific implicit directories.
  2048. std::string implicitDirVar =
  2049. cmStrCat("CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_DIRECTORIES");
  2050. implicitDirs.append(this->Makefile->GetDefinition(implicitDirVar));
  2051. // Store implicit link directories.
  2052. this->ImplicitLinkDirs.insert(implicitDirs.begin(), implicitDirs.end());
  2053. // Get language-specific implicit libraries.
  2054. std::string implicitLibVar =
  2055. cmStrCat("CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_LIBRARIES");
  2056. cmList implicitLibs{ this->Makefile->GetDefinition(implicitLibVar) };
  2057. // Store implicit link libraries.
  2058. for (auto const& item : implicitLibs) {
  2059. // Items starting in '-' but not '-l' are flags, not libraries,
  2060. // and should not be filtered by this implicit list.
  2061. if (item[0] != '-' || item[1] == 'l') {
  2062. this->ImplicitLinkLibs.insert(item);
  2063. }
  2064. }
  2065. // Get platform specific rpath link directories
  2066. cmList::append(this->RuntimeLinkDirs,
  2067. this->Makefile->GetDefinition("CMAKE_PLATFORM_RUNTIME_PATH"));
  2068. }
  2069. std::vector<std::string> const&
  2070. cmComputeLinkInformation::GetRuntimeSearchPath() const
  2071. {
  2072. return this->OrderRuntimeSearchPath->GetOrderedDirectories();
  2073. }
  2074. void cmComputeLinkInformation::AddLibraryRuntimeInfo(
  2075. std::string const& fullPath, cmGeneratorTarget const* target)
  2076. {
  2077. // Ignore targets on Apple where install_name is not @rpath.
  2078. // The dependenty library can be found with other means such as
  2079. // @loader_path or full paths.
  2080. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  2081. if (!target->HasMacOSXRpathInstallNameDir(this->Config)) {
  2082. return;
  2083. }
  2084. }
  2085. // Libraries with unknown type must be handled using just the file
  2086. // on disk.
  2087. if (target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  2088. this->AddLibraryRuntimeInfo(fullPath);
  2089. return;
  2090. }
  2091. // Skip targets that are not shared libraries (modules cannot be linked).
  2092. if (target->GetType() != cmStateEnums::SHARED_LIBRARY) {
  2093. return;
  2094. }
  2095. auto const* info = target->GetImportInfo(this->Config);
  2096. // Try to get the soname of the library. Only files with this name
  2097. // could possibly conflict.
  2098. const char* soname =
  2099. (!info || info->SOName.empty()) ? nullptr : info->SOName.c_str();
  2100. // If this shared library has a known runtime artifact (IMPORTED_LOCATION),
  2101. // include its location in the runtime path ordering.
  2102. if (!info || !info->Location.empty()) {
  2103. this->OrderRuntimeSearchPath->AddRuntimeLibrary(fullPath, soname);
  2104. if (this->LinkWithRuntimePath) {
  2105. this->OrderLinkerSearchPath->AddRuntimeLibrary(fullPath, soname);
  2106. }
  2107. }
  2108. }
  2109. void cmComputeLinkInformation::AddLibraryRuntimeInfo(
  2110. std::string const& fullPath)
  2111. {
  2112. // Get the name of the library from the file name.
  2113. bool is_shared_library = false;
  2114. std::string file = cmSystemTools::GetFilenameName(fullPath);
  2115. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  2116. // Check that @rpath is part of the install name.
  2117. // If it isn't, return.
  2118. std::string soname;
  2119. if (!cmSystemTools::GuessLibraryInstallName(fullPath, soname)) {
  2120. return;
  2121. }
  2122. if (soname.find("@rpath") == std::string::npos) {
  2123. return;
  2124. }
  2125. }
  2126. is_shared_library = this->ExtractSharedLibraryName.find(file);
  2127. if (!is_shared_library) {
  2128. // On some platforms (AIX) a shared library may look static.
  2129. if (this->ArchivesMayBeShared) {
  2130. if (this->ExtractStaticLibraryName.find(file)) {
  2131. // This is the name of a shared library or archive.
  2132. is_shared_library = true;
  2133. }
  2134. }
  2135. }
  2136. // It could be an Apple framework
  2137. if (!is_shared_library) {
  2138. is_shared_library =
  2139. this->GlobalGenerator
  2140. ->SplitFrameworkPath(fullPath,
  2141. cmGlobalGenerator::FrameworkFormat::Strict)
  2142. .has_value();
  2143. }
  2144. if (!is_shared_library) {
  2145. return;
  2146. }
  2147. // Include this library in the runtime path ordering.
  2148. this->OrderRuntimeSearchPath->AddRuntimeLibrary(fullPath);
  2149. if (this->LinkWithRuntimePath) {
  2150. this->OrderLinkerSearchPath->AddRuntimeLibrary(fullPath);
  2151. }
  2152. }
  2153. static void cmCLI_ExpandListUnique(std::string const& str,
  2154. std::vector<std::string>& out,
  2155. std::set<std::string>& emitted)
  2156. {
  2157. cmList tmp{ str };
  2158. for (std::string const& i : tmp) {
  2159. if (emitted.insert(i).second) {
  2160. out.push_back(i);
  2161. }
  2162. }
  2163. }
  2164. void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs,
  2165. bool for_install) const
  2166. {
  2167. // Select whether to generate runtime search directories.
  2168. bool outputRuntime =
  2169. !this->Makefile->IsOn("CMAKE_SKIP_RPATH") && !this->RuntimeFlag.empty();
  2170. // Select whether to generate an rpath for the install tree or the
  2171. // build tree.
  2172. bool linking_for_install =
  2173. (for_install ||
  2174. this->Target->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH"));
  2175. bool use_install_rpath =
  2176. (outputRuntime && this->Target->HaveInstallTreeRPATH(this->Config) &&
  2177. linking_for_install);
  2178. bool use_build_rpath =
  2179. (outputRuntime && this->Target->HaveBuildTreeRPATH(this->Config) &&
  2180. !linking_for_install);
  2181. bool use_link_rpath = outputRuntime && linking_for_install &&
  2182. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH") &&
  2183. this->Target->GetPropertyAsBool("INSTALL_RPATH_USE_LINK_PATH");
  2184. // Select whether to use $ORIGIN in RPATHs for artifacts in the build tree.
  2185. std::string const& originToken = this->Makefile->GetSafeDefinition(
  2186. "CMAKE_SHARED_LIBRARY_RPATH_ORIGIN_TOKEN");
  2187. std::string targetOutputDir = this->Target->GetDirectory(this->Config);
  2188. bool use_relative_build_rpath =
  2189. this->Target->GetPropertyAsBool("BUILD_RPATH_USE_ORIGIN") &&
  2190. !originToken.empty() && !targetOutputDir.empty();
  2191. // Construct the RPATH.
  2192. std::set<std::string> emitted;
  2193. if (use_install_rpath) {
  2194. std::string install_rpath;
  2195. this->Target->GetInstallRPATH(this->Config, install_rpath);
  2196. cmCLI_ExpandListUnique(install_rpath, runtimeDirs, emitted);
  2197. }
  2198. if (use_build_rpath) {
  2199. // Add directories explicitly specified by user
  2200. std::string build_rpath;
  2201. if (this->Target->GetBuildRPATH(this->Config, build_rpath)) {
  2202. // This will not resolve entries to use $ORIGIN, the user is expected
  2203. // to do that if necessary.
  2204. cmCLI_ExpandListUnique(build_rpath, runtimeDirs, emitted);
  2205. }
  2206. }
  2207. if (use_build_rpath || use_link_rpath) {
  2208. std::string rootPath;
  2209. if (cmValue sysrootLink =
  2210. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  2211. rootPath = *sysrootLink;
  2212. } else {
  2213. rootPath = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  2214. }
  2215. cmValue stagePath = this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX");
  2216. std::string const& installPrefix =
  2217. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
  2218. cmSystemTools::ConvertToUnixSlashes(rootPath);
  2219. std::vector<std::string> const& rdirs = this->GetRuntimeSearchPath();
  2220. std::string const& topBinaryDir =
  2221. this->CMakeInstance->GetHomeOutputDirectory();
  2222. for (std::string const& ri : rdirs) {
  2223. // Put this directory in the rpath if using build-tree rpath
  2224. // support or if using the link path as an rpath.
  2225. if (use_build_rpath) {
  2226. std::string d = ri;
  2227. if (!rootPath.empty() && cmHasPrefix(d, rootPath)) {
  2228. d.erase(0, rootPath.size());
  2229. } else if (cmNonempty(stagePath) && cmHasPrefix(d, *stagePath)) {
  2230. d.erase(0, (*stagePath).size());
  2231. d = cmStrCat(installPrefix, '/', d);
  2232. cmSystemTools::ConvertToUnixSlashes(d);
  2233. } else if (use_relative_build_rpath) {
  2234. // If expansion of the $ORIGIN token is supported and permitted per
  2235. // policy, use relative paths in the RPATH.
  2236. if (cmSystemTools::ComparePath(d, topBinaryDir) ||
  2237. cmSystemTools::IsSubDirectory(d, topBinaryDir)) {
  2238. d = cmSystemTools::RelativePath(targetOutputDir, d);
  2239. if (!d.empty()) {
  2240. d = cmStrCat(originToken, "/", d);
  2241. } else {
  2242. d = originToken;
  2243. }
  2244. }
  2245. }
  2246. if (emitted.insert(d).second) {
  2247. runtimeDirs.push_back(std::move(d));
  2248. }
  2249. } else if (use_link_rpath) {
  2250. // Do not add any path inside the source or build tree.
  2251. std::string const& topSourceDir =
  2252. this->CMakeInstance->GetHomeDirectory();
  2253. if (!cmSystemTools::ComparePath(ri, topSourceDir) &&
  2254. !cmSystemTools::ComparePath(ri, topBinaryDir) &&
  2255. !cmSystemTools::IsSubDirectory(ri, topSourceDir) &&
  2256. !cmSystemTools::IsSubDirectory(ri, topBinaryDir)) {
  2257. std::string d = ri;
  2258. if (!rootPath.empty() && cmHasPrefix(d, rootPath)) {
  2259. d.erase(0, rootPath.size());
  2260. } else if (cmNonempty(stagePath) && cmHasPrefix(d, *stagePath)) {
  2261. d.erase(0, (*stagePath).size());
  2262. d = cmStrCat(installPrefix, '/', d);
  2263. cmSystemTools::ConvertToUnixSlashes(d);
  2264. }
  2265. if (emitted.insert(d).second) {
  2266. runtimeDirs.push_back(std::move(d));
  2267. }
  2268. }
  2269. }
  2270. }
  2271. }
  2272. // Add runtime paths required by the languages to always be
  2273. // present. This is done even when skipping rpath support.
  2274. {
  2275. cmGeneratorTarget::LinkClosure const* lc =
  2276. this->Target->GetLinkClosure(this->Config);
  2277. for (std::string const& li : lc->Languages) {
  2278. std::string useVar = cmStrCat(
  2279. "CMAKE_", li, "_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH");
  2280. if (this->Makefile->IsOn(useVar)) {
  2281. std::string dirVar =
  2282. cmStrCat("CMAKE_", li, "_IMPLICIT_LINK_DIRECTORIES");
  2283. if (cmValue dirs = this->Makefile->GetDefinition(dirVar)) {
  2284. cmCLI_ExpandListUnique(*dirs, runtimeDirs, emitted);
  2285. }
  2286. }
  2287. }
  2288. }
  2289. // Add runtime paths required by the platform to always be
  2290. // present. This is done even when skipping rpath support.
  2291. cmCLI_ExpandListUnique(this->RuntimeAlways, runtimeDirs, emitted);
  2292. }
  2293. std::string cmComputeLinkInformation::GetRPathString(bool for_install) const
  2294. {
  2295. // Get the directories to use.
  2296. std::vector<std::string> runtimeDirs;
  2297. this->GetRPath(runtimeDirs, for_install);
  2298. // Concatenate the paths.
  2299. std::string rpath = cmJoin(runtimeDirs, this->GetRuntimeSep());
  2300. // If the rpath will be replaced at install time, prepare space.
  2301. if (!for_install && this->RuntimeUseChrpath) {
  2302. if (!rpath.empty()) {
  2303. // Add one trailing separator so the linker does not reuse the
  2304. // rpath .dynstr entry for a symbol name that happens to match
  2305. // the end of the rpath string.
  2306. rpath += this->GetRuntimeSep();
  2307. }
  2308. // Make sure it is long enough to hold the replacement value.
  2309. std::string::size_type minLength = this->GetChrpathString().length();
  2310. while (rpath.length() < minLength) {
  2311. rpath += this->GetRuntimeSep();
  2312. }
  2313. }
  2314. return rpath;
  2315. }
  2316. std::string cmComputeLinkInformation::GetChrpathString() const
  2317. {
  2318. if (!this->RuntimeUseChrpath) {
  2319. return "";
  2320. }
  2321. return this->GetRPathString(true);
  2322. }