cmComputeLinkInformation.cxx 85 KB

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