cmFindLibraryCommand.cxx 17 KB

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