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