cmFindLibraryCommand.cxx 16.2 KB
Newer Older
1 2 3
/*============================================================================
  CMake - Cross Platform Makefile Generator
  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4

5 6
  Distributed under the OSI-approved BSD License (the "License");
  see accompanying file Copyright.txt for details.
7

8 9 10 11
  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License for more information.
============================================================================*/
12
#include "cmFindLibraryCommand.h"
13
#include "cmCacheManager.h"
14 15
#include <cmsys/Directory.hxx>
#include <cmsys/stl/algorithm>
16

Bill Hoffman's avatar
Bill Hoffman committed
17 18
cmFindLibraryCommand::cmFindLibraryCommand()
{ 
Brad King's avatar
Brad King committed
19 20 21 22 23 24 25
  this->EnvironmentPath = "LIB";
}

//----------------------------------------------------------------------------
void cmFindLibraryCommand::GenerateDocumentation()
{
  this->cmFindBase::GenerateDocumentation();
Bill Hoffman's avatar
Bill Hoffman committed
26
  cmSystemTools::ReplaceString(this->GenericDocumentation,
27
                               "FIND_XXX", "find_library");
Bill Hoffman's avatar
Bill Hoffman committed
28 29
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "CMAKE_XXX_PATH", "CMAKE_LIBRARY_PATH");
30 31 32 33 34 35
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "CMAKE_XXX_MAC_PATH",
                               "CMAKE_FRAMEWORK_PATH");
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "CMAKE_SYSTEM_XXX_MAC_PATH",
                               "CMAKE_SYSTEM_FRAMEWORK_PATH");
Bill Hoffman's avatar
Bill Hoffman committed
36 37 38
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "XXX_SYSTEM", "LIB");
  cmSystemTools::ReplaceString(this->GenericDocumentation,
Brad King's avatar
Brad King committed
39
                               "CMAKE_SYSTEM_XXX_PATH",
Ken Martin's avatar
Ken Martin committed
40
                               "CMAKE_SYSTEM_LIBRARY_PATH");
Bill Hoffman's avatar
Bill Hoffman committed
41 42 43 44
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "SEARCH_XXX_DESC", "library");
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "SEARCH_XXX", "library");
45 46
  cmSystemTools::ReplaceString(this->GenericDocumentation,
                               "XXX_SUBDIR", "lib");
47 48 49 50
  cmSystemTools::ReplaceString(
    this->GenericDocumentation,
    "XXX_EXTRA_PREFIX_ENTRY",
    "   <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and\n");
Alexander Neundorf's avatar
 
Alexander Neundorf committed
51
  cmSystemTools::ReplaceString(this->GenericDocumentation,
Brad King's avatar
Brad King committed
52
                               "CMAKE_FIND_ROOT_PATH_MODE_XXX",
Alexander Neundorf's avatar
 
Alexander Neundorf committed
53
                               "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY");
Brad King's avatar
Brad King committed
54
  this->GenericDocumentation +=
Bill Hoffman's avatar
Bill Hoffman committed
55
    "\n"
56
    "If the library found is a framework, then VAR will be set to "
Bill Hoffman's avatar
Bill Hoffman committed
57 58 59
    "the full path to the framework <fullPath>/A.framework. "
    "When a full path to a framework is used as a library, "
    "CMake will use a -framework A, and a -F<fullPath> to "
60 61 62 63 64 65 66
    "link the framework to the target."
    "\n"
    "If the global property FIND_LIBRARY_USE_LIB64_PATHS is set all search "
    "paths will be tested as normal, with \"64/\" appended, and with all "
    "matches of \"lib/\" replaced with \"lib64/\". This property is "
    "automatically set for the platforms that are known to need it if at "
    "least one of the languages supported by the PROJECT command is enabled.";
Bill Hoffman's avatar
Bill Hoffman committed
67 68
}

