cmFindLibraryCommand.cxx 17 KB

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