cmFindLibraryCommand.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 "cmFindLibraryCommand.h"
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <set>
  8. #include <utility>
  9. #include "cmsys/RegularExpression.hxx"
  10. #include "cmGlobalGenerator.h"
  11. #include "cmMakefile.h"
  12. #include "cmState.h"
  13. #include "cmStateTypes.h"
  14. #include "cmStringAlgorithms.h"
  15. #include "cmSystemTools.h"
  16. #include "cmValue.h"
  17. class cmExecutionStatus;
  18. cmFindLibraryCommand::cmFindLibraryCommand(cmExecutionStatus& status)
  19. : cmFindBase("find_library", status)
  20. {
  21. this->EnvironmentPath = "LIB";
  22. this->NamesPerDirAllowed = true;
  23. this->VariableDocumentation = "Path to a library.";
  24. this->VariableType = cmStateEnums::FILEPATH;
  25. }
  26. // cmFindLibraryCommand
  27. bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn)
  28. {
  29. this->DebugMode = this->ComputeIfDebugModeWanted();
  30. this->CMakePathName = "LIBRARY";
  31. if (!this->ParseArguments(argsIn)) {
  32. return false;
  33. }
  34. if (this->AlreadyDefined) {
  35. this->NormalizeFindResult();
  36. return true;
  37. }
  38. // add custom lib<qual> paths instead of using fixed lib32, lib64 or
  39. // libx32
  40. if (cmValue customLib = this->Makefile->GetDefinition(
  41. "CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX")) {
  42. this->AddArchitecturePaths(customLib->c_str());
  43. }
  44. // add special 32 bit paths if this is a 32 bit compile.
  45. else if (this->Makefile->PlatformIs32Bit() &&
  46. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  47. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  48. this->AddArchitecturePaths("32");
  49. }
  50. // add special 64 bit paths if this is a 64 bit compile.
  51. else if (this->Makefile->PlatformIs64Bit() &&
  52. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  53. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  54. this->AddArchitecturePaths("64");
  55. }
  56. // add special 32 bit paths if this is an x32 compile.
  57. else if (this->Makefile->PlatformIsx32() &&
  58. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  59. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  60. this->AddArchitecturePaths("x32");
  61. }
  62. std::string const library = this->FindLibrary();
  63. this->StoreFindResult(library);
  64. return true;
  65. }
  66. void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix)
  67. {
  68. std::vector<std::string> original;
  69. original.swap(this->SearchPaths);
  70. for (std::string const& o : original) {
  71. this->AddArchitecturePath(o, 0, suffix);
  72. if (this->DebugMode) {
  73. std::string msg = cmStrCat(
  74. "find_library(", this->VariableName, ") removed original suffix ", o,
  75. " from PATH_SUFFIXES while adding architecture paths for suffix '",
  76. suffix, "'");
  77. this->DebugMessage(msg);
  78. }
  79. }
  80. }
  81. static bool cmLibDirsLinked(std::string const& l, std::string const& r)
  82. {
  83. // Compare the real paths of the two directories.
  84. // Since our caller only changed the trailing component of each
  85. // directory, the real paths can be the same only if at least one of
  86. // the trailing components is a symlink. Use this as an optimization
  87. // to avoid excessive realpath calls.
  88. return (cmSystemTools::FileIsSymlink(l) ||
  89. cmSystemTools::FileIsSymlink(r)) &&
  90. cmSystemTools::GetRealPath(l) == cmSystemTools::GetRealPath(r);
  91. }
  92. void cmFindLibraryCommand::AddArchitecturePath(
  93. std::string const& dir, std::string::size_type start_pos, const char* suffix,
  94. bool fresh)
  95. {
  96. std::string::size_type pos = dir.find("lib/", start_pos);
  97. if (pos != std::string::npos) {
  98. // Check for "lib".
  99. std::string lib = dir.substr(0, pos + 3);
  100. bool use_lib = cmSystemTools::FileIsDirectory(lib);
  101. // Check for "lib<suffix>" and use it first.
  102. std::string libX = lib + suffix;
  103. bool use_libX = cmSystemTools::FileIsDirectory(libX);
  104. // Avoid copies of the same directory due to symlinks.
  105. if (use_libX && use_lib && cmLibDirsLinked(libX, lib)) {
  106. use_libX = false;
  107. }
  108. if (use_libX) {
  109. libX += dir.substr(pos + 3);
  110. std::string::size_type libX_pos = pos + 3 + strlen(suffix) + 1;
  111. this->AddArchitecturePath(libX, libX_pos, suffix);
  112. }
  113. if (use_lib) {
  114. this->AddArchitecturePath(dir, pos + 3 + 1, suffix, false);
  115. }
  116. }
  117. if (fresh) {
  118. // Check for the original unchanged path.
  119. bool use_dir = cmSystemTools::FileIsDirectory(dir);
  120. // Check for <dir><suffix>/ and use it first.
  121. std::string dirX = dir + suffix;
  122. bool use_dirX = cmSystemTools::FileIsDirectory(dirX);
  123. // Avoid copies of the same directory due to symlinks.
  124. if (use_dirX && use_dir && cmLibDirsLinked(dirX, dir)) {
  125. use_dirX = false;
  126. }
  127. if (use_dirX) {
  128. dirX += "/";
  129. if (this->DebugMode) {
  130. std::string msg = cmStrCat(
  131. "find_library(", this->VariableName, ") added replacement path ",
  132. dirX, " to PATH_SUFFIXES for architecture suffix '", suffix, "'");
  133. this->DebugMessage(msg);
  134. }
  135. this->SearchPaths.push_back(std::move(dirX));
  136. }
  137. if (use_dir) {
  138. this->SearchPaths.push_back(dir);
  139. if (this->DebugMode) {
  140. std::string msg = cmStrCat(
  141. "find_library(", this->VariableName, ") added replacement path ",
  142. dir, " to PATH_SUFFIXES for architecture suffix '", suffix, "'");
  143. this->DebugMessage(msg);
  144. }
  145. }
  146. }
  147. }
  148. std::string cmFindLibraryCommand::FindLibrary()
  149. {
  150. std::string library;
  151. if (this->SearchFrameworkFirst || this->SearchFrameworkOnly) {
  152. library = this->FindFrameworkLibrary();
  153. }
  154. if (library.empty() && !this->SearchFrameworkOnly) {
  155. library = this->FindNormalLibrary();
  156. }
  157. if (library.empty() && this->SearchFrameworkLast) {
  158. library = this->FindFrameworkLibrary();
  159. }
  160. return library;
  161. }
  162. struct cmFindLibraryHelper
  163. {
  164. cmFindLibraryHelper(std::string debugName, cmMakefile* mf,
  165. cmFindBase const* findBase);
  166. // Context information.
  167. cmMakefile* Makefile;
  168. cmGlobalGenerator* GG;
  169. // List of valid prefixes and suffixes.
  170. std::vector<std::string> Prefixes;
  171. std::vector<std::string> Suffixes;
  172. std::string PrefixRegexStr;
  173. std::string SuffixRegexStr;
  174. // Keep track of the best library file found so far.
  175. using size_type = std::vector<std::string>::size_type;
  176. std::string BestPath;
  177. // Support for OpenBSD shared library naming: lib<name>.so.<major>.<minor>
  178. bool OpenBSD;
  179. bool DebugMode;
  180. // Current names under consideration.
  181. struct Name
  182. {
  183. bool TryRaw = false;
  184. std::string Raw;
  185. cmsys::RegularExpression Regex;
  186. };
  187. std::vector<Name> Names;
  188. // Current full path under consideration.
  189. std::string TestPath;
  190. void RegexFromLiteral(std::string& out, std::string const& in);
  191. void RegexFromList(std::string& out, std::vector<std::string> const& in);
  192. size_type GetPrefixIndex(std::string const& prefix)
  193. {
  194. return std::find(this->Prefixes.begin(), this->Prefixes.end(), prefix) -
  195. this->Prefixes.begin();
  196. }
  197. size_type GetSuffixIndex(std::string const& suffix)
  198. {
  199. return std::find(this->Suffixes.begin(), this->Suffixes.end(), suffix) -
  200. this->Suffixes.begin();
  201. }
  202. bool HasValidSuffix(std::string const& name);
  203. void AddName(std::string const& name);
  204. void SetName(std::string const& name);
  205. bool CheckDirectory(std::string const& path);
  206. bool CheckDirectoryForName(std::string const& path, Name& name);
  207. cmFindBaseDebugState DebugSearches;
  208. void DebugLibraryFailed(std::string const& name, std::string const& path)
  209. {
  210. if (this->DebugMode) {
  211. auto regexName =
  212. cmStrCat(this->PrefixRegexStr, name, this->SuffixRegexStr);
  213. this->DebugSearches.FailedAt(path, regexName);
  214. }
  215. }
  216. void DebugLibraryFound(std::string const& name, std::string const& path)
  217. {
  218. if (this->DebugMode) {
  219. auto regexName =
  220. cmStrCat(this->PrefixRegexStr, name, this->SuffixRegexStr);
  221. this->DebugSearches.FoundAt(path, regexName);
  222. }
  223. }
  224. };
  225. namespace {
  226. std::string const& get_prefixes(cmMakefile* mf)
  227. {
  228. #ifdef _WIN32
  229. static std::string defaultPrefix = ";lib";
  230. #else
  231. static std::string defaultPrefix = "lib";
  232. #endif
  233. cmValue prefixProp = mf->GetDefinition("CMAKE_FIND_LIBRARY_PREFIXES");
  234. return (prefixProp) ? *prefixProp : defaultPrefix;
  235. }
  236. std::string const& get_suffixes(cmMakefile* mf)
  237. {
  238. #ifdef _WIN32
  239. static std::string defaultSuffix = ".lib;.dll.a;.a";
  240. #elif defined(__APPLE__)
  241. static std::string defaultSuffix = ".tbd;.dylib;.so;.a";
  242. #elif defined(__hpux)
  243. static std::string defaultSuffix = ".sl;.so;.a";
  244. #else
  245. static std::string defaultSuffix = ".so;.a";
  246. #endif
  247. cmValue suffixProp = mf->GetDefinition("CMAKE_FIND_LIBRARY_SUFFIXES");
  248. return (suffixProp) ? *suffixProp : defaultSuffix;
  249. }
  250. }
  251. cmFindLibraryHelper::cmFindLibraryHelper(std::string debugName, cmMakefile* mf,
  252. cmFindBase const* base)
  253. : Makefile(mf)
  254. , DebugMode(base->DebugModeEnabled())
  255. , DebugSearches(std::move(debugName), base)
  256. {
  257. this->GG = this->Makefile->GetGlobalGenerator();
  258. // Collect the list of library name prefixes/suffixes to try.
  259. std::string const& prefixes_list = get_prefixes(this->Makefile);
  260. std::string const& suffixes_list = get_suffixes(this->Makefile);
  261. cmExpandList(prefixes_list, this->Prefixes, true);
  262. cmExpandList(suffixes_list, this->Suffixes, true);
  263. this->RegexFromList(this->PrefixRegexStr, this->Prefixes);
  264. this->RegexFromList(this->SuffixRegexStr, this->Suffixes);
  265. // Check whether to use OpenBSD-style library version comparisons.
  266. this->OpenBSD = this->Makefile->GetState()->GetGlobalPropertyAsBool(
  267. "FIND_LIBRARY_USE_OPENBSD_VERSIONING");
  268. }
  269. void cmFindLibraryHelper::RegexFromLiteral(std::string& out,
  270. std::string const& in)
  271. {
  272. for (char ch : in) {
  273. if (ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' ||
  274. ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' ||
  275. ch == '^' || ch == '$') {
  276. out += "\\";
  277. }
  278. #if defined(_WIN32) || defined(__APPLE__)
  279. out += static_cast<char>(tolower(ch));
  280. #else
  281. out += ch;
  282. #endif
  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::string const& s : in) {
  293. // Separate from previous item.
  294. out += sep;
  295. sep = "|";
  296. // Append this item.
  297. this->RegexFromLiteral(out, s);
  298. }
  299. out += ")";
  300. }
  301. bool cmFindLibraryHelper::HasValidSuffix(std::string const& name)
  302. {
  303. for (std::string suffix : this->Suffixes) {
  304. if (name.length() <= suffix.length()) {
  305. continue;
  306. }
  307. // Check if the given name ends in a valid library suffix.
  308. if (name.substr(name.size() - suffix.length()) == suffix) {
  309. return true;
  310. }
  311. // Check if a valid library suffix is somewhere in the name,
  312. // this may happen e.g. for versioned shared libraries: libfoo.so.2
  313. suffix += ".";
  314. if (name.find(suffix) != std::string::npos) {
  315. return true;
  316. }
  317. }
  318. return false;
  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 = cmStrCat('^', this->PrefixRegexStr);
  328. this->RegexFromLiteral(regex, name);
  329. regex += this->SuffixRegexStr;
  330. if (this->OpenBSD) {
  331. regex += "(\\.[0-9]+\\.[0-9]+)?";
  332. }
  333. regex += "$";
  334. entry.Regex.compile(regex);
  335. this->Names.push_back(std::move(entry));
  336. }
  337. void cmFindLibraryHelper::SetName(std::string const& name)
  338. {
  339. this->Names.clear();
  340. this->AddName(name);
  341. }
  342. bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
  343. {
  344. for (Name& i : this->Names) {
  345. if (this->CheckDirectoryForName(path, i)) {
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path,
  352. Name& name)
  353. {
  354. // If the original library name provided by the user matches one of
  355. // the suffixes, try it first. This allows users to search
  356. // specifically for a static library on some platforms (on MS tools
  357. // one cannot tell just from the library name whether it is a static
  358. // library or an import library).
  359. if (name.TryRaw) {
  360. this->TestPath = cmStrCat(path, name.Raw);
  361. const bool exists = cmSystemTools::FileExists(this->TestPath, true);
  362. if (!exists) {
  363. this->DebugLibraryFailed(name.Raw, path);
  364. } else {
  365. this->DebugLibraryFound(name.Raw, path);
  366. this->BestPath = cmSystemTools::CollapseFullPath(this->TestPath);
  367. cmSystemTools::ConvertToUnixSlashes(this->BestPath);
  368. return true;
  369. }
  370. }
  371. // No library file has yet been found.
  372. size_type bestPrefix = this->Prefixes.size();
  373. size_type bestSuffix = this->Suffixes.size();
  374. unsigned int bestMajor = 0;
  375. unsigned int bestMinor = 0;
  376. // Search for a file matching the library name regex.
  377. std::string dir = path;
  378. cmSystemTools::ConvertToUnixSlashes(dir);
  379. std::set<std::string> const& files = this->GG->GetDirectoryContent(dir);
  380. for (std::string const& origName : files) {
  381. #if defined(_WIN32) || defined(__APPLE__)
  382. std::string testName = cmSystemTools::LowerCase(origName);
  383. #else
  384. std::string const& testName = origName;
  385. #endif
  386. if (name.Regex.find(testName)) {
  387. this->TestPath = cmStrCat(path, origName);
  388. // Make sure the path is readable and is not a directory.
  389. if (cmSystemTools::FileExists(this->TestPath, true)) {
  390. this->DebugLibraryFound(name.Raw, dir);
  391. // This is a matching file. Check if it is better than the
  392. // best name found so far. Earlier prefixes are preferred,
  393. // followed by earlier suffixes. For OpenBSD, shared library
  394. // version extensions are compared.
  395. size_type prefix = this->GetPrefixIndex(name.Regex.match(1));
  396. size_type suffix = this->GetSuffixIndex(name.Regex.match(2));
  397. unsigned int major = 0;
  398. unsigned int minor = 0;
  399. if (this->OpenBSD) {
  400. sscanf(name.Regex.match(3).c_str(), ".%u.%u", &major, &minor);
  401. }
  402. if (this->BestPath.empty() || prefix < bestPrefix ||
  403. (prefix == bestPrefix && suffix < bestSuffix) ||
  404. (prefix == bestPrefix && suffix == bestSuffix &&
  405. (major > bestMajor ||
  406. (major == bestMajor && minor > bestMinor)))) {
  407. this->BestPath = this->TestPath;
  408. bestPrefix = prefix;
  409. bestSuffix = suffix;
  410. bestMajor = major;
  411. bestMinor = minor;
  412. }
  413. }
  414. }
  415. }
  416. if (this->BestPath.empty()) {
  417. this->DebugLibraryFailed(name.Raw, dir);
  418. } else {
  419. this->DebugLibraryFound(name.Raw, this->BestPath);
  420. }
  421. // Use the best candidate found in this directory, if any.
  422. return !this->BestPath.empty();
  423. }
  424. std::string cmFindLibraryCommand::FindNormalLibrary()
  425. {
  426. if (this->NamesPerDir) {
  427. return this->FindNormalLibraryNamesPerDir();
  428. }
  429. return this->FindNormalLibraryDirsPerName();
  430. }
  431. std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir()
  432. {
  433. // Search for all names in each directory.
  434. cmFindLibraryHelper helper(this->FindCommandName, this->Makefile, this);
  435. for (std::string const& n : this->Names) {
  436. helper.AddName(n);
  437. }
  438. // Search every directory.
  439. for (std::string const& sp : this->SearchPaths) {
  440. if (helper.CheckDirectory(sp)) {
  441. return helper.BestPath;
  442. }
  443. }
  444. // Couldn't find the library.
  445. return "";
  446. }
  447. std::string cmFindLibraryCommand::FindNormalLibraryDirsPerName()
  448. {
  449. // Search the entire path for each name.
  450. cmFindLibraryHelper helper(this->FindCommandName, this->Makefile, this);
  451. for (std::string const& n : this->Names) {
  452. // Switch to searching for this name.
  453. helper.SetName(n);
  454. // Search every directory.
  455. for (std::string const& sp : this->SearchPaths) {
  456. if (helper.CheckDirectory(sp)) {
  457. return helper.BestPath;
  458. }
  459. }
  460. }
  461. // Couldn't find the library.
  462. return "";
  463. }
  464. std::string cmFindLibraryCommand::FindFrameworkLibrary()
  465. {
  466. if (this->NamesPerDir) {
  467. return this->FindFrameworkLibraryNamesPerDir();
  468. }
  469. return this->FindFrameworkLibraryDirsPerName();
  470. }
  471. std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir()
  472. {
  473. std::string fwPath;
  474. // Search for all names in each search path.
  475. for (std::string const& d : this->SearchPaths) {
  476. for (std::string const& n : this->Names) {
  477. fwPath = cmStrCat(d, n, ".framework");
  478. if (cmSystemTools::FileIsDirectory(fwPath)) {
  479. return cmSystemTools::CollapseFullPath(fwPath);
  480. }
  481. }
  482. }
  483. // No framework found.
  484. return "";
  485. }
  486. std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName()
  487. {
  488. std::string fwPath;
  489. // Search for each name in all search paths.
  490. for (std::string const& n : this->Names) {
  491. for (std::string const& d : this->SearchPaths) {
  492. fwPath = cmStrCat(d, n, ".framework");
  493. if (cmSystemTools::FileIsDirectory(fwPath)) {
  494. return cmSystemTools::CollapseFullPath(fwPath);
  495. }
  496. }
  497. }
  498. // No framework found.
  499. return "";
  500. }
  501. bool cmFindLibrary(std::vector<std::string> const& args,
  502. cmExecutionStatus& status)
  503. {
  504. return cmFindLibraryCommand(status).InitialPass(args);
  505. }