cmFindLibraryCommand.cxx 18 KB

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