cmComputeLinkInformation.cxx 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmComputeLinkInformation.h"
  14. #include "cmGlobalGenerator.h"
  15. #include "cmLocalGenerator.h"
  16. #include "cmMakefile.h"
  17. #include "cmTarget.h"
  18. #include <algorithm>
  19. #include <ctype.h>
  20. /*
  21. Notes about linking on various platforms:
  22. ------------------------------------------------------------------------------
  23. Linux, FreeBSD, Mac OS X, IRIX, Sun, Windows:
  24. Linking to libraries using the full path works fine.
  25. ------------------------------------------------------------------------------
  26. On AIX, more work is needed.
  27. The "-bnoipath" option is needed. From "man ld":
  28. Note: If you specify a shared object, or an archive file
  29. containing a shared object, with an absolute or relative path
  30. name, instead of with the -lName flag, the path name is
  31. included in the import file ID string in the loader section of
  32. the output file. You can override this behavior with the
  33. -bnoipath option.
  34. noipath
  35. For shared objects listed on the command-line, rather than
  36. specified with the -l flag, use a null path component when
  37. listing the shared object in the loader section of the
  38. output file. A null path component is always used for
  39. shared objects specified with the -l flag. This option
  40. does not affect the specification of a path component by
  41. using a line beginning with #! in an import file. The
  42. default is the ipath option.
  43. This prevents the full path specified on the compile line from being
  44. compiled directly into the binary.
  45. By default the linker places -L paths in the embedded runtime path.
  46. In order to implement CMake's RPATH interface correctly, we need the
  47. -blibpath:Path option. From "man ld":
  48. libpath:Path
  49. Uses Path as the library path when writing the loader section
  50. of the output file. Path is neither checked for validity nor
  51. used when searching for libraries specified by the -l flag.
  52. Path overrides any library paths generated when the -L flag is
  53. used.
  54. If you do not specify any -L flags, or if you specify the
  55. nolibpath option, the default library path information is
  56. written in the loader section of the output file. The default
  57. library path information is the value of the LIBPATH
  58. environment variable if it is defined, and /usr/lib:/lib,
  59. otherwise.
  60. We can pass -Wl,-blibpath:/usr/lib:/lib always to avoid the -L stuff
  61. and not break when the user sets LIBPATH. Then if we want to add an
  62. rpath we insert it into the option before /usr/lib.
  63. ------------------------------------------------------------------------------
  64. On HP-UX, more work is needed. There are differences between
  65. versions.
  66. ld: 92453-07 linker linker ld B.10.33 990520
  67. Linking with a full path works okay for static and shared libraries.
  68. The linker seems to always put the full path to where the library
  69. was found in the binary whether using a full path or -lfoo syntax.
  70. Transitive link dependencies work just fine due to the full paths.
  71. It has the "-l:libfoo.sl" option. The +nodefaultrpath is accepted
  72. but not documented and does not seem to do anything. There is no
  73. +forceload option.
  74. ld: 92453-07 linker ld HP Itanium(R) B.12.41 IPF/IPF
  75. Linking with a full path works okay for static libraries.
  76. Linking with a full path works okay for shared libraries. However
  77. dependent (transitive) libraries of those linked directly must be
  78. either found with an rpath stored in the direct dependencies or
  79. found in -L paths as if they were specified with "-l:libfoo.sl"
  80. (really "-l:<soname>"). The search matches that of the dynamic
  81. loader but only with -L paths. In other words, if we have an
  82. executable that links to shared library bar which links to shared
  83. library foo, the link line for the exe must contain
  84. /dir/with/bar/libbar.sl -L/dir/with/foo
  85. It does not matter whether the exe wants to link to foo directly or
  86. whether /dir/with/foo/libfoo.sl is listed. The -L path must still
  87. be present. It should match the runtime path computed for the
  88. executable taking all directly and transitively linked libraries
  89. into account.
  90. The "+nodefaultrpath" option should be used to avoid getting -L
  91. paths in the rpath unless we add our own rpath with +b. This means
  92. that skip-build-rpath should use this option.
  93. See documentation in "man ld", "man dld.so", and
  94. http://docs.hp.com/en/B2355-90968/creatingandusinglibraries.htm
  95. +[no]defaultrpath
  96. +defaultrpath is the default. Include any paths that are
  97. specified with -L in the embedded path, unless you specify the
  98. +b option. If you use +b, only the path list specified by +b is
  99. in the embedded path.
  100. The +nodefaultrpath option removes all library paths that were
  101. specified with the -L option from the embedded path. The linker
  102. searches the library paths specified by the -L option at link
  103. time. At run time, the only library paths searched are those
  104. specified by the environment variables LD_LIBRARY_PATH and
  105. SHLIB_PATH, library paths specified by the +b linker option, and
  106. finally the default library paths.
  107. +rpathfirst
  108. This option will cause the paths specified in RPATH (embedded
  109. path) to be used before the paths specified in LD_LIBRARY_PATH
  110. or SHLIB_PATH, in searching for shared libraries. This changes
  111. the default search order of LD_LIBRARY_PATH, SHLIB_PATH, and
  112. RPATH (embedded path).
  113. */
  114. //----------------------------------------------------------------------------
  115. cmComputeLinkInformation
  116. ::cmComputeLinkInformation(cmTarget* target, const char* config)
  117. {
  118. // Store context information.
  119. this->Target = target;
  120. this->Makefile = this->Target->GetMakefile();
  121. this->LocalGenerator = this->Makefile->GetLocalGenerator();
  122. this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
  123. // The configuration being linked.
  124. this->Config = config;
  125. // Get the language used for linking this target.
  126. this->LinkLanguage =
  127. this->Target->GetLinkerLanguage(this->GlobalGenerator);
  128. // Check whether we should use an import library for linking a target.
  129. this->UseImportLibrary =
  130. this->Makefile->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")?true:false;
  131. // On platforms without import libraries there may be a special flag
  132. // to use when creating a plugin (module) that obtains symbols from
  133. // the program that will load it.
  134. this->LoaderFlag = 0;
  135. if(!this->UseImportLibrary &&
  136. this->Target->GetType() == cmTarget::MODULE_LIBRARY)
  137. {
  138. std::string loader_flag_var = "CMAKE_SHARED_MODULE_LOADER_";
  139. loader_flag_var += this->LinkLanguage;
  140. loader_flag_var += "_FLAG";
  141. this->LoaderFlag = this->Makefile->GetDefinition(loader_flag_var.c_str());
  142. }
  143. // Get options needed to link libraries.
  144. this->LibLinkFlag =
  145. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FLAG");
  146. this->LibLinkFileFlag =
  147. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FILE_FLAG");
  148. this->LibLinkSuffix =
  149. this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_SUFFIX");
  150. // Get link type information.
  151. this->ComputeLinkTypeInfo();
  152. // Setup the link item parser.
  153. this->ComputeItemParserInfo();
  154. // Setup framework support.
  155. this->ComputeFrameworkInfo();
  156. // Initial state.
  157. this->RuntimeSearchPathComputed = false;
  158. }
  159. //----------------------------------------------------------------------------
  160. cmComputeLinkInformation::ItemVector const&
  161. cmComputeLinkInformation::GetItems()
  162. {
  163. return this->Items;
  164. }
  165. //----------------------------------------------------------------------------
  166. std::vector<std::string> const& cmComputeLinkInformation::GetDirectories()
  167. {
  168. return this->Directories;
  169. }
  170. //----------------------------------------------------------------------------
  171. std::vector<std::string> const& cmComputeLinkInformation::GetDepends()
  172. {
  173. return this->Depends;
  174. }
  175. //----------------------------------------------------------------------------
  176. std::vector<std::string> const& cmComputeLinkInformation::GetFrameworkPaths()
  177. {
  178. return this->FrameworkPaths;
  179. }
  180. //----------------------------------------------------------------------------
  181. bool cmComputeLinkInformation::Compute()
  182. {
  183. // Skip targets that do not link.
  184. if(!(this->Target->GetType() == cmTarget::EXECUTABLE ||
  185. this->Target->GetType() == cmTarget::SHARED_LIBRARY ||
  186. this->Target->GetType() == cmTarget::MODULE_LIBRARY ||
  187. this->Target->GetType() == cmTarget::STATIC_LIBRARY))
  188. {
  189. return false;
  190. }
  191. // We require a link language for the target.
  192. if(!this->LinkLanguage)
  193. {
  194. cmSystemTools::
  195. Error("CMake can not determine linker language for target:",
  196. this->Target->GetName());
  197. return false;
  198. }
  199. // Compute which library configuration to link.
  200. cmTarget::LinkLibraryType linkType = cmTarget::OPTIMIZED;
  201. if(this->Config && cmSystemTools::UpperCase(this->Config) == "DEBUG")
  202. {
  203. linkType = cmTarget::DEBUG;
  204. }
  205. // Get the list of libraries against which this target wants to link.
  206. {
  207. const cmTarget::LinkLibraryVectorType& libs =
  208. this->Target->GetLinkLibraries();
  209. for(cmTarget::LinkLibraryVectorType::const_iterator li = libs.begin();
  210. li != libs.end(); ++li)
  211. {
  212. // Link to a library if it is not the same target and is meant for
  213. // this configuration type.
  214. if((this->Target->GetType() == cmTarget::EXECUTABLE ||
  215. li->first != this->Target->GetName()) &&
  216. (li->second == cmTarget::GENERAL || li->second == linkType))
  217. {
  218. this->AddItem(li->first);
  219. }
  220. }
  221. }
  222. // Restore the target link type so the correct system runtime
  223. // libraries are found.
  224. this->SetCurrentLinkType(this->StartLinkType);
  225. // Compute the linker search path.
  226. this->ComputeLinkerSearchDirectories();
  227. return true;
  228. }
  229. //----------------------------------------------------------------------------
  230. void cmComputeLinkInformation::AddItem(std::string const& item)
  231. {
  232. // Compute the proper name to use to link this library.
  233. // TODO: Change third argument to support imported libraries.
  234. cmTarget* tgt = this->GlobalGenerator->FindTarget(0, item.c_str(), false);
  235. const char* config = this->Config;
  236. bool implib = this->UseImportLibrary;
  237. bool impexe = (tgt &&
  238. tgt->GetType() == cmTarget::EXECUTABLE &&
  239. tgt->GetPropertyAsBool("ENABLE_EXPORTS"));
  240. if(impexe && !implib && !this->LoaderFlag)
  241. {
  242. // Skip linking to executables on platforms with no import
  243. // libraries or loader flags.
  244. return;
  245. }
  246. if(tgt && (tgt->GetType() == cmTarget::STATIC_LIBRARY ||
  247. tgt->GetType() == cmTarget::SHARED_LIBRARY ||
  248. tgt->GetType() == cmTarget::MODULE_LIBRARY ||
  249. impexe))
  250. {
  251. // This is a CMake target. Ask the target for its real name.
  252. if(impexe && this->LoaderFlag)
  253. {
  254. // This link item is an executable that may provide symbols
  255. // used by this target. A special flag is needed on this
  256. // platform. Add it now.
  257. std::string linkItem;
  258. linkItem = this->LoaderFlag;
  259. std::string exe = tgt->GetFullPath(config, implib);
  260. linkItem += exe;
  261. this->Items.push_back(Item(linkItem, true));
  262. this->Depends.push_back(exe);
  263. }
  264. else
  265. {
  266. // Pass the full path to the target file.
  267. std::string lib = tgt->GetFullPath(config, implib);
  268. this->Depends.push_back(lib);
  269. #ifdef __APPLE__
  270. if(tgt->GetType() == cmTarget::SHARED_LIBRARY &&
  271. tgt->GetPropertyAsBool("FRAMEWORK"))
  272. {
  273. // Frameworks on OS X need only the framework directory to
  274. // link.
  275. std::string fw = tgt->GetDirectory(config, implib);
  276. this->AddFrameworkItem(fw);
  277. }
  278. else
  279. #endif
  280. {
  281. this->AddTargetItem(lib, tgt);
  282. this->AddLibraryRuntimeInfo(lib, tgt);
  283. }
  284. }
  285. }
  286. else
  287. {
  288. // This is not a CMake target. Use the name given.
  289. if(cmSystemTools::FileIsFullPath(item.c_str()))
  290. {
  291. if(cmSystemTools::FileIsDirectory(item.c_str()))
  292. {
  293. // This is a directory.
  294. this->AddDirectoryItem(item);
  295. }
  296. else
  297. {
  298. // Use the full path given to the library file.
  299. this->Depends.push_back(item);
  300. this->AddFullItem(item);
  301. this->AddLibraryRuntimeInfo(item);
  302. }
  303. }
  304. else
  305. {
  306. // This is a library or option specified by the user.
  307. this->AddUserItem(item);
  308. }
  309. }
  310. }
  311. //----------------------------------------------------------------------------
  312. void cmComputeLinkInformation::ComputeLinkTypeInfo()
  313. {
  314. // First assume we cannot do link type stuff.
  315. this->LinkTypeEnabled = false;
  316. // Lookup link type selection flags.
  317. const char* static_link_type_flag = 0;
  318. const char* shared_link_type_flag = 0;
  319. const char* target_type_str = 0;
  320. switch(this->Target->GetType())
  321. {
  322. case cmTarget::EXECUTABLE: target_type_str = "EXE"; break;
  323. case cmTarget::SHARED_LIBRARY: target_type_str = "SHARED_LIBRARY"; break;
  324. case cmTarget::MODULE_LIBRARY: target_type_str = "SHARED_MODULE"; break;
  325. default: break;
  326. }
  327. if(target_type_str)
  328. {
  329. std::string static_link_type_flag_var = "CMAKE_";
  330. static_link_type_flag_var += target_type_str;
  331. static_link_type_flag_var += "_LINK_STATIC_";
  332. static_link_type_flag_var += this->LinkLanguage;
  333. static_link_type_flag_var += "_FLAGS";
  334. static_link_type_flag =
  335. this->Makefile->GetDefinition(static_link_type_flag_var.c_str());
  336. std::string shared_link_type_flag_var = "CMAKE_";
  337. shared_link_type_flag_var += target_type_str;
  338. shared_link_type_flag_var += "_LINK_DYNAMIC_";
  339. shared_link_type_flag_var += this->LinkLanguage;
  340. shared_link_type_flag_var += "_FLAGS";
  341. shared_link_type_flag =
  342. this->Makefile->GetDefinition(shared_link_type_flag_var.c_str());
  343. }
  344. // We can support link type switching only if all needed flags are
  345. // known.
  346. if(static_link_type_flag && *static_link_type_flag &&
  347. shared_link_type_flag && *shared_link_type_flag)
  348. {
  349. this->LinkTypeEnabled = true;
  350. this->StaticLinkTypeFlag = static_link_type_flag;
  351. this->SharedLinkTypeFlag = shared_link_type_flag;
  352. }
  353. // TODO: Lookup the starting link type from the target (is it being
  354. // linked statically?).
  355. this->StartLinkType = LinkShared;
  356. this->CurrentLinkType = this->StartLinkType;
  357. }
  358. //----------------------------------------------------------------------------
  359. void cmComputeLinkInformation::ComputeItemParserInfo()
  360. {
  361. // Get possible library name prefixes.
  362. cmMakefile* mf = this->Makefile;
  363. this->AddLinkPrefix(mf->GetDefinition("CMAKE_STATIC_LIBRARY_PREFIX"));
  364. this->AddLinkPrefix(mf->GetDefinition("CMAKE_SHARED_LIBRARY_PREFIX"));
  365. // Import library names should be matched and treated as shared
  366. // libraries for the purposes of linking.
  367. this->AddLinkExtension(mf->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX"),
  368. LinkShared);
  369. this->AddLinkExtension(mf->GetDefinition("CMAKE_STATIC_LIBRARY_SUFFIX"),
  370. LinkStatic);
  371. this->AddLinkExtension(mf->GetDefinition("CMAKE_SHARED_LIBRARY_SUFFIX"),
  372. LinkShared);
  373. this->AddLinkExtension(mf->GetDefinition("CMAKE_LINK_LIBRARY_SUFFIX"),
  374. LinkUnknown);
  375. if(const char* linkSuffixes =
  376. mf->GetDefinition("CMAKE_EXTRA_LINK_EXTENSIONS"))
  377. {
  378. std::vector<std::string> linkSuffixVec;
  379. cmSystemTools::ExpandListArgument(linkSuffixes, linkSuffixVec);
  380. for(std::vector<std::string>::iterator i = linkSuffixVec.begin();
  381. i != linkSuffixVec.end(); ++i)
  382. {
  383. this->AddLinkExtension(i->c_str(), LinkUnknown);
  384. }
  385. }
  386. // Compute a regex to match link extensions.
  387. std::string libext = this->CreateExtensionRegex(this->LinkExtensions);
  388. // Create regex to remove any library extension.
  389. std::string reg("(.*)");
  390. reg += libext;
  391. this->RemoveLibraryExtension.compile(reg.c_str());
  392. // Create a regex to match a library name. Match index 1 will be
  393. // the prefix if it exists and empty otherwise. Match index 2 will
  394. // be the library name. Match index 3 will be the library
  395. // extension.
  396. reg = "^(";
  397. for(std::set<cmStdString>::iterator p = this->LinkPrefixes.begin();
  398. p != this->LinkPrefixes.end(); ++p)
  399. {
  400. reg += *p;
  401. reg += "|";
  402. }
  403. reg += ")";
  404. reg += "([^/]*)";
  405. // Create a regex to match any library name.
  406. std::string reg_any = reg;
  407. reg_any += libext;
  408. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  409. fprintf(stderr, "any regex [%s]\n", reg_any.c_str());
  410. #endif
  411. this->ExtractAnyLibraryName.compile(reg_any.c_str());
  412. // Create a regex to match static library names.
  413. if(!this->StaticLinkExtensions.empty())
  414. {
  415. std::string reg_static = reg;
  416. reg_static += this->CreateExtensionRegex(this->StaticLinkExtensions);
  417. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  418. fprintf(stderr, "static regex [%s]\n", reg_static.c_str());
  419. #endif
  420. this->ExtractStaticLibraryName.compile(reg_static.c_str());
  421. }
  422. // Create a regex to match shared library names.
  423. if(!this->SharedLinkExtensions.empty())
  424. {
  425. std::string reg_shared = reg;
  426. reg_shared += this->CreateExtensionRegex(this->SharedLinkExtensions);
  427. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  428. fprintf(stderr, "shared regex [%s]\n", reg_shared.c_str());
  429. #endif
  430. this->ExtractSharedLibraryName.compile(reg_shared.c_str());
  431. }
  432. }
  433. //----------------------------------------------------------------------------
  434. void cmComputeLinkInformation::AddLinkPrefix(const char* p)
  435. {
  436. if(p)
  437. {
  438. this->LinkPrefixes.insert(p);
  439. }
  440. }
  441. //----------------------------------------------------------------------------
  442. void cmComputeLinkInformation::AddLinkExtension(const char* e, LinkType type)
  443. {
  444. if(e && *e)
  445. {
  446. if(type == LinkStatic)
  447. {
  448. this->StaticLinkExtensions.push_back(e);
  449. }
  450. if(type == LinkShared)
  451. {
  452. this->SharedLinkExtensions.push_back(e);
  453. }
  454. this->LinkExtensions.push_back(e);
  455. }
  456. }
  457. //----------------------------------------------------------------------------
  458. std::string
  459. cmComputeLinkInformation
  460. ::CreateExtensionRegex(std::vector<std::string> const& exts)
  461. {
  462. // Build a list of extension choices.
  463. std::string libext = "(";
  464. const char* sep = "";
  465. for(std::vector<std::string>::const_iterator i = exts.begin();
  466. i != exts.end(); ++i)
  467. {
  468. // Separate this choice from the previous one.
  469. libext += sep;
  470. sep = "|";
  471. // Store this extension choice with the "." escaped.
  472. libext += "\\";
  473. #if defined(_WIN32) && !defined(__CYGWIN__)
  474. libext += this->NoCaseExpression(i->c_str());
  475. #else
  476. libext += *i;
  477. #endif
  478. }
  479. // Finish the list.
  480. libext += ").*";
  481. return libext;
  482. }
  483. //----------------------------------------------------------------------------
  484. std::string cmComputeLinkInformation::NoCaseExpression(const char* str)
  485. {
  486. std::string ret;
  487. const char* s = str;
  488. while(*s)
  489. {
  490. if(*s == '.')
  491. {
  492. ret += *s;
  493. }
  494. else
  495. {
  496. ret += "[";
  497. ret += tolower(*s);
  498. ret += toupper(*s);
  499. ret += "]";
  500. }
  501. s++;
  502. }
  503. return ret;
  504. }
  505. //-------------------------------------------------------------------
  506. void cmComputeLinkInformation::SetCurrentLinkType(LinkType lt)
  507. {
  508. // If we are changing the current link type add the flag to tell the
  509. // linker about it.
  510. if(this->CurrentLinkType != lt)
  511. {
  512. this->CurrentLinkType = lt;
  513. if(this->LinkTypeEnabled)
  514. {
  515. switch(this->CurrentLinkType)
  516. {
  517. case LinkStatic:
  518. this->Items.push_back(Item(this->StaticLinkTypeFlag, false));
  519. break;
  520. case LinkShared:
  521. this->Items.push_back(Item(this->SharedLinkTypeFlag, false));
  522. break;
  523. default:
  524. break;
  525. }
  526. }
  527. }
  528. }
  529. //----------------------------------------------------------------------------
  530. void cmComputeLinkInformation::AddTargetItem(std::string const& item,
  531. cmTarget* target)
  532. {
  533. // This is called to handle a link item that is a full path to a target.
  534. // If the target is not a static library make sure the link type is
  535. // shared. This is because dynamic-mode linking can handle both
  536. // shared and static libraries but static-mode can handle only
  537. // static libraries. If a previous user item changed the link type
  538. // to static we need to make sure it is back to shared.
  539. if(target->GetType() != cmTarget::STATIC_LIBRARY)
  540. {
  541. this->SetCurrentLinkType(LinkShared);
  542. }
  543. // If this platform wants a flag before the full path, add it.
  544. if(!this->LibLinkFileFlag.empty())
  545. {
  546. this->Items.push_back(Item(this->LibLinkFileFlag, false));
  547. }
  548. // Now add the full path to the library.
  549. this->Items.push_back(Item(item, true));
  550. }
  551. //----------------------------------------------------------------------------
  552. void cmComputeLinkInformation::AddFullItem(std::string const& item)
  553. {
  554. // This is called to handle a link item that is a full path.
  555. // If the target is not a static library make sure the link type is
  556. // shared. This is because dynamic-mode linking can handle both
  557. // shared and static libraries but static-mode can handle only
  558. // static libraries. If a previous user item changed the link type
  559. // to static we need to make sure it is back to shared.
  560. if(this->LinkTypeEnabled)
  561. {
  562. std::string name = cmSystemTools::GetFilenameName(item);
  563. if(this->ExtractSharedLibraryName.find(name))
  564. {
  565. this->SetCurrentLinkType(LinkShared);
  566. }
  567. else if(!this->ExtractStaticLibraryName.find(item))
  568. {
  569. // We cannot determine the type. Assume it is the target's
  570. // default type.
  571. this->SetCurrentLinkType(this->StartLinkType);
  572. }
  573. }
  574. // If this platform wants a flag before the full path, add it.
  575. if(!this->LibLinkFileFlag.empty())
  576. {
  577. this->Items.push_back(Item(this->LibLinkFileFlag, false));
  578. }
  579. // Now add the full path to the library.
  580. this->Items.push_back(Item(item, true));
  581. }
  582. //----------------------------------------------------------------------------
  583. void cmComputeLinkInformation::AddUserItem(std::string const& item)
  584. {
  585. // This is called to handle a link item that does not match a CMake
  586. // target and is not a full path. We check here if it looks like a
  587. // library file name to automatically request the proper link type
  588. // from the linker. For example:
  589. //
  590. // foo ==> -lfoo
  591. // libfoo.a ==> -Wl,-Bstatic -lfoo
  592. std::string lib;
  593. // Parse out the prefix, base, and suffix components of the
  594. // library name. If the name matches that of a shared or static
  595. // library then set the link type accordingly.
  596. //
  597. // Search for shared library names first because some platforms
  598. // have shared libraries with names that match the static library
  599. // pattern. For example cygwin and msys use the convention
  600. // libfoo.dll.a for import libraries and libfoo.a for static
  601. // libraries. On AIX a library with the name libfoo.a can be
  602. // shared!
  603. if(this->ExtractSharedLibraryName.find(item))
  604. {
  605. // This matches a shared library file name.
  606. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  607. fprintf(stderr, "shared regex matched [%s] [%s] [%s]\n",
  608. this->ExtractSharedLibraryName.match(1).c_str(),
  609. this->ExtractSharedLibraryName.match(2).c_str(),
  610. this->ExtractSharedLibraryName.match(3).c_str());
  611. #endif
  612. // Set the link type to shared.
  613. this->SetCurrentLinkType(LinkShared);
  614. // Use just the library name so the linker will search.
  615. lib = this->ExtractSharedLibraryName.match(2);
  616. }
  617. else if(this->ExtractStaticLibraryName.find(item))
  618. {
  619. // This matches a static library file name.
  620. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  621. fprintf(stderr, "static regex matched [%s] [%s] [%s]\n",
  622. this->ExtractStaticLibraryName.match(1).c_str(),
  623. this->ExtractStaticLibraryName.match(2).c_str(),
  624. this->ExtractStaticLibraryName.match(3).c_str());
  625. #endif
  626. // Set the link type to static.
  627. this->SetCurrentLinkType(LinkStatic);
  628. // Use just the library name so the linker will search.
  629. lib = this->ExtractStaticLibraryName.match(2);
  630. }
  631. else if(this->ExtractAnyLibraryName.find(item))
  632. {
  633. // This matches a library file name.
  634. #ifdef CM_COMPUTE_LINK_INFO_DEBUG
  635. fprintf(stderr, "any regex matched [%s] [%s] [%s]\n",
  636. this->ExtractAnyLibraryName.match(1).c_str(),
  637. this->ExtractAnyLibraryName.match(2).c_str(),
  638. this->ExtractAnyLibraryName.match(3).c_str());
  639. #endif
  640. // Restore the target link type since this item does not specify
  641. // one.
  642. this->SetCurrentLinkType(this->StartLinkType);
  643. // Use just the library name so the linker will search.
  644. lib = this->ExtractAnyLibraryName.match(2);
  645. }
  646. else if(item[0] == '-' || item[0] == '$' || item[0] == '`')
  647. {
  648. // This is a linker option provided by the user. Restore the
  649. // target link type since this item does not specify one.
  650. this->SetCurrentLinkType(this->StartLinkType);
  651. // Use the item verbatim.
  652. this->Items.push_back(Item(item, false));
  653. return;
  654. }
  655. else
  656. {
  657. // This is a name specified by the user. We must ask the linker
  658. // to search for a library with this name. Restore the target
  659. // link type since this item does not specify one.
  660. this->SetCurrentLinkType(this->StartLinkType);
  661. lib = item;
  662. }
  663. // Create an option to ask the linker to search for the library.
  664. std::string out = this->LibLinkFlag;
  665. out += lib;
  666. out += this->LibLinkSuffix;
  667. this->Items.push_back(Item(out, false));
  668. // Here we could try to find the library the linker will find and
  669. // add a runtime information entry for it. It would probably not be
  670. // reliable and we want to encourage use of full paths for library
  671. // specification.
  672. }
  673. //----------------------------------------------------------------------------
  674. void cmComputeLinkInformation::AddFrameworkItem(std::string const& item)
  675. {
  676. // Try to separate the framework name and path.
  677. if(!this->SplitFramework.find(item.c_str()))
  678. {
  679. cmOStringStream e;
  680. e << "Could not parse framework path \"" << item << "\" "
  681. << "linked by target " << this->Target->GetName() << ".";
  682. cmSystemTools::Error(e.str().c_str());
  683. return;
  684. }
  685. // Add the directory portion to the framework search path.
  686. this->AddFrameworkPath(this->SplitFramework.match(1));
  687. // Add the item using the -framework option.
  688. std::string fw = "-framework ";
  689. fw += this->SplitFramework.match(2);
  690. this->Items.push_back(Item(fw, false));
  691. }
  692. //----------------------------------------------------------------------------
  693. void cmComputeLinkInformation::AddDirectoryItem(std::string const& item)
  694. {
  695. #ifdef __APPLE__
  696. if(cmSystemTools::IsPathToFramework(item.c_str()))
  697. {
  698. this->AddFrameworkItem(item);
  699. }
  700. else
  701. #endif
  702. {
  703. this->DropDirectoryItem(item);
  704. }
  705. }
  706. //----------------------------------------------------------------------------
  707. void cmComputeLinkInformation::DropDirectoryItem(std::string const& item)
  708. {
  709. // A full path to a directory was found as a link item. Warn the
  710. // user.
  711. cmOStringStream e;
  712. e << "WARNING: Target \"" << this->Target->GetName()
  713. << "\" requests linking to directory \"" << item << "\". "
  714. << "Targets may link only to libraries. "
  715. << "CMake is dropping the item.";
  716. cmSystemTools::Message(e.str().c_str());
  717. }
  718. //----------------------------------------------------------------------------
  719. void cmComputeLinkInformation::ComputeFrameworkInfo()
  720. {
  721. // Avoid adding system framework paths. See "man ld" on OS X.
  722. this->FrameworkPathsEmmitted.insert("/Library/Frameworks");
  723. this->FrameworkPathsEmmitted.insert("/Network/Library/Frameworks");
  724. this->FrameworkPathsEmmitted.insert("/System/Library/Frameworks");
  725. // Regular expression to extract a framework path and name.
  726. this->SplitFramework.compile("(.*)/(.*)\\.framework$");
  727. }
  728. //----------------------------------------------------------------------------
  729. void cmComputeLinkInformation::AddFrameworkPath(std::string const& p)
  730. {
  731. if(this->FrameworkPathsEmmitted.insert(p).second)
  732. {
  733. this->FrameworkPaths.push_back(p);
  734. }
  735. }
  736. //----------------------------------------------------------------------------
  737. void cmComputeLinkInformation::ComputeLinkerSearchDirectories()
  738. {
  739. // Some search paths should never be emitted.
  740. this->DirectoriesEmmitted.insert("");
  741. if(const char* implicitLinks =
  742. (this->Makefile->GetDefinition
  743. ("CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES")))
  744. {
  745. std::vector<std::string> implicitLinkVec;
  746. cmSystemTools::ExpandListArgument(implicitLinks, implicitLinkVec);
  747. for(std::vector<std::string>::const_iterator
  748. i = implicitLinkVec.begin();
  749. i != implicitLinkVec.end(); ++i)
  750. {
  751. this->DirectoriesEmmitted.insert(*i);
  752. }
  753. }
  754. // Check if we need to include the runtime search path at link time.
  755. std::string var = "CMAKE_SHARED_LIBRARY_LINK_";
  756. var += this->LinkLanguage;
  757. var += "_WITH_RUNTIME_PATH";
  758. if(this->Makefile->IsOn(var.c_str()))
  759. {
  760. // This platform requires the runtime library path for shared
  761. // libraries to be specified at link time as -L paths. It needs
  762. // them so that transitive dependencies of the libraries linked
  763. // may be found by the linker.
  764. this->AddLinkerSearchDirectories(this->GetRuntimeSearchPath());
  765. }
  766. // Get the search path entries requested by the user.
  767. this->AddLinkerSearchDirectories(this->Target->GetLinkDirectories());
  768. }
  769. //----------------------------------------------------------------------------
  770. void
  771. cmComputeLinkInformation
  772. ::AddLinkerSearchDirectories(std::vector<std::string> const& dirs)
  773. {
  774. for(std::vector<std::string>::const_iterator i = dirs.begin();
  775. i != dirs.end(); ++i)
  776. {
  777. if(this->DirectoriesEmmitted.insert(*i).second)
  778. {
  779. this->Directories.push_back(*i);
  780. }
  781. }
  782. }
  783. //----------------------------------------------------------------------------
  784. std::vector<std::string> const&
  785. cmComputeLinkInformation::GetRuntimeSearchPath()
  786. {
  787. if(!this->RuntimeSearchPathComputed)
  788. {
  789. this->RuntimeSearchPathComputed = true;
  790. this->CollectRuntimeDirectories();
  791. this->FindConflictingLibraries();
  792. this->OrderRuntimeSearchPath();
  793. }
  794. return this->RuntimeSearchPath;
  795. }
  796. //============================================================================
  797. // Directory ordering computation.
  798. // - Useful to compute a safe runtime library path order
  799. // - Need runtime path for supporting INSTALL_RPATH_USE_LINK_PATH
  800. // - Need runtime path at link time to pickup transitive link dependencies
  801. // for shared libraries (in future when we do not always add them).
  802. //----------------------------------------------------------------------------
  803. void
  804. cmComputeLinkInformation::AddLibraryRuntimeInfo(std::string const& fullPath,
  805. cmTarget* target)
  806. {
  807. // Skip targets that are not shared libraries (modules cannot be linked).
  808. if(target->GetType() != cmTarget::SHARED_LIBRARY)
  809. {
  810. return;
  811. }
  812. // Try to get the soname of the library. Only files with this name
  813. // could possibly conflict.
  814. std::string soName;
  815. const char* soname = 0;
  816. if(!target->IsImported())
  817. {
  818. std::string name;
  819. std::string realName;
  820. std::string impName;
  821. std::string pdbName;
  822. target->GetLibraryNames(name, soName, realName, impName, pdbName,
  823. this->Config);
  824. soname = soName.c_str();
  825. }
  826. // Add the library runtime entry.
  827. this->AddLibraryRuntimeInfo(fullPath, soname);
  828. }
  829. //----------------------------------------------------------------------------
  830. void
  831. cmComputeLinkInformation::AddLibraryRuntimeInfo(std::string const& fullPath,
  832. const char* soname)
  833. {
  834. // Get the name of the library from the file name.
  835. std::string file = cmSystemTools::GetFilenameName(fullPath);
  836. if(!this->ExtractSharedLibraryName.find(file.c_str()))
  837. {
  838. // This is not the name of a shared library.
  839. return;
  840. }
  841. // Add the runtime information at most once.
  842. if(this->LibraryRuntimeInfoEmmitted.insert(fullPath).second)
  843. {
  844. // Construct the runtime information entry for this library.
  845. LibraryRuntimeEntry entry;
  846. entry.FileName = cmSystemTools::GetFilenameName(fullPath);
  847. entry.SOName = soname? soname : "";
  848. entry.Directory = cmSystemTools::GetFilenamePath(fullPath);
  849. this->LibraryRuntimeInfo.push_back(entry);
  850. }
  851. else
  852. {
  853. // This can happen if the same library is linked multiple times.
  854. // In that case the runtime information check need be done only
  855. // once anyway. For shared libs we could add a check in AddItem
  856. // to not repeat them.
  857. }
  858. }
  859. //----------------------------------------------------------------------------
  860. void cmComputeLinkInformation::CollectRuntimeDirectories()
  861. {
  862. // Get all directories that should be in the runtime search path.
  863. // Add directories containing libraries linked with full path.
  864. for(std::vector<LibraryRuntimeEntry>::iterator
  865. ei = this->LibraryRuntimeInfo.begin();
  866. ei != this->LibraryRuntimeInfo.end(); ++ei)
  867. {
  868. ei->DirectoryIndex = this->AddRuntimeDirectory(ei->Directory);
  869. }
  870. // Add link directories specified for the target.
  871. std::vector<std::string> const& dirs = this->GetDirectories();
  872. for(std::vector<std::string>::const_iterator di = dirs.begin();
  873. di != dirs.end(); ++di)
  874. {
  875. this->AddRuntimeDirectory(*di);
  876. }
  877. }
  878. //----------------------------------------------------------------------------
  879. int cmComputeLinkInformation::AddRuntimeDirectory(std::string const& dir)
  880. {
  881. // Add the runtime directory with a unique index.
  882. std::map<cmStdString, int>::iterator i =
  883. this->RuntimeDirectoryIndex.find(dir);
  884. if(i == this->RuntimeDirectoryIndex.end())
  885. {
  886. std::map<cmStdString, int>::value_type
  887. entry(dir, static_cast<int>(this->RuntimeDirectories.size()));
  888. i = this->RuntimeDirectoryIndex.insert(entry).first;
  889. this->RuntimeDirectories.push_back(dir);
  890. }
  891. return i->second;
  892. }
  893. //----------------------------------------------------------------------------
  894. struct cmCLIRuntimeConflictCompare
  895. {
  896. typedef std::pair<int, int> RuntimeConflictPair;
  897. // The conflict pair is unique based on just the directory
  898. // (first). The second element is only used for displaying
  899. // information about why the entry is present.
  900. bool operator()(RuntimeConflictPair const& l,
  901. RuntimeConflictPair const& r)
  902. {
  903. return l.first == r.first;
  904. }
  905. };
  906. //----------------------------------------------------------------------------
  907. void cmComputeLinkInformation::FindConflictingLibraries()
  908. {
  909. // Allocate the conflict graph.
  910. this->RuntimeConflictGraph.resize(this->RuntimeDirectories.size());
  911. this->RuntimeDirectoryVisited.resize(this->RuntimeDirectories.size(), 0);
  912. // Find all runtime directories providing each library.
  913. for(unsigned int lri = 0; lri < this->LibraryRuntimeInfo.size(); ++lri)
  914. {
  915. this->FindDirectoriesForLib(lri);
  916. }
  917. // Clean up the conflict graph representation.
  918. for(std::vector<RuntimeConflictList>::iterator
  919. i = this->RuntimeConflictGraph.begin();
  920. i != this->RuntimeConflictGraph.end(); ++i)
  921. {
  922. // Sort the outgoing edges for each graph node so that the
  923. // original order will be preserved as much as possible.
  924. std::sort(i->begin(), i->end());
  925. // Make the edge list unique so cycle detection will be reliable.
  926. RuntimeConflictList::iterator last =
  927. std::unique(i->begin(), i->end(), cmCLIRuntimeConflictCompare());
  928. i->erase(last, i->end());
  929. }
  930. }
  931. //----------------------------------------------------------------------------
  932. void cmComputeLinkInformation::FindDirectoriesForLib(unsigned int lri)
  933. {
  934. // Search through the runtime directories to find those providing
  935. // this library.
  936. LibraryRuntimeEntry& re = this->LibraryRuntimeInfo[lri];
  937. for(unsigned int i = 0; i < this->RuntimeDirectories.size(); ++i)
  938. {
  939. // Skip the directory that is supposed to provide the library.
  940. if(this->RuntimeDirectories[i] == re.Directory)
  941. {
  942. continue;
  943. }
  944. // Determine which type of check to do.
  945. if(!re.SOName.empty())
  946. {
  947. // We have the library soname. Check if it will be found.
  948. std::string file = this->RuntimeDirectories[i];
  949. file += "/";
  950. file += re.SOName;
  951. std::set<cmStdString> const& files =
  952. (this->GlobalGenerator
  953. ->GetDirectoryContent(this->RuntimeDirectories[i], false));
  954. if(files.find(re.SOName) != files.end() ||
  955. cmSystemTools::FileExists(file.c_str(), true))
  956. {
  957. // The library will be found in this directory but this is not
  958. // the directory named for it. Add an entry to make sure the
  959. // desired directory comes before this one.
  960. RuntimeConflictPair p(re.DirectoryIndex, lri);
  961. this->RuntimeConflictGraph[i].push_back(p);
  962. }
  963. }
  964. else
  965. {
  966. // We do not have the soname. Look for files in the directory
  967. // that may conflict.
  968. std::set<cmStdString> const& files =
  969. (this->GlobalGenerator
  970. ->GetDirectoryContent(this->RuntimeDirectories[i], true));
  971. // Get the set of files that might conflict. Since we do not
  972. // know the soname just look at all files that start with the
  973. // file name. Usually the soname starts with the library name.
  974. std::string base = re.FileName;
  975. std::set<cmStdString>::const_iterator first = files.lower_bound(base);
  976. ++base[base.size()-1];
  977. std::set<cmStdString>::const_iterator last = files.upper_bound(base);
  978. bool found = false;
  979. for(std::set<cmStdString>::const_iterator fi = first;
  980. !found && fi != last; ++fi)
  981. {
  982. found = true;
  983. }
  984. if(found)
  985. {
  986. // The library may be found in this directory but this is not
  987. // the directory named for it. Add an entry to make sure the
  988. // desired directory comes before this one.
  989. RuntimeConflictPair p(re.DirectoryIndex, lri);
  990. this->RuntimeConflictGraph[i].push_back(p);
  991. }
  992. }
  993. }
  994. }
  995. //----------------------------------------------------------------------------
  996. void cmComputeLinkInformation::OrderRuntimeSearchPath()
  997. {
  998. // Allow a cycle to be diagnosed once.
  999. this->CycleDiagnosed = false;
  1000. // Iterate through the directories in the original order.
  1001. for(unsigned int i=0; i < this->RuntimeDirectories.size(); ++i)
  1002. {
  1003. this->VisitRuntimeDirectory(i, true);
  1004. }
  1005. }
  1006. //----------------------------------------------------------------------------
  1007. void cmComputeLinkInformation::VisitRuntimeDirectory(unsigned int i,
  1008. bool top)
  1009. {
  1010. // Skip nodes already visited.
  1011. if(this->RuntimeDirectoryVisited[i])
  1012. {
  1013. if(!top)
  1014. {
  1015. // We have reached a previously visited node but were not called
  1016. // to start a new section of the graph. There is a cycle.
  1017. this->DiagnoseCycle();
  1018. }
  1019. return;
  1020. }
  1021. // We are not visiting this node so mark it.
  1022. this->RuntimeDirectoryVisited[i] = 1;
  1023. // Visit the neighbors of the node first.
  1024. RuntimeConflictList const& clist = this->RuntimeConflictGraph[i];
  1025. for(RuntimeConflictList::const_iterator j = clist.begin();
  1026. j != clist.end(); ++j)
  1027. {
  1028. this->VisitRuntimeDirectory(j->first, false);
  1029. }
  1030. // Now that all directories required to come before this one have
  1031. // been emmitted, emit this directory.
  1032. this->RuntimeSearchPath.push_back(this->RuntimeDirectories[i]);
  1033. }
  1034. //----------------------------------------------------------------------------
  1035. void cmComputeLinkInformation::DiagnoseCycle()
  1036. {
  1037. // Report the cycle at most once.
  1038. if(this->CycleDiagnosed)
  1039. {
  1040. return;
  1041. }
  1042. this->CycleDiagnosed = true;
  1043. // Construct the message.
  1044. cmOStringStream e;
  1045. e << "WARNING: Cannot generate a safe runtime path for target "
  1046. << this->Target->GetName()
  1047. << " because there is a cycle in the constraint graph:\n";
  1048. // Clean up the conflict graph representation.
  1049. for(unsigned int i=0; i < this->RuntimeConflictGraph.size(); ++i)
  1050. {
  1051. RuntimeConflictList const& clist = this->RuntimeConflictGraph[i];
  1052. e << "dir " << i << " is [" << this->RuntimeDirectories[i] << "]\n";
  1053. for(RuntimeConflictList::const_iterator j = clist.begin();
  1054. j != clist.end(); ++j)
  1055. {
  1056. e << " dir " << j->first << " must precede it due to [";
  1057. LibraryRuntimeEntry const& re = this->LibraryRuntimeInfo[j->second];
  1058. if(re.SOName.empty())
  1059. {
  1060. e << re.FileName;
  1061. }
  1062. else
  1063. {
  1064. e << re.SOName;
  1065. }
  1066. e << "]\n";
  1067. }
  1068. }
  1069. cmSystemTools::Message(e.str().c_str());
  1070. }