cmComputeLinkInformation.cxx 95 KB

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