69
// cmFindLibraryCommand
70 71
bool cmFindLibraryCommand
::InitialPass(std::vector<std::string> const& argsIn, cmExecutionStatus &)
72
{
Bill Hoffman's avatar
Bill Hoffman committed
73 74 75
  this->VariableDocumentation = "Path to a library.";
  this->CMakePathName = "LIBRARY";
  if(!this->ParseArguments(argsIn))
76 77
    {
    return false;
Bill Hoffman's avatar
Bill Hoffman committed
78 79
    }
  if(this->AlreadyInCache)
80
    {
81 82 83 84 85 86 87 88 89
    // If the user specifies the entry on the command line without a
    // type we should add the type and docstring but keep the original
    // value.
    if(this->AlreadyInCacheWithoutMetaInfo)
      {
      this->Makefile->AddCacheDefinition(this->VariableName.c_str(), "",
                                         this->VariableDocumentation.c_str(),
                                         cmCacheManager::FILEPATH);
      }
Bill Hoffman's avatar
Bill Hoffman committed
90
    return true;
91
    }
92

93
  if(const char* abi_name =
94 95
     this->Makefile->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI"))
    {
96 97
    std::string abi = abi_name;
    if(abi.find("ELF N32") != abi.npos)
98
      {
99 100 101
      // Convert lib to lib32.
      this->AddArchitecturePaths("32");
      }
102 103
    }

104 105 106 107
  if(this->Makefile->GetCMakeInstance()
     ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
    {
    // add special 64 bit paths if this is a 64 bit compile.
108 109 110 111
    if(this->Makefile->PlatformIs64Bit())
      {
      this->AddArchitecturePaths("64");
      }
112 113
    }

114 115
  std::string library = this->FindLibrary();
  if(library != "")
Bill Hoffman's avatar
Bill Hoffman committed
116
    {
117 118 119 120 121 122
    // Save the value in the cache
    this->Makefile->AddCacheDefinition(this->VariableName.c_str(),
                                       library.c_str(),
                                       this->VariableDocumentation.c_str(),
                                       cmCacheManager::FILEPATH);
    return true;
Bill Hoffman's avatar
Bill Hoffman committed
123 124
    }
  std::string notfound = this->VariableName + "-NOTFOUND";
Ken Martin's avatar
Ken Martin committed
125 126 127 128
  this->Makefile->AddCacheDefinition(this->VariableName.c_str(),
                                     notfound.c_str(),
                                     this->VariableDocumentation.c_str(),
                                     cmCacheManager::FILEPATH);
Bill Hoffman's avatar
Bill Hoffman committed
129 130 131
  return true;
}

132
//----------------------------------------------------------------------------
133
void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix)
134
{
135 136 137 138 139
  std::vector<std::string> newPaths;
  bool found = false;
  std::string subpath = "lib";
  subpath += suffix;
  subpath += "/";
140 141 142
  for(std::vector<std::string>::iterator i = this->SearchPaths.begin();
      i != this->SearchPaths.end(); ++i)
    {
143
    // Try replacing lib/ with lib<suffix>/
144
    std::string s = *i;
145
    cmSystemTools::ReplaceString(s, "lib/", subpath.c_str());
146 147
    if((s != *i) && cmSystemTools::FileIsDirectory(s.c_str()))
      {
148 149
      found = true;
      newPaths.push_back(s);
150
      }
151 152 153 154

    // Now look for lib<suffix>
    s = *i;
    s += suffix;
155
    s += "/";
156
    if(cmSystemTools::FileIsDirectory(s.c_str()))
157
      {
158 159
      found = true;
      newPaths.push_back(s);
160 161 162 163
      }
    // now add the original unchanged path
    if(cmSystemTools::FileIsDirectory(i->c_str()))
      {
164
      newPaths.push_back(*i);
165 166
      }
    }
167 168 169

  // If any new paths were found replace the original set.
  if(found)
170
    {
171
    this->SearchPaths = newPaths;
172 173
    }
}
174

175 176
//----------------------------------------------------------------------------
std::string cmFindLibraryCommand::FindLibrary()
Bill Hoffman's avatar
Bill Hoffman committed
177
{
178 179
  std::string library;
  if(this->SearchFrameworkFirst || this->SearchFrameworkOnly)
180
    {
181
    library = this->FindFrameworkLibrary();
Bill Hoffman's avatar
Bill Hoffman committed
182
    }
183
  if(library.empty() && !this->SearchFrameworkOnly)
Bill Hoffman's avatar
Bill Hoffman committed
184
    {
185
    library = this->FindNormalLibrary();
Bill Hoffman's avatar
Bill Hoffman committed
186
    }
187 188 189 190 191 192 193 194
  if(library.empty() && this->SearchFrameworkLast)
    {
    library = this->FindFrameworkLibrary();
    }
  return library;
}

//----------------------------------------------------------------------------
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
struct cmFindLibraryHelper
{
  cmFindLibraryHelper(cmMakefile* mf);

  // Context information.
  cmMakefile* Makefile;
  cmGlobalGenerator* GG;

  // List of valid prefixes and suffixes.
  std::vector<std::string> Prefixes;
  std::vector<std::string> Suffixes;
  std::string PrefixRegexStr;
  std::string SuffixRegexStr;

  // Keep track of the best library file found so far.
  typedef std::vector<std::string>::size_type size_type;
  std::string BestPath;
  size_type BestPrefix;
  size_type BestSuffix;

215 216 217 218 219
  // Support for OpenBSD shared library naming: lib<name>.so.<major>.<minor>
  bool OpenBSD;
  unsigned int BestMajor;
  unsigned int BestMinor;

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  // Current name under consideration.
  cmsys::RegularExpression NameRegex;
  bool TryRawName;
  std::string RawName;

  // Current full path under consideration.
  std::string TestPath;

  void RegexFromLiteral(std::string& out, std::string const& in);
  void RegexFromList(std::string& out, std::vector<std::string> const& in);
  size_type GetPrefixIndex(std::string const& prefix)
    {
    return cmsys_stl::find(this->Prefixes.begin(), this->Prefixes.end(),
                           prefix) - this->Prefixes.begin();
    }
  size_type GetSuffixIndex(std::string const& suffix)
    {
    return cmsys_stl::find(this->Suffixes.begin(), this->Suffixes.end(),
                           suffix) - this->Suffixes.begin();
    }
  bool HasValidSuffix(std::string const& name);
  void SetName(std::string const& name);
  bool CheckDirectory(std::string const& path);
};

//----------------------------------------------------------------------------
cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf):
  Makefile(mf)
