cmComputeLinkInformation.cxx 83 KB

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