cmFindLibraryCommand.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 = "^";
  277. regex += this->PrefixRegexStr;
  278. this->RegexFromLiteral(regex, name);
  279. regex += this->SuffixRegexStr;
  280. if (this->OpenBSD) {
  281. regex += "(\\.[0-9]+\\.[0-9]+)?";
  282. }
  283. regex += "$";
  284. entry.Regex.compile(regex.c_str());
  285. this->Names.push_back(std::move(entry));
  286. }
  287. void cmFindLibraryHelper::SetName(std::string const& name)
  288. {
  289. this->Names.clear();
  290. this->AddName(name);
  291. }
  292. bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
  293. {
  294. for (Name& i : this->Names) {
  295. if (this->CheckDirectoryForName(path, i)) {
  296. return true;
  297. }
  298. }
  299. return false;
  300. }
  301. bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path,
  302. Name& name)
  303. {
  304. // If the original library name provided by the user matches one of
  305. // the suffixes, try it first. This allows users to search
  306. // specifically for a static library on some platforms (on MS tools
  307. // one cannot tell just from the library name whether it is a static
  308. // library or an import library).
  309. if (name.TryRaw) {
  310. this->TestPath = path;
  311. this->TestPath += name.Raw;
  312. if (cmSystemTools::FileExists(this->TestPath, true)) {
  313. this->BestPath = cmSystemTools::CollapseFullPath(this->TestPath);
  314. cmSystemTools::ConvertToUnixSlashes(this->BestPath);
  315. return true;
  316. }
  317. }
  318. // No library file has yet been found.
  319. size_type bestPrefix = this->Prefixes.size();
  320. size_type bestSuffix = this->Suffixes.size();
  321. unsigned int bestMajor = 0;
  322. unsigned int bestMinor = 0;
  323. // Search for a file matching the library name regex.
  324. std::string dir = path;
  325. cmSystemTools::ConvertToUnixSlashes(dir);
  326. std::set<std::string> const& files = this->GG->GetDirectoryContent(dir);
  327. for (std::string const& origName : files) {
  328. #if defined(_WIN32) || defined(__APPLE__)
  329. std::string testName = cmSystemTools::LowerCase(origName);
  330. #else
  331. std::string const& testName = origName;
  332. #endif
  333. if (name.Regex.find(testName)) {
  334. this->TestPath = path;
  335. this->TestPath += origName;
  336. if (!cmSystemTools::FileIsDirectory(this->TestPath)) {
  337. // This is a matching file. Check if it is better than the
  338. // best name found so far. Earlier prefixes are preferred,
  339. // followed by earlier suffixes. For OpenBSD, shared library
  340. // version extensions are compared.
  341. size_type prefix = this->GetPrefixIndex(name.Regex.match(1));
  342. size_type suffix = this->GetSuffixIndex(name.Regex.match(2));
  343. unsigned int major = 0;
  344. unsigned int minor = 0;
  345. if (this->OpenBSD) {
  346. sscanf(name.Regex.match(3).c_str(), ".%u.%u", &major, &minor);
  347. }
  348. if (this->BestPath.empty() || prefix < bestPrefix ||
  349. (prefix == bestPrefix && suffix < bestSuffix) ||
  350. (prefix == bestPrefix && suffix == bestSuffix &&
  351. (major > bestMajor ||
  352. (major == bestMajor && minor > bestMinor)))) {
  353. this->BestPath = this->TestPath;
  354. bestPrefix = prefix;
  355. bestSuffix = suffix;
  356. bestMajor = major;
  357. bestMinor = minor;
  358. }
  359. }
  360. }
  361. }
  362. // Use the best candidate found in this directory, if any.
  363. return !this->BestPath.empty();
  364. }
  365. std::string cmFindLibraryCommand::FindNormalLibrary()
  366. {
  367. if (this->NamesPerDir) {
  368. return this->FindNormalLibraryNamesPerDir();
  369. }
  370. return this->FindNormalLibraryDirsPerName();
  371. }
  372. std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir()
  373. {
  374. // Search for all names in each directory.
  375. cmFindLibraryHelper helper(this->Makefile);
  376. for (std::string const& n : this->Names) {
  377. helper.AddName(n);
  378. }
  379. // Search every directory.
  380. for (std::string const& sp : this->SearchPaths) {
  381. if (helper.CheckDirectory(sp)) {
  382. return helper.BestPath;
  383. }
  384. }
  385. // Couldn't find the library.
  386. return "";
  387. }
  388. std::string cmFindLibraryCommand::FindNormalLibraryDirsPerName()
  389. {
  390. // Search the entire path for each name.
  391. cmFindLibraryHelper helper(this->Makefile);
  392. for (std::string const& n : this->Names) {
  393. // Switch to searching for this name.
  394. helper.SetName(n);
  395. // Search every directory.
  396. for (std::string const& sp : this->SearchPaths) {
  397. if (helper.CheckDirectory(sp)) {
  398. return helper.BestPath;
  399. }
  400. }
  401. }
  402. // Couldn't find the library.
  403. return "";
  404. }
  405. std::string cmFindLibraryCommand::FindFrameworkLibrary()
  406. {
  407. if (this->NamesPerDir) {
  408. return this->FindFrameworkLibraryNamesPerDir();
  409. }
  410. return this->FindFrameworkLibraryDirsPerName();
  411. }
  412. std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir()
  413. {
  414. std::string fwPath;
  415. // Search for all names in each search path.
  416. for (std::string const& d : this->SearchPaths) {
  417. for (std::string const& n : this->Names) {
  418. fwPath = d;
  419. fwPath += n;
  420. fwPath += ".framework";
  421. if (cmSystemTools::FileIsDirectory(fwPath)) {
  422. return cmSystemTools::CollapseFullPath(fwPath);
  423. }
  424. }
  425. }
  426. // No framework found.
  427. return "";
  428. }
  429. std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName()
  430. {
  431. std::string fwPath;
  432. // Search for each name in all search paths.
  433. for (std::string const& n : this->Names) {
  434. for (std::string const& d : this->SearchPaths) {
  435. fwPath = d;
  436. fwPath += n;
  437. fwPath += ".framework";
  438. if (cmSystemTools::FileIsDirectory(fwPath)) {
  439. return cmSystemTools::CollapseFullPath(fwPath);
  440. }
  441. }
  442. }
  443. // No framework found.
  444. return "";
  445. }