cmComputeLinkInformation.cxx 68 KB

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