248
{
249 250
  this->GG = this->Makefile->GetLocalGenerator()->GetGlobalGenerator();

251
  // Collect the list of library name prefixes/suffixes to try.
Bill Hoffman's avatar
Bill Hoffman committed
252
  const char* prefixes_list =
Ken Martin's avatar
Ken Martin committed
253
    this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_PREFIXES");
Bill Hoffman's avatar
Bill Hoffman committed
254
  const char* suffixes_list =
Ken Martin's avatar
Ken Martin committed
255
    this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_SUFFIXES");
256 257 258 259
  cmSystemTools::ExpandListArgument(prefixes_list, this->Prefixes, true);
  cmSystemTools::ExpandListArgument(suffixes_list, this->Suffixes, true);
  this->RegexFromList(this->PrefixRegexStr, this->Prefixes);
  this->RegexFromList(this->SuffixRegexStr, this->Suffixes);
260

261 262 263 264 265
  // Check whether to use OpenBSD-style library version comparisons.
  this->OpenBSD =
    this->Makefile->GetCMakeInstance()
    ->GetPropertyAsBool("FIND_LIBRARY_USE_OPENBSD_VERSIONING");

266 267 268 269 270
  this->TryRawName = false;

  // No library file has yet been found.
  this->BestPrefix = this->Prefixes.size();
  this->BestSuffix = this->Suffixes.size();
271 272
  this->BestMajor = 0;
  this->BestMinor = 0;
273 274 275 276 277 278 279
}

//----------------------------------------------------------------------------
void cmFindLibraryHelper::RegexFromLiteral(std::string& out,
                                           std::string const& in)
{
  for(std::string::const_iterator ci = in.begin(); ci != in.end(); ++ci)
Bill Hoffman's avatar
Bill Hoffman committed
280
    {
281 282 283 284
    char ch = *ci;
    if(ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' ||
       ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' ||
       ch == '^' || ch == '$')
285
      {
286
      out += "\\";
287
      }
288 289 290 291 292 293 294
#if defined(_WIN32) || defined(__APPLE__)
    out += tolower(ch);
#else
    out += ch;
#endif
    }
}
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
//----------------------------------------------------------------------------
void cmFindLibraryHelper::RegexFromList(std::string& out,
                                        std::vector<std::string> const& in)
{
  // Surround the list in parens so the '|' does not apply to anything
  // else and the result can be checked after matching.
  out += "(";
  const char* sep = "";
  for(std::vector<std::string>::const_iterator si = in.begin();
      si != in.end(); ++si)
    {
    // Separate from previous item.
    out += sep;
    sep = "|";

    // Append this item.
    this->RegexFromLiteral(out, *si);
    }
  out += ")";
}

//----------------------------------------------------------------------------
bool cmFindLibraryHelper::HasValidSuffix(std::string const& name)
{
  for(std::vector<std::string>::const_iterator si = this->Suffixes.begin();
      si != this->Suffixes.end(); ++si)
    {
323 324 325 326 327 328 329 330 331 332 333 334 335 336
    std::string suffix = *si;
    if(name.length() <= suffix.length())
      {
      continue;
      }
    // Check if the given name ends in a valid library suffix.
    if(name.substr(name.size()-suffix.length()) == suffix)
      {
      return true;
      }
    // Check if a valid library suffix is somewhere in the name,
    // this may happen e.g. for versioned shared libraries: libfoo.so.2
    suffix += ".";
    if(name.find(suffix) != name.npos)
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
      {
      return true;
      }
    }
  return false;
}

//----------------------------------------------------------------------------
void cmFindLibraryHelper::SetName(std::string const& name)
{
  // Consider checking the raw name too.
  this->TryRawName = this->HasValidSuffix(name);
  this->RawName = name;

  // Build a regular expression to match library names.
  std::string regex = "^";
  regex += this->PrefixRegexStr;
  this->RegexFromLiteral(regex, name);
  regex += this->SuffixRegexStr;
356 357 358 359
  if(this->OpenBSD)
    {
    regex += "(\\.[0-9]+\\.[0-9]+)?";
    }
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
  regex += "$";
  this->NameRegex.compile(regex.c_str());
}

//----------------------------------------------------------------------------
bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
{
  // If the original library name provided by the user matches one of
  // the suffixes, try it first.  This allows users to search
  // specifically for a static library on some platforms (on MS tools
  // one cannot tell just from the library name whether it is a static
  // library or an import library).
  if(this->TryRawName)
    {
    this->TestPath = path;
    this->TestPath += this->RawName;
    if(cmSystemTools::FileExists(this->TestPath.c_str(), true))
      {
      this->BestPath =
        cmSystemTools::CollapseFullPath(this->TestPath.c_str());
      cmSystemTools::ConvertToUnixSlashes(this->BestPath);
      return true;
      }
    }

  // Search for a file matching the library name regex.
  std::string dir = path;
  cmSystemTools::ConvertToUnixSlashes(dir);
  std::set<cmStdString> const& files = this->GG->GetDirectoryContent(dir);
  for(std::set<cmStdString>::const_iterator fi = files.begin();
      fi != files.end(); ++fi)
    {
    std::string const& origName = *fi;
#if defined(_WIN32) || defined(__APPLE__)
    std::string testName = cmSystemTools::LowerCase(origName);
#else
    std::string const& testName = origName;
#endif
    if(this->NameRegex.find(testName))
399
      {
400 401 402
      this->TestPath = path;
      this->TestPath += origName;
      if(!cmSystemTools::FileIsDirectory(this->TestPath.c_str()))
403
        {
404 405
        // This is a matching file.  Check if it is better than the
        // best name found so far.  Earlier prefixes are preferred,
406 407
        // followed by earlier suffixes.  For OpenBSD, shared library
        // version extensions are compared.
408 409
        size_type prefix = this->GetPrefixIndex(this->NameRegex.match(1));
        size_type suffix = this->GetSuffixIndex(this->NameRegex.match(2));
410 411 412 413 414 415
        unsigned int major = 0;
        unsigned int minor = 0;
        if(this->OpenBSD)
          {
          sscanf(this->NameRegex.match(3).c_str(), ".%u.%u", &major, &minor);
          }
416
        if(this->BestPath.empty() || prefix < this->BestPrefix ||
417 418 419 420
           (prefix == this->BestPrefix && suffix < this->BestSuffix) ||
           (prefix == this->BestPrefix && suffix == this->BestSuffix &&
            (major > this->BestMajor ||
             (major == this->BestMajor && minor > this->BestMinor))))
421
          {
422 423 424
          this->BestPath = this->TestPath;
          this->BestPrefix = prefix;
          this->BestSuffix = suffix;
425 426
          this->BestMajor = major;
          this->BestMinor = minor;
427
          }
428
        }
429 430
      }
    }
431

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  // Use the best candidate found in this directory, if any.
  return !this->BestPath.empty();
}

//----------------------------------------------------------------------------
std::string cmFindLibraryCommand::FindNormalLibrary()
{
  // Search the entire path for each name.
  cmFindLibraryHelper helper(this->Makefile);
  for(std::vector<std::string>::const_iterator ni = this->Names.begin();
      ni != this->Names.end() ; ++ni)
    {
    // Switch to searching for this name.
    std::string const& name = *ni;
    helper.SetName(name);

    // Search every directory.
    for(std::vector<std::string>::const_iterator
          p = this->SearchPaths.begin();
        p != this->SearchPaths.end(); ++p)
      {
      if(helper.CheckDirectory(*p))
454
        {
455
        return helper.BestPath;
456
        }
457 458
      }
    }
Bill Hoffman's avatar
Bill Hoffman committed
459 460
  // Couldn't find the library.
  return "";
461
}
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

//----------------------------------------------------------------------------
std::string cmFindLibraryCommand::FindFrameworkLibrary()
{
  // Search for a framework of each name in the entire search path.
  for(std::vector<std::string>::const_iterator ni = this->Names.begin();
      ni != this->Names.end() ; ++ni)
    {
    // Search the paths for a framework with this name.
    std::string fwName = *ni;
    fwName += ".framework";
    std::string fwPath = cmSystemTools::FindDirectory(fwName.c_str(),
                                                      this->SearchPaths,
                                                      true);
    if(!fwPath.empty())
      {
      return fwPath;
      }
    }

  // No framework found.
  return "";
}