Imported Upstream version 2.8.9
[platform/upstream/cmake.git] / Source / cmFindLibraryCommand.cxx
1 /*============================================================================
2   CMake - Cross Platform Makefile Generator
3   Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4
5   Distributed under the OSI-approved BSD License (the "License");
6   see accompanying file Copyright.txt for details.
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the License for more information.
11 ============================================================================*/
12 #include "cmFindLibraryCommand.h"
13 #include "cmCacheManager.h"
14 #include <cmsys/Directory.hxx>
15 #include <cmsys/stl/algorithm>
16
17 cmFindLibraryCommand::cmFindLibraryCommand()
18
19   this->EnvironmentPath = "LIB";
20 }
21
22 //----------------------------------------------------------------------------
23 void cmFindLibraryCommand::GenerateDocumentation()
24 {
25   this->cmFindBase::GenerateDocumentation();
26   cmSystemTools::ReplaceString(this->GenericDocumentation,
27                                "FIND_XXX", "find_library");
28   cmSystemTools::ReplaceString(this->GenericDocumentation,
29                                "CMAKE_XXX_PATH", "CMAKE_LIBRARY_PATH");
30   cmSystemTools::ReplaceString(this->GenericDocumentation,
31                                "CMAKE_XXX_MAC_PATH",
32                                "CMAKE_FRAMEWORK_PATH");
33   cmSystemTools::ReplaceString(this->GenericDocumentation,
34                                "CMAKE_SYSTEM_XXX_MAC_PATH",
35                                "CMAKE_SYSTEM_FRAMEWORK_PATH");
36   cmSystemTools::ReplaceString(this->GenericDocumentation,
37                                "XXX_SYSTEM", "LIB");
38   cmSystemTools::ReplaceString(this->GenericDocumentation,
39                                "CMAKE_SYSTEM_XXX_PATH",
40                                "CMAKE_SYSTEM_LIBRARY_PATH");
41   cmSystemTools::ReplaceString(this->GenericDocumentation,
42                                "SEARCH_XXX_DESC", "library");
43   cmSystemTools::ReplaceString(this->GenericDocumentation,
44                                "SEARCH_XXX", "library");
45   cmSystemTools::ReplaceString(this->GenericDocumentation,
46                                "XXX_SUBDIR", "lib");
47   cmSystemTools::ReplaceString(
48     this->GenericDocumentation,
49     "XXX_EXTRA_PREFIX_ENTRY",
50     "   <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and\n");
51   cmSystemTools::ReplaceString(this->GenericDocumentation,
52                                "CMAKE_FIND_ROOT_PATH_MODE_XXX",
53                                "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY");
54   this->GenericDocumentation +=
55     "\n"
56     "If the library found is a framework, then VAR will be set to "
57     "the full path to the framework <fullPath>/A.framework. "
58     "When a full path to a framework is used as a library, "
59     "CMake will use a -framework A, and a -F<fullPath> to "
60     "link the framework to the target."
61     "\n"
62     "If the global property FIND_LIBRARY_USE_LIB64_PATHS is set all search "
63     "paths will be tested as normal, with \"64/\" appended, and with all "
64     "matches of \"lib/\" replaced with \"lib64/\". This property is "
65     "automatically set for the platforms that are known to need it if at "
66     "least one of the languages supported by the PROJECT command is enabled.";
67 }
68
69 // cmFindLibraryCommand
70 bool cmFindLibraryCommand
71 ::InitialPass(std::vector<std::string> const& argsIn, cmExecutionStatus &)
72 {
73   this->VariableDocumentation = "Path to a library.";
74   this->CMakePathName = "LIBRARY";
75   if(!this->ParseArguments(argsIn))
76     {
77     return false;
78     }
79   if(this->AlreadyInCache)
80     {
81     // If the user specifies the entry on the command line without a
82     // type we should add the type and docstring but keep the original
83     // value.
84     if(this->AlreadyInCacheWithoutMetaInfo)
85       {
86       this->Makefile->AddCacheDefinition(this->VariableName.c_str(), "",
87                                          this->VariableDocumentation.c_str(),
88                                          cmCacheManager::FILEPATH);
89       }
90     return true;
91     }
92
93   if(const char* abi_name =
94      this->Makefile->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI"))
95     {
96     std::string abi = abi_name;
97     if(abi.find("ELF N32") != abi.npos)
98       {
99       // Convert lib to lib32.
100       this->AddArchitecturePaths("32");
101       }
102     }
103
104   if(this->Makefile->GetCMakeInstance()
105      ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
106     {
107     // add special 64 bit paths if this is a 64 bit compile.
108     this->AddLib64Paths();
109     }
110
111   std::string library = this->FindLibrary();
112   if(library != "")
113     {
114     // Save the value in the cache
115     this->Makefile->AddCacheDefinition(this->VariableName.c_str(),
116                                        library.c_str(),
117                                        this->VariableDocumentation.c_str(),
118                                        cmCacheManager::FILEPATH);
119     return true;
120     }
121   std::string notfound = this->VariableName + "-NOTFOUND";
122   this->Makefile->AddCacheDefinition(this->VariableName.c_str(),
123                                      notfound.c_str(),
124                                      this->VariableDocumentation.c_str(),
125                                      cmCacheManager::FILEPATH);
126   return true;
127 }
128
129 //----------------------------------------------------------------------------
130 void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix)
131 {
132   std::vector<std::string> newPaths;
133   bool found = false;
134   std::string subpath = "lib";
135   subpath += suffix;
136   subpath += "/";
137   for(std::vector<std::string>::iterator i = this->SearchPaths.begin();
138       i != this->SearchPaths.end(); ++i)
139     {
140     // Try replacing lib/ with lib<suffix>/
141     std::string s = *i;
142     cmSystemTools::ReplaceString(s, "lib/", subpath.c_str());
143     if((s != *i) && cmSystemTools::FileIsDirectory(s.c_str()))
144       {
145       found = true;
146       newPaths.push_back(s);
147       }
148
149     // Now look for lib<suffix>
150     s = *i;
151     s += suffix;
152     if(cmSystemTools::FileIsDirectory(s.c_str()))
153       {
154       found = true;
155       newPaths.push_back(s);
156       }
157     // now add the original unchanged path
158     if(cmSystemTools::FileIsDirectory(i->c_str()))
159       {
160       newPaths.push_back(*i);
161       }
162     }
163
164   // If any new paths were found replace the original set.
165   if(found)
166     {
167     this->SearchPaths = newPaths;
168     }
169 }
170
171 void cmFindLibraryCommand::AddLib64Paths()
172 {  
173   std::string voidsize =
174     this->Makefile->GetSafeDefinition("CMAKE_SIZEOF_VOID_P");
175   int size = atoi(voidsize.c_str());
176   if(size != 8)
177     {
178     return;
179     }
180   std::vector<std::string> path64;
181   bool found64 = false;
182   for(std::vector<std::string>::iterator i = this->SearchPaths.begin(); 
183       i != this->SearchPaths.end(); ++i)
184     {
185     std::string s = *i;
186     std::string s2 = *i;
187     cmSystemTools::ReplaceString(s, "lib/", "lib64/");
188     // try to replace lib with lib64 and see if it is there,
189     // then prepend it to the path
190     // Note that all paths have trailing slashes.
191     if((s != *i) && cmSystemTools::FileIsDirectory(s.c_str()))
192       {
193       path64.push_back(s);
194       found64 = true;
195       }  
196     // now just add a 64 to the path name and if it is there,
197     // add it to the path
198     s2 += "64/";
199     if(cmSystemTools::FileIsDirectory(s2.c_str()))
200       {
201       found64 = true;
202       path64.push_back(s2);
203       } 
204     // now add the original unchanged path
205     if(cmSystemTools::FileIsDirectory(i->c_str()))
206       {
207       path64.push_back(*i);
208       }
209     }
210   // now replace the SearchPaths with the 64 bit converted path
211   // if any 64 bit paths were discovered
212   if(found64)
213     {
214     this->SearchPaths = path64;
215     }
216 }
217
218 //----------------------------------------------------------------------------
219 std::string cmFindLibraryCommand::FindLibrary()
220 {
221   std::string library;
222   if(this->SearchFrameworkFirst || this->SearchFrameworkOnly)
223     {
224     library = this->FindFrameworkLibrary();
225     }
226   if(library.empty() && !this->SearchFrameworkOnly)
227     {
228     library = this->FindNormalLibrary();
229     }
230   if(library.empty() && this->SearchFrameworkLast)
231     {
232     library = this->FindFrameworkLibrary();
233     }
234   return library;
235 }
236
237 //----------------------------------------------------------------------------
238 struct cmFindLibraryHelper
239 {
240   cmFindLibraryHelper(cmMakefile* mf);
241
242   // Context information.
243   cmMakefile* Makefile;
244   cmGlobalGenerator* GG;
245
246   // List of valid prefixes and suffixes.
247   std::vector<std::string> Prefixes;
248   std::vector<std::string> Suffixes;
249   std::string PrefixRegexStr;
250   std::string SuffixRegexStr;
251
252   // Keep track of the best library file found so far.
253   typedef std::vector<std::string>::size_type size_type;
254   std::string BestPath;
255   size_type BestPrefix;
256   size_type BestSuffix;
257
258   // Support for OpenBSD shared library naming: lib<name>.so.<major>.<minor>
259   bool OpenBSD;
260   unsigned int BestMajor;
261   unsigned int BestMinor;
262
263   // Current name under consideration.
264   cmsys::RegularExpression NameRegex;
265   bool TryRawName;
266   std::string RawName;
267
268   // Current full path under consideration.
269   std::string TestPath;
270
271   void RegexFromLiteral(std::string& out, std::string const& in);
272   void RegexFromList(std::string& out, std::vector<std::string> const& in);
273   size_type GetPrefixIndex(std::string const& prefix)
274     {
275     return cmsys_stl::find(this->Prefixes.begin(), this->Prefixes.end(),
276                            prefix) - this->Prefixes.begin();
277     }
278   size_type GetSuffixIndex(std::string const& suffix)
279     {
280     return cmsys_stl::find(this->Suffixes.begin(), this->Suffixes.end(),
281                            suffix) - this->Suffixes.begin();
282     }
283   bool HasValidSuffix(std::string const& name);
284   void SetName(std::string const& name);
285   bool CheckDirectory(std::string const& path);
286 };
287
288 //----------------------------------------------------------------------------
289 cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf):
290   Makefile(mf)
291 {
292   this->GG = this->Makefile->GetLocalGenerator()->GetGlobalGenerator();
293
294   // Collect the list of library name prefixes/suffixes to try.
295   const char* prefixes_list =
296     this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_PREFIXES");
297   const char* suffixes_list =
298     this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_SUFFIXES");
299   cmSystemTools::ExpandListArgument(prefixes_list, this->Prefixes, true);
300   cmSystemTools::ExpandListArgument(suffixes_list, this->Suffixes, true);
301   this->RegexFromList(this->PrefixRegexStr, this->Prefixes);
302   this->RegexFromList(this->SuffixRegexStr, this->Suffixes);
303
304   // Check whether to use OpenBSD-style library version comparisons.
305   this->OpenBSD =
306     this->Makefile->GetCMakeInstance()
307     ->GetPropertyAsBool("FIND_LIBRARY_USE_OPENBSD_VERSIONING");
308
309   this->TryRawName = false;
310
311   // No library file has yet been found.
312   this->BestPrefix = this->Prefixes.size();
313   this->BestSuffix = this->Suffixes.size();
314   this->BestMajor = 0;
315   this->BestMinor = 0;
316 }
317
318 //----------------------------------------------------------------------------
319 void cmFindLibraryHelper::RegexFromLiteral(std::string& out,
320                                            std::string const& in)
321 {
322   for(std::string::const_iterator ci = in.begin(); ci != in.end(); ++ci)
323     {
324     char ch = *ci;
325     if(ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' ||
326        ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' ||
327        ch == '^' || ch == '$')
328       {
329       out += "\\";
330       }
331 #if defined(_WIN32) || defined(__APPLE__)
332     out += tolower(ch);
333 #else
334     out += ch;
335 #endif
336     }
337 }
338
339 //----------------------------------------------------------------------------
340 void cmFindLibraryHelper::RegexFromList(std::string& out,
341                                         std::vector<std::string> const& in)
342 {
343   // Surround the list in parens so the '|' does not apply to anything
344   // else and the result can be checked after matching.
345   out += "(";
346   const char* sep = "";
347   for(std::vector<std::string>::const_iterator si = in.begin();
348       si != in.end(); ++si)
349     {
350     // Separate from previous item.
351     out += sep;
352     sep = "|";
353
354     // Append this item.
355     this->RegexFromLiteral(out, *si);
356     }
357   out += ")";
358 }
359
360 //----------------------------------------------------------------------------
361 bool cmFindLibraryHelper::HasValidSuffix(std::string const& name)
362 {
363   for(std::vector<std::string>::const_iterator si = this->Suffixes.begin();
364       si != this->Suffixes.end(); ++si)
365     {
366     std::string suffix = *si;
367     if(name.length() <= suffix.length())
368       {
369       continue;
370       }
371     // Check if the given name ends in a valid library suffix.
372     if(name.substr(name.size()-suffix.length()) == suffix)
373       {
374       return true;
375       }
376     // Check if a valid library suffix is somewhere in the name,
377     // this may happen e.g. for versioned shared libraries: libfoo.so.2
378     suffix += ".";
379     if(name.find(suffix) != name.npos)
380       {
381       return true;
382       }
383     }
384   return false;
385 }
386
387 //----------------------------------------------------------------------------
388 void cmFindLibraryHelper::SetName(std::string const& name)
389 {
390   // Consider checking the raw name too.
391   this->TryRawName = this->HasValidSuffix(name);
392   this->RawName = name;
393
394   // Build a regular expression to match library names.
395   std::string regex = "^";
396   regex += this->PrefixRegexStr;
397   this->RegexFromLiteral(regex, name);
398   regex += this->SuffixRegexStr;
399   if(this->OpenBSD)
400     {
401     regex += "(\\.[0-9]+\\.[0-9]+)?";
402     }
403   regex += "$";
404   this->NameRegex.compile(regex.c_str());
405 }
406
407 //----------------------------------------------------------------------------
408 bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
409 {
410   // If the original library name provided by the user matches one of
411   // the suffixes, try it first.  This allows users to search
412   // specifically for a static library on some platforms (on MS tools
413   // one cannot tell just from the library name whether it is a static
414   // library or an import library).
415   if(this->TryRawName)
416     {
417     this->TestPath = path;
418     this->TestPath += this->RawName;
419     if(cmSystemTools::FileExists(this->TestPath.c_str(), true))
420       {
421       this->BestPath =
422         cmSystemTools::CollapseFullPath(this->TestPath.c_str());
423       cmSystemTools::ConvertToUnixSlashes(this->BestPath);
424       return true;
425       }
426     }
427
428   // Search for a file matching the library name regex.
429   std::string dir = path;
430   cmSystemTools::ConvertToUnixSlashes(dir);
431   std::set<cmStdString> const& files = this->GG->GetDirectoryContent(dir);
432   for(std::set<cmStdString>::const_iterator fi = files.begin();
433       fi != files.end(); ++fi)
434     {
435     std::string const& origName = *fi;
436 #if defined(_WIN32) || defined(__APPLE__)
437     std::string testName = cmSystemTools::LowerCase(origName);
438 #else
439     std::string const& testName = origName;
440 #endif
441     if(this->NameRegex.find(testName))
442       {
443       this->TestPath = path;
444       this->TestPath += origName;
445       if(!cmSystemTools::FileIsDirectory(this->TestPath.c_str()))
446         {
447         // This is a matching file.  Check if it is better than the
448         // best name found so far.  Earlier prefixes are preferred,
449         // followed by earlier suffixes.  For OpenBSD, shared library
450         // version extensions are compared.
451         size_type prefix = this->GetPrefixIndex(this->NameRegex.match(1));
452         size_type suffix = this->GetSuffixIndex(this->NameRegex.match(2));
453         unsigned int major = 0;
454         unsigned int minor = 0;
455         if(this->OpenBSD)
456           {
457           sscanf(this->NameRegex.match(3).c_str(), ".%u.%u", &major, &minor);
458           }
459         if(this->BestPath.empty() || prefix < this->BestPrefix ||
460            (prefix == this->BestPrefix && suffix < this->BestSuffix) ||
461            (prefix == this->BestPrefix && suffix == this->BestSuffix &&
462             (major > this->BestMajor ||
463              (major == this->BestMajor && minor > this->BestMinor))))
464           {
465           this->BestPath = this->TestPath;
466           this->BestPrefix = prefix;
467           this->BestSuffix = suffix;
468           this->BestMajor = major;
469           this->BestMinor = minor;
470           }
471         }
472       }
473     }
474
475   // Use the best candidate found in this directory, if any.
476   return !this->BestPath.empty();
477 }
478
479 //----------------------------------------------------------------------------
480 std::string cmFindLibraryCommand::FindNormalLibrary()
481 {
482   // Search the entire path for each name.
483   cmFindLibraryHelper helper(this->Makefile);
484   for(std::vector<std::string>::const_iterator ni = this->Names.begin();
485       ni != this->Names.end() ; ++ni)
486     {
487     // Switch to searching for this name.
488     std::string const& name = *ni;
489     helper.SetName(name);
490
491     // Search every directory.
492     for(std::vector<std::string>::const_iterator
493           p = this->SearchPaths.begin();
494         p != this->SearchPaths.end(); ++p)
495       {
496       if(helper.CheckDirectory(*p))
497         {
498         return helper.BestPath;
499         }
500       }
501     }
502   // Couldn't find the library.
503   return "";
504 }
505
506 //----------------------------------------------------------------------------
507 std::string cmFindLibraryCommand::FindFrameworkLibrary()
508 {
509   // Search for a framework of each name in the entire search path.
510   for(std::vector<std::string>::const_iterator ni = this->Names.begin();
511       ni != this->Names.end() ; ++ni)
512     {
513     // Search the paths for a framework with this name.
514     std::string fwName = *ni;
515     fwName += ".framework";
516     std::string fwPath = cmSystemTools::FindDirectory(fwName.c_str(),
517                                                       this->SearchPaths,
518                                                       true);
519     if(!fwPath.empty())
520       {
521       return fwPath;
522       }
523     }
524
525   // No framework found.
526   return "";
527 }