cmFindLibraryCommand.cxx 17 KB

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