cmComputeLinkInformation.cxx 89 KB

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