cmFindLibraryCommand.cxx 15 KB

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