cmFindLibraryCommand.cxx 17 KB

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