cmFindLibraryCommand.cxx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #include "cmFindLibraryCommand.h"
  11. #include "cmCacheManager.h"
  12. #include <cmsys/Directory.hxx>
  13. #include <cmsys/stl/algorithm>
  14. cmFindLibraryCommand::cmFindLibraryCommand()
  15. {
  16. this->EnvironmentPath = "LIB";
  17. this->NamesPerDirAllowed = true;
  18. }
  19. //----------------------------------------------------------------------------
  20. void cmFindLibraryCommand::GenerateDocumentation()
  21. {
  22. this->cmFindBase::GenerateDocumentation();
  23. cmSystemTools::ReplaceString(this->GenericDocumentation,
  24. "FIND_XXX", "find_library");
  25. cmSystemTools::ReplaceString(this->GenericDocumentation,
  26. "CMAKE_XXX_PATH", "CMAKE_LIBRARY_PATH");
  27. cmSystemTools::ReplaceString(this->GenericDocumentation,
  28. "CMAKE_XXX_MAC_PATH",
  29. "CMAKE_FRAMEWORK_PATH");
  30. cmSystemTools::ReplaceString(this->GenericDocumentation,
  31. "CMAKE_SYSTEM_XXX_MAC_PATH",
  32. "CMAKE_SYSTEM_FRAMEWORK_PATH");
  33. cmSystemTools::ReplaceString(this->GenericDocumentation,
  34. "XXX_SYSTEM", "LIB");
  35. cmSystemTools::ReplaceString(this->GenericDocumentation,
  36. "CMAKE_SYSTEM_XXX_PATH",
  37. "CMAKE_SYSTEM_LIBRARY_PATH");
  38. cmSystemTools::ReplaceString(this->GenericDocumentation,
  39. "SEARCH_XXX_DESC", "library");
  40. cmSystemTools::ReplaceString(this->GenericDocumentation,
  41. "SEARCH_XXX", "library");
  42. cmSystemTools::ReplaceString(this->GenericDocumentation,
  43. "XXX_SUBDIR", "lib");
  44. cmSystemTools::ReplaceString(this->GenericDocumentation,
  45. "NAMES name1 [name2 ...]",
  46. "NAMES name1 [name2 ...] [NAMES_PER_DIR]");
  47. cmSystemTools::ReplaceString(
  48. this->GenericDocumentation,
  49. "XXX_EXTRA_PREFIX_ENTRY",
  50. " <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and\n");
  51. cmSystemTools::ReplaceString(this->GenericDocumentation,
  52. "CMAKE_FIND_ROOT_PATH_MODE_XXX",
  53. "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY");
  54. this->GenericDocumentation +=
  55. "\n"
  56. "When more than one value is given to the NAMES option this command "
  57. "by default will consider one name at a time and search every directory "
  58. "for it. "
  59. "The NAMES_PER_DIR option tells this command to consider one directory "
  60. "at a time and search for all names in it."
  61. "\n"
  62. "If the library found is a framework, then VAR will be set to "
  63. "the full path to the framework <fullPath>/A.framework. "
  64. "When a full path to a framework is used as a library, "
  65. "CMake will use a -framework A, and a -F<fullPath> to "
  66. "link the framework to the target."
  67. "\n"
  68. "If the global property FIND_LIBRARY_USE_LIB64_PATHS is set all search "
  69. "paths will be tested as normal, with \"64/\" appended, and with all "
  70. "matches of \"lib/\" replaced with \"lib64/\". This property is "
  71. "automatically set for the platforms that are known to need it if at "
  72. "least one of the languages supported by the PROJECT command is enabled.";
  73. }
  74. // cmFindLibraryCommand
  75. bool cmFindLibraryCommand
  76. ::InitialPass(std::vector<std::string> const& argsIn, cmExecutionStatus &)
  77. {
  78. this->VariableDocumentation = "Path to a library.";
  79. this->CMakePathName = "LIBRARY";
  80. if(!this->ParseArguments(argsIn))
  81. {
  82. return false;
  83. }
  84. if(this->AlreadyInCache)
  85. {
  86. // If the user specifies the entry on the command line without a
  87. // type we should add the type and docstring but keep the original
  88. // value.
  89. if(this->AlreadyInCacheWithoutMetaInfo)
  90. {
  91. this->Makefile->AddCacheDefinition(this->VariableName.c_str(), "",
  92. this->VariableDocumentation.c_str(),
  93. cmCacheManager::FILEPATH);
  94. }
  95. return true;
  96. }
  97. if(const char* abi_name =
  98. this->Makefile->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI"))
  99. {
  100. std::string abi = abi_name;
  101. if(abi.find("ELF N32") != abi.npos)
  102. {
  103. // Convert lib to lib32.
  104. this->AddArchitecturePaths("32");
  105. }
  106. }
  107. if(this->Makefile->GetCMakeInstance()
  108. ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
  109. {
  110. // add special 64 bit paths if this is a 64 bit compile.
  111. if(this->Makefile->PlatformIs64Bit())
  112. {
  113. this->AddArchitecturePaths("64");
  114. }
  115. }
  116. std::string library = this->FindLibrary();
  117. if(library != "")
  118. {
  119. // Save the value in the cache
  120. this->Makefile->AddCacheDefinition(this->VariableName.c_str(),
  121. library.c_str(),
  122. this->VariableDocumentation.c_str(),
  123. cmCacheManager::FILEPATH);
  124. return true;
  125. }
  126. std::string notfound = this->VariableName + "-NOTFOUND";
  127. this->Makefile->AddCacheDefinition(this->VariableName.c_str(),
  128. notfound.c_str(),
  129. this->VariableDocumentation.c_str(),
  130. cmCacheManager::FILEPATH);
  131. return true;
  132. }
  133. //----------------------------------------------------------------------------
  134. void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix)
  135. {
  136. std::vector<std::string> original;
  137. original.swap(this->SearchPaths);
  138. for(std::vector<std::string>::iterator i = original.begin();
  139. i != original.end(); ++i)
  140. {
  141. this->AddArchitecturePath(*i, 0, suffix);
  142. }
  143. }
  144. //----------------------------------------------------------------------------
  145. void cmFindLibraryCommand::AddArchitecturePath(
  146. std::string const& dir, std::string::size_type start_pos,
  147. const char* suffix, bool fresh)
  148. {
  149. std::string::size_type pos = dir.find("lib/", start_pos);
  150. if(pos != std::string::npos)
  151. {
  152. std::string cur_dir = dir.substr(0,pos+3);
  153. // Follow "lib<suffix>".
  154. std::string next_dir = cur_dir + suffix;
  155. if(cmSystemTools::FileIsDirectory(next_dir.c_str()))
  156. {
  157. next_dir += dir.substr(pos+3);
  158. std::string::size_type next_pos = pos+3+strlen(suffix)+1;
  159. this->AddArchitecturePath(next_dir, next_pos, suffix);
  160. }
  161. // Follow "lib".
  162. if(cmSystemTools::FileIsDirectory(cur_dir.c_str()))
  163. {
  164. this->AddArchitecturePath(dir, pos+3+1, suffix, false);
  165. }
  166. }
  167. if(fresh)
  168. {
  169. // Check for <dir><suffix>/.
  170. std::string cur_dir = dir + suffix + "/";
  171. if(cmSystemTools::FileIsDirectory(cur_dir.c_str()))
  172. {
  173. this->SearchPaths.push_back(cur_dir);
  174. }
  175. // Now add the original unchanged path
  176. if(cmSystemTools::FileIsDirectory(dir.c_str()))
  177. {
  178. this->SearchPaths.push_back(dir);
  179. }
  180. }
  181. }
  182. //----------------------------------------------------------------------------
  183. std::string cmFindLibraryCommand::FindLibrary()
  184. {
  185. std::string library;
  186. if(this->SearchFrameworkFirst || this->SearchFrameworkOnly)
  187. {
  188. library = this->FindFrameworkLibrary();
  189. }
  190. if(library.empty() && !this->SearchFrameworkOnly)
  191. {
  192. library = this->FindNormalLibrary();
  193. }
  194. if(library.empty() && this->SearchFrameworkLast)
  195. {
  196. library = this->FindFrameworkLibrary();
  197. }
  198. return library;
  199. }
  200. //----------------------------------------------------------------------------
  201. struct cmFindLibraryHelper
  202. {
  203. cmFindLibraryHelper(cmMakefile* mf);
  204. // Context information.
  205. cmMakefile* Makefile;
  206. cmGlobalGenerator* GG;
  207. // List of valid prefixes and suffixes.
  208. std::vector<std::string> Prefixes;
  209. std::vector<std::string> Suffixes;
  210. std::string PrefixRegexStr;
  211. std::string SuffixRegexStr;
  212. // Keep track of the best library file found so far.
  213. typedef std::vector<std::string>::size_type size_type;
  214. std::string BestPath;
  215. // Support for OpenBSD shared library naming: lib<name>.so.<major>.<minor>
  216. bool OpenBSD;
  217. // Current names under consideration.
  218. struct Name
  219. {
  220. bool TryRaw;
  221. std::string Raw;
  222. cmsys::RegularExpression Regex;
  223. Name(): TryRaw(false) {}
  224. };
  225. std::vector<Name> Names;
  226. // Current full path under consideration.
  227. std::string TestPath;
  228. void RegexFromLiteral(std::string& out, std::string const& in);
  229. void RegexFromList(std::string& out, std::vector<std::string> const& in);
  230. size_type GetPrefixIndex(std::string const& prefix)
  231. {
  232. return cmsys_stl::find(this->Prefixes.begin(), this->Prefixes.end(),
  233. prefix) - this->Prefixes.begin();
  234. }
  235. size_type GetSuffixIndex(std::string const& suffix)
  236. {
  237. return cmsys_stl::find(this->Suffixes.begin(), this->Suffixes.end(),
  238. suffix) - this->Suffixes.begin();
  239. }
  240. bool HasValidSuffix(std::string const& name);
  241. void AddName(std::string const& name);
  242. bool CheckDirectory(std::string const& path);
  243. bool CheckDirectoryForName(std::string const& path, Name& name);
  244. };
  245. //----------------------------------------------------------------------------
  246. cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf):
  247. Makefile(mf)
  248. {
  249. this->GG = this->Makefile->GetLocalGenerator()->GetGlobalGenerator();
  250. // Collect the list of library name prefixes/suffixes to try.
  251. const char* prefixes_list =
  252. this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_PREFIXES");
  253. const char* suffixes_list =
  254. this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_SUFFIXES");
  255. cmSystemTools::ExpandListArgument(prefixes_list, this->Prefixes, true);
  256. cmSystemTools::ExpandListArgument(suffixes_list, this->Suffixes, true);
  257. this->RegexFromList(this->PrefixRegexStr, this->Prefixes);
  258. this->RegexFromList(this->SuffixRegexStr, this->Suffixes);
  259. // Check whether to use OpenBSD-style library version comparisons.
  260. this->OpenBSD =
  261. this->Makefile->GetCMakeInstance()
  262. ->GetPropertyAsBool("FIND_LIBRARY_USE_OPENBSD_VERSIONING");
  263. }
  264. //----------------------------------------------------------------------------
  265. void cmFindLibraryHelper::RegexFromLiteral(std::string& out,
  266. std::string const& in)
  267. {
  268. for(std::string::const_iterator ci = in.begin(); ci != in.end(); ++ci)
  269. {
  270. char ch = *ci;
  271. if(ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' ||
  272. ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' ||
  273. ch == '^' || ch == '$')
  274. {
  275. out += "\\";
  276. }
  277. #if defined(_WIN32) || defined(__APPLE__)
  278. out += tolower(ch);
  279. #else
  280. out += ch;
  281. #endif
  282. }
  283. }
  284. //----------------------------------------------------------------------------
  285. void cmFindLibraryHelper::RegexFromList(std::string& out,
  286. std::vector<std::string> const& in)
  287. {
  288. // Surround the list in parens so the '|' does not apply to anything
  289. // else and the result can be checked after matching.
  290. out += "(";
  291. const char* sep = "";
  292. for(std::vector<std::string>::const_iterator si = in.begin();
  293. si != in.end(); ++si)
  294. {
  295. // Separate from previous item.
  296. out += sep;
  297. sep = "|";
  298. // Append this item.
  299. this->RegexFromLiteral(out, *si);
  300. }
  301. out += ")";
  302. }
  303. //----------------------------------------------------------------------------
  304. bool cmFindLibraryHelper::HasValidSuffix(std::string const& name)
  305. {
  306. for(std::vector<std::string>::const_iterator si = this->Suffixes.begin();
  307. si != this->Suffixes.end(); ++si)
  308. {
  309. std::string suffix = *si;
  310. if(name.length() <= suffix.length())
  311. {
  312. continue;
  313. }
  314. // Check if the given name ends in a valid library suffix.
  315. if(name.substr(name.size()-suffix.length()) == suffix)
  316. {
  317. return true;
  318. }
  319. // Check if a valid library suffix is somewhere in the name,
  320. // this may happen e.g. for versioned shared libraries: libfoo.so.2
  321. suffix += ".";
  322. if(name.find(suffix) != name.npos)
  323. {
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. //----------------------------------------------------------------------------
  330. void cmFindLibraryHelper::AddName(std::string const& name)
  331. {
  332. Name entry;
  333. // Consider checking the raw name too.
  334. entry.TryRaw = this->HasValidSuffix(name);
  335. entry.Raw = name;
  336. // Build a regular expression to match library names.
  337. std::string regex = "^";
  338. regex += this->PrefixRegexStr;
  339. this->RegexFromLiteral(regex, name);
  340. regex += this->SuffixRegexStr;
  341. if(this->OpenBSD)
  342. {
  343. regex += "(\\.[0-9]+\\.[0-9]+)?";
  344. }
  345. regex += "$";
  346. entry.Regex.compile(regex.c_str());
  347. this->Names.push_back(entry);
  348. }
  349. //----------------------------------------------------------------------------
  350. bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
  351. {
  352. for(std::vector<Name>::iterator i = this->Names.begin();
  353. i != this->Names.end(); ++i)
  354. {
  355. if(this->CheckDirectoryForName(path, *i))
  356. {
  357. return true;
  358. }
  359. }
  360. return false;
  361. }
  362. //----------------------------------------------------------------------------
  363. bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path,
  364. Name& name)
  365. {
  366. // If the original library name provided by the user matches one of
  367. // the suffixes, try it first. This allows users to search
  368. // specifically for a static library on some platforms (on MS tools
  369. // one cannot tell just from the library name whether it is a static
  370. // library or an import library).
  371. if(name.TryRaw)
  372. {
  373. this->TestPath = path;
  374. this->TestPath += name.Raw;
  375. if(cmSystemTools::FileExists(this->TestPath.c_str(), true))
  376. {
  377. this->BestPath =
  378. cmSystemTools::CollapseFullPath(this->TestPath.c_str());
  379. cmSystemTools::ConvertToUnixSlashes(this->BestPath);
  380. return true;
  381. }
  382. }
  383. // No library file has yet been found.
  384. size_type bestPrefix = this->Prefixes.size();
  385. size_type bestSuffix = this->Suffixes.size();
  386. unsigned int bestMajor = 0;
  387. unsigned int bestMinor = 0;
  388. // Search for a file matching the library name regex.
  389. std::string dir = path;
  390. cmSystemTools::ConvertToUnixSlashes(dir);
  391. std::set<cmStdString> const& files = this->GG->GetDirectoryContent(dir);
  392. for(std::set<cmStdString>::const_iterator fi = files.begin();
  393. fi != files.end(); ++fi)
  394. {
  395. std::string const& origName = *fi;
  396. #if defined(_WIN32) || defined(__APPLE__)
  397. std::string testName = cmSystemTools::LowerCase(origName);
  398. #else
  399. std::string const& testName = origName;
  400. #endif
  401. if(name.Regex.find(testName))
  402. {
  403. this->TestPath = path;
  404. this->TestPath += origName;
  405. if(!cmSystemTools::FileIsDirectory(this->TestPath.c_str()))
  406. {
  407. // This is a matching file. Check if it is better than the
  408. // best name found so far. Earlier prefixes are preferred,
  409. // followed by earlier suffixes. For OpenBSD, shared library
  410. // version extensions are compared.
  411. size_type prefix = this->GetPrefixIndex(name.Regex.match(1));
  412. size_type suffix = this->GetSuffixIndex(name.Regex.match(2));
  413. unsigned int major = 0;
  414. unsigned int minor = 0;
  415. if(this->OpenBSD)
  416. {
  417. sscanf(name.Regex.match(3).c_str(), ".%u.%u", &major, &minor);
  418. }
  419. if(this->BestPath.empty() || prefix < bestPrefix ||
  420. (prefix == bestPrefix && suffix < bestSuffix) ||
  421. (prefix == bestPrefix && suffix == bestSuffix &&
  422. (major > bestMajor ||
  423. (major == bestMajor && minor > bestMinor))))
  424. {
  425. this->BestPath = this->TestPath;
  426. bestPrefix = prefix;
  427. bestSuffix = suffix;
  428. bestMajor = major;
  429. bestMinor = minor;
  430. }
  431. }
  432. }
  433. }
  434. // Use the best candidate found in this directory, if any.
  435. return !this->BestPath.empty();
  436. }
  437. //----------------------------------------------------------------------------
  438. std::string cmFindLibraryCommand::FindNormalLibrary()
  439. {
  440. if(this->NamesPerDir)
  441. {
  442. return this->FindNormalLibraryNamesPerDir();
  443. }
  444. else
  445. {
  446. return this->FindNormalLibraryDirsPerName();
  447. }
  448. }
  449. //----------------------------------------------------------------------------
  450. std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir()
  451. {
  452. // Search for all names in each directory.
  453. cmFindLibraryHelper helper(this->Makefile);
  454. for(std::vector<std::string>::const_iterator ni = this->Names.begin();
  455. ni != this->Names.end() ; ++ni)
  456. {
  457. helper.AddName(*ni);
  458. }
  459. // Search every directory.
  460. for(std::vector<std::string>::const_iterator
  461. p = this->SearchPaths.begin(); p != this->SearchPaths.end(); ++p)
  462. {
  463. if(helper.CheckDirectory(*p))
  464. {
  465. return helper.BestPath;
  466. }
  467. }
  468. // Couldn't find the library.
  469. return "";
  470. }
  471. //----------------------------------------------------------------------------
  472. std::string cmFindLibraryCommand::FindNormalLibraryDirsPerName()
  473. {
  474. // Search the entire path for each name.
  475. cmFindLibraryHelper helper(this->Makefile);
  476. for(std::vector<std::string>::const_iterator ni = this->Names.begin();
  477. ni != this->Names.end() ; ++ni)
  478. {
  479. // Switch to searching for this name.
  480. std::string const& name = *ni;
  481. helper.AddName(name);
  482. // Search every directory.
  483. for(std::vector<std::string>::const_iterator
  484. p = this->SearchPaths.begin();
  485. p != this->SearchPaths.end(); ++p)
  486. {
  487. if(helper.CheckDirectory(*p))
  488. {
  489. return helper.BestPath;
  490. }
  491. }
  492. }
  493. // Couldn't find the library.
  494. return "";
  495. }
  496. //----------------------------------------------------------------------------
  497. std::string cmFindLibraryCommand::FindFrameworkLibrary()
  498. {
  499. if(this->NamesPerDir)
  500. {
  501. return this->FindFrameworkLibraryNamesPerDir();
  502. }
  503. else
  504. {
  505. return this->FindFrameworkLibraryDirsPerName();
  506. }
  507. }
  508. //----------------------------------------------------------------------------
  509. std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir()
  510. {
  511. std::string fwPath;
  512. // Search for all names in each search path.
  513. for(std::vector<std::string>::const_iterator di = this->SearchPaths.begin();
  514. di != this->SearchPaths.end(); ++di)
  515. {
  516. for(std::vector<std::string>::const_iterator ni = this->Names.begin();
  517. ni != this->Names.end() ; ++ni)
  518. {
  519. fwPath = *di;
  520. fwPath += *ni;
  521. fwPath += ".framework";
  522. if(cmSystemTools::FileIsDirectory(fwPath.c_str()))
  523. {
  524. return cmSystemTools::CollapseFullPath(fwPath.c_str());
  525. }
  526. }
  527. }
  528. // No framework found.
  529. return "";
  530. }
  531. //----------------------------------------------------------------------------
  532. std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName()
  533. {
  534. std::string fwPath;
  535. // Search for each name in all search paths.
  536. for(std::vector<std::string>::const_iterator ni = this->Names.begin();
  537. ni != this->Names.end() ; ++ni)
  538. {
  539. for(std::vector<std::string>::const_iterator
  540. di = this->SearchPaths.begin();
  541. di != this->SearchPaths.end(); ++di)
  542. {
  543. fwPath = *di;
  544. fwPath += *ni;
  545. fwPath += ".framework";
  546. if(cmSystemTools::FileIsDirectory(fwPath.c_str()))
  547. {
  548. return cmSystemTools::CollapseFullPath(fwPath.c_str());
  549. }
  550. }
  551. }
  552. // No framework found.
  553. return "";
  554. }