cmFindLibraryCommand.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 library = this->FindLibrary();
  65. if (library != "") {
  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::vector<std::string>::const_iterator i = original.begin();
  83. i != original.end(); ++i) {
  84. this->AddArchitecturePath(*i, 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(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;
  176. std::string Raw;
  177. cmsys::RegularExpression Regex;
  178. Name()
  179. : TryRaw(false)
  180. {
  181. }
  182. };
  183. std::vector<Name> Names;
  184. // Current full path under consideration.
  185. std::string TestPath;
  186. void RegexFromLiteral(std::string& out, std::string const& in);
  187. void RegexFromList(std::string& out, std::vector<std::string> const& in);
  188. size_type GetPrefixIndex(std::string const& prefix)
  189. {
  190. return std::find(this->Prefixes.begin(), this->Prefixes.end(), prefix) -
  191. this->Prefixes.begin();
  192. }
  193. size_type GetSuffixIndex(std::string const& suffix)
  194. {
  195. return std::find(this->Suffixes.begin(), this->Suffixes.end(), suffix) -
  196. this->Suffixes.begin();
  197. }
  198. bool HasValidSuffix(std::string const& name);
  199. void AddName(std::string const& name);
  200. void SetName(std::string const& name);
  201. bool CheckDirectory(std::string const& path);
  202. bool CheckDirectoryForName(std::string const& path, Name& name);
  203. };
  204. cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf)
  205. : Makefile(mf)
  206. {
  207. this->GG = this->Makefile->GetGlobalGenerator();
  208. // Collect the list of library name prefixes/suffixes to try.
  209. const char* prefixes_list =
  210. this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_PREFIXES");
  211. const char* suffixes_list =
  212. this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_SUFFIXES");
  213. cmSystemTools::ExpandListArgument(prefixes_list, this->Prefixes, true);
  214. cmSystemTools::ExpandListArgument(suffixes_list, this->Suffixes, true);
  215. this->RegexFromList(this->PrefixRegexStr, this->Prefixes);
  216. this->RegexFromList(this->SuffixRegexStr, this->Suffixes);
  217. // Check whether to use OpenBSD-style library version comparisons.
  218. this->OpenBSD = this->Makefile->GetState()->GetGlobalPropertyAsBool(
  219. "FIND_LIBRARY_USE_OPENBSD_VERSIONING");
  220. }
  221. void cmFindLibraryHelper::RegexFromLiteral(std::string& out,
  222. std::string const& in)
  223. {
  224. for (std::string::const_iterator ci = in.begin(); ci != in.end(); ++ci) {
  225. char ch = *ci;
  226. if (ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' ||
  227. ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' ||
  228. ch == '^' || ch == '$') {
  229. out += "\\";
  230. }
  231. #if defined(_WIN32) || defined(__APPLE__)
  232. out += tolower(ch);
  233. #else
  234. out += ch;
  235. #endif
  236. }
  237. }
  238. void cmFindLibraryHelper::RegexFromList(std::string& out,
  239. std::vector<std::string> const& in)
  240. {
  241. // Surround the list in parens so the '|' does not apply to anything
  242. // else and the result can be checked after matching.
  243. out += "(";
  244. const char* sep = "";
  245. for (std::vector<std::string>::const_iterator si = in.begin();
  246. si != in.end(); ++si) {
  247. // Separate from previous item.
  248. out += sep;
  249. sep = "|";
  250. // Append this item.
  251. this->RegexFromLiteral(out, *si);
  252. }
  253. out += ")";
  254. }
  255. bool cmFindLibraryHelper::HasValidSuffix(std::string const& name)
  256. {
  257. for (std::vector<std::string>::const_iterator si = this->Suffixes.begin();
  258. si != this->Suffixes.end(); ++si) {
  259. std::string suffix = *si;
  260. if (name.length() <= suffix.length()) {
  261. continue;
  262. }
  263. // Check if the given name ends in a valid library suffix.
  264. if (name.substr(name.size() - suffix.length()) == suffix) {
  265. return true;
  266. }
  267. // Check if a valid library suffix is somewhere in the name,
  268. // this may happen e.g. for versioned shared libraries: libfoo.so.2
  269. suffix += ".";
  270. if (name.find(suffix) != std::string::npos) {
  271. return true;
  272. }
  273. }
  274. return false;
  275. }
  276. void cmFindLibraryHelper::AddName(std::string const& name)
  277. {
  278. Name entry;
  279. // Consider checking the raw name too.
  280. entry.TryRaw = this->HasValidSuffix(name);
  281. entry.Raw = name;
  282. // Build a regular expression to match library names.
  283. std::string regex = "^";
  284. regex += this->PrefixRegexStr;
  285. this->RegexFromLiteral(regex, name);
  286. regex += this->SuffixRegexStr;
  287. if (this->OpenBSD) {
  288. regex += "(\\.[0-9]+\\.[0-9]+)?";
  289. }
  290. regex += "$";
  291. entry.Regex.compile(regex.c_str());
  292. this->Names.push_back(entry);
  293. }
  294. void cmFindLibraryHelper::SetName(std::string const& name)
  295. {
  296. this->Names.clear();
  297. this->AddName(name);
  298. }
  299. bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
  300. {
  301. for (std::vector<Name>::iterator i = this->Names.begin();
  302. i != this->Names.end(); ++i) {
  303. if (this->CheckDirectoryForName(path, *i)) {
  304. return true;
  305. }
  306. }
  307. return false;
  308. }
  309. bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path,
  310. Name& name)
  311. {
  312. // If the original library name provided by the user matches one of
  313. // the suffixes, try it first. This allows users to search
  314. // specifically for a static library on some platforms (on MS tools
  315. // one cannot tell just from the library name whether it is a static
  316. // library or an import library).
  317. if (name.TryRaw) {
  318. this->TestPath = path;
  319. this->TestPath += name.Raw;
  320. if (cmSystemTools::FileExists(this->TestPath.c_str(), true)) {
  321. this->BestPath = cmSystemTools::CollapseFullPath(this->TestPath);
  322. cmSystemTools::ConvertToUnixSlashes(this->BestPath);
  323. return true;
  324. }
  325. }
  326. // No library file has yet been found.
  327. size_type bestPrefix = this->Prefixes.size();
  328. size_type bestSuffix = this->Suffixes.size();
  329. unsigned int bestMajor = 0;
  330. unsigned int bestMinor = 0;
  331. // Search for a file matching the library name regex.
  332. std::string dir = path;
  333. cmSystemTools::ConvertToUnixSlashes(dir);
  334. std::set<std::string> const& files = this->GG->GetDirectoryContent(dir);
  335. for (std::set<std::string>::const_iterator fi = files.begin();
  336. fi != files.end(); ++fi) {
  337. std::string const& origName = *fi;
  338. #if defined(_WIN32) || defined(__APPLE__)
  339. std::string testName = cmSystemTools::LowerCase(origName);
  340. #else
  341. std::string const& testName = origName;
  342. #endif
  343. if (name.Regex.find(testName)) {
  344. this->TestPath = path;
  345. this->TestPath += origName;
  346. if (!cmSystemTools::FileIsDirectory(this->TestPath)) {
  347. // This is a matching file. Check if it is better than the
  348. // best name found so far. Earlier prefixes are preferred,
  349. // followed by earlier suffixes. For OpenBSD, shared library
  350. // version extensions are compared.
  351. size_type prefix = this->GetPrefixIndex(name.Regex.match(1));
  352. size_type suffix = this->GetSuffixIndex(name.Regex.match(2));
  353. unsigned int major = 0;
  354. unsigned int minor = 0;
  355. if (this->OpenBSD) {
  356. sscanf(name.Regex.match(3).c_str(), ".%u.%u", &major, &minor);
  357. }
  358. if (this->BestPath.empty() || prefix < bestPrefix ||
  359. (prefix == bestPrefix && suffix < bestSuffix) ||
  360. (prefix == bestPrefix && suffix == bestSuffix &&
  361. (major > bestMajor ||
  362. (major == bestMajor && minor > bestMinor)))) {
  363. this->BestPath = this->TestPath;
  364. bestPrefix = prefix;
  365. bestSuffix = suffix;
  366. bestMajor = major;
  367. bestMinor = minor;
  368. }
  369. }
  370. }
  371. }
  372. // Use the best candidate found in this directory, if any.
  373. return !this->BestPath.empty();
  374. }
  375. std::string cmFindLibraryCommand::FindNormalLibrary()
  376. {
  377. if (this->NamesPerDir) {
  378. return this->FindNormalLibraryNamesPerDir();
  379. }
  380. return this->FindNormalLibraryDirsPerName();
  381. }
  382. std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir()
  383. {
  384. // Search for all names in each directory.
  385. cmFindLibraryHelper helper(this->Makefile);
  386. for (std::vector<std::string>::const_iterator ni = this->Names.begin();
  387. ni != this->Names.end(); ++ni) {
  388. helper.AddName(*ni);
  389. }
  390. // Search every directory.
  391. for (std::vector<std::string>::const_iterator p = this->SearchPaths.begin();
  392. p != this->SearchPaths.end(); ++p) {
  393. if (helper.CheckDirectory(*p)) {
  394. return helper.BestPath;
  395. }
  396. }
  397. // Couldn't find the library.
  398. return "";
  399. }
  400. std::string cmFindLibraryCommand::FindNormalLibraryDirsPerName()
  401. {
  402. // Search the entire path for each name.
  403. cmFindLibraryHelper helper(this->Makefile);
  404. for (std::vector<std::string>::const_iterator ni = this->Names.begin();
  405. ni != this->Names.end(); ++ni) {
  406. // Switch to searching for this name.
  407. helper.SetName(*ni);
  408. // Search every directory.
  409. for (std::vector<std::string>::const_iterator p =
  410. this->SearchPaths.begin();
  411. p != this->SearchPaths.end(); ++p) {
  412. if (helper.CheckDirectory(*p)) {
  413. return helper.BestPath;
  414. }
  415. }
  416. }
  417. // Couldn't find the library.
  418. return "";
  419. }
  420. std::string cmFindLibraryCommand::FindFrameworkLibrary()
  421. {
  422. if (this->NamesPerDir) {
  423. return this->FindFrameworkLibraryNamesPerDir();
  424. }
  425. return this->FindFrameworkLibraryDirsPerName();
  426. }
  427. std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir()
  428. {
  429. std::string fwPath;
  430. // Search for all names in each search path.
  431. for (std::vector<std::string>::const_iterator di = this->SearchPaths.begin();
  432. di != this->SearchPaths.end(); ++di) {
  433. for (std::vector<std::string>::const_iterator ni = this->Names.begin();
  434. ni != this->Names.end(); ++ni) {
  435. fwPath = *di;
  436. fwPath += *ni;
  437. fwPath += ".framework";
  438. if (cmSystemTools::FileIsDirectory(fwPath)) {
  439. return cmSystemTools::CollapseFullPath(fwPath);
  440. }
  441. }
  442. }
  443. // No framework found.
  444. return "";
  445. }
  446. std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName()
  447. {
  448. std::string fwPath;
  449. // Search for each name in all search paths.
  450. for (std::vector<std::string>::const_iterator ni = this->Names.begin();
  451. ni != this->Names.end(); ++ni) {
  452. for (std::vector<std::string>::const_iterator di =
  453. this->SearchPaths.begin();
  454. di != this->SearchPaths.end(); ++di) {
  455. fwPath = *di;
  456. fwPath += *ni;
  457. fwPath += ".framework";
  458. if (cmSystemTools::FileIsDirectory(fwPath)) {
  459. return cmSystemTools::CollapseFullPath(fwPath);
  460. }
  461. }
  462. }
  463. // No framework found.
  464. return "";
  465. }