cmFindLibraryCommand.cxx 15 KB

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