cmFindLibraryCommand.cxx 15 KB

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