Support/Path: Deprecate Path::hasMagicNumber and replace all uses with fs::has_magic.
[oota-llvm.git] / lib / Support / Path.cpp
1 //===-- Path.cpp - Implement OS Path Concept --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This header file implements the operating system Path concept.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/Path.h"
15 #include "llvm/Config/config.h"
16 #include <cassert>
17 #include <cstring>
18 #include <ostream>
19 using namespace llvm;
20 using namespace sys;
21
22 //===----------------------------------------------------------------------===//
23 //=== WARNING: Implementation here must contain only TRULY operating system
24 //===          independent code.
25 //===----------------------------------------------------------------------===//
26
27 bool Path::operator==(const Path &that) const {
28   return path == that.path;
29 }
30
31 bool Path::operator<(const Path& that) const {
32   return path < that.path;
33 }
34
35 Path
36 Path::GetLLVMConfigDir() {
37   Path result;
38 #ifdef LLVM_ETCDIR
39   if (result.set(LLVM_ETCDIR))
40     return result;
41 #endif
42   return GetLLVMDefaultConfigDir();
43 }
44
45 LLVMFileType
46 sys::IdentifyFileType(const char *magic, unsigned length) {
47   assert(magic && "Invalid magic number string");
48   assert(length >=4 && "Invalid magic number length");
49   switch ((unsigned char)magic[0]) {
50     case 0xDE:  // 0x0B17C0DE = BC wraper
51       if (magic[1] == (char)0xC0 && magic[2] == (char)0x17 &&
52           magic[3] == (char)0x0B)
53         return Bitcode_FileType;
54       break;
55     case 'B':
56       if (magic[1] == 'C' && magic[2] == (char)0xC0 && magic[3] == (char)0xDE)
57         return Bitcode_FileType;
58       break;
59     case '!':
60       if (length >= 8)
61         if (memcmp(magic,"!<arch>\n",8) == 0)
62           return Archive_FileType;
63       break;
64
65     case '\177':
66       if (magic[1] == 'E' && magic[2] == 'L' && magic[3] == 'F') {
67         if (length >= 18 && magic[17] == 0)
68           switch (magic[16]) {
69             default: break;
70             case 1: return ELF_Relocatable_FileType;
71             case 2: return ELF_Executable_FileType;
72             case 3: return ELF_SharedObject_FileType;
73             case 4: return ELF_Core_FileType;
74           }
75       }
76       break;
77
78     case 0xCA:
79       if (magic[1] == char(0xFE) && magic[2] == char(0xBA) &&
80           magic[3] == char(0xBE)) {
81         // This is complicated by an overlap with Java class files.
82         // See the Mach-O section in /usr/share/file/magic for details.
83         if (length >= 8 && magic[7] < 43)
84           // FIXME: Universal Binary of any type.
85           return Mach_O_DynamicallyLinkedSharedLib_FileType;
86       }
87       break;
88
89     case 0xFE:
90     case 0xCE: {
91       uint16_t type = 0;
92       if (magic[0] == char(0xFE) && magic[1] == char(0xED) &&
93           magic[2] == char(0xFA) && magic[3] == char(0xCE)) {
94         /* Native endian */
95         if (length >= 16) type = magic[14] << 8 | magic[15];
96       } else if (magic[0] == char(0xCE) && magic[1] == char(0xFA) &&
97                  magic[2] == char(0xED) && magic[3] == char(0xFE)) {
98         /* Reverse endian */
99         if (length >= 14) type = magic[13] << 8 | magic[12];
100       }
101       switch (type) {
102         default: break;
103         case 1: return Mach_O_Object_FileType;
104         case 2: return Mach_O_Executable_FileType;
105         case 3: return Mach_O_FixedVirtualMemorySharedLib_FileType;
106         case 4: return Mach_O_Core_FileType;
107         case 5: return Mach_O_PreloadExecutable_FileType;
108         case 6: return Mach_O_DynamicallyLinkedSharedLib_FileType;
109         case 7: return Mach_O_DynamicLinker_FileType;
110         case 8: return Mach_O_Bundle_FileType;
111         case 9: return Mach_O_DynamicallyLinkedSharedLibStub_FileType;
112         case 10: break; // FIXME: MH_DSYM companion file with only debug.
113       }
114       break;
115     }
116     case 0xF0: // PowerPC Windows
117     case 0x83: // Alpha 32-bit
118     case 0x84: // Alpha 64-bit
119     case 0x66: // MPS R4000 Windows
120     case 0x50: // mc68K
121     case 0x4c: // 80386 Windows
122       if (magic[1] == 0x01)
123         return COFF_FileType;
124
125     case 0x90: // PA-RISC Windows
126     case 0x68: // mc68K Windows
127       if (magic[1] == 0x02)
128         return COFF_FileType;
129       break;
130     case 0x64: // x86-64 Windows.
131       if (magic[1] == char(0x86))
132         return COFF_FileType;
133       break;
134
135     default:
136       break;
137   }
138   return Unknown_FileType;
139 }
140
141 bool
142 Path::isArchive() const {
143   std::string Magic;
144   if (getMagicNumber(Magic, 8))
145     if (IdentifyFileType(Magic.c_str(), Magic.length()) == Archive_FileType)
146       return true;
147   return false;
148 }
149
150 bool
151 Path::isDynamicLibrary() const {
152   std::string Magic;
153   if (getMagicNumber(Magic, 64))
154     switch (IdentifyFileType(Magic.c_str(),
155                              static_cast<unsigned>(Magic.length()))) {
156       default: return false;
157       case Mach_O_FixedVirtualMemorySharedLib_FileType:
158       case Mach_O_DynamicallyLinkedSharedLib_FileType:
159       case Mach_O_DynamicallyLinkedSharedLibStub_FileType:
160       case ELF_SharedObject_FileType:
161       case COFF_FileType:  return true;
162     }
163
164   return false;
165 }
166
167 bool
168 Path::isObjectFile() const {
169   std::string Magic;
170   if (getMagicNumber(Magic, 64))
171     if (IdentifyFileType(Magic.c_str(),
172                          static_cast<unsigned>(Magic.length()))
173         != Unknown_FileType) {
174       // Everything in LLVMFileType is currently an object file.
175       return true;
176     }
177
178   return false;
179 }
180
181 Path
182 Path::FindLibrary(std::string& name) {
183   std::vector<sys::Path> LibPaths;
184   GetSystemLibraryPaths(LibPaths);
185   for (unsigned i = 0; i < LibPaths.size(); ++i) {
186     sys::Path FullPath(LibPaths[i]);
187     FullPath.appendComponent("lib" + name + LTDL_SHLIB_EXT);
188     if (FullPath.isDynamicLibrary())
189       return FullPath;
190     FullPath.eraseSuffix();
191     FullPath.appendSuffix("a");
192     if (FullPath.isArchive())
193       return FullPath;
194   }
195   return sys::Path();
196 }
197
198 StringRef Path::GetDLLSuffix() {
199   return &(LTDL_SHLIB_EXT[1]);
200 }
201
202 void
203 Path::appendSuffix(StringRef suffix) {
204   if (!suffix.empty()) {
205     path.append(".");
206     path.append(suffix);
207   }
208 }
209
210 bool
211 Path::isBitcodeFile() const {
212   std::string actualMagic;
213   if (!getMagicNumber(actualMagic, 4))
214     return false;
215   LLVMFileType FT =
216     IdentifyFileType(actualMagic.c_str(),
217                      static_cast<unsigned>(actualMagic.length()));
218   return FT == Bitcode_FileType;
219 }
220
221 bool Path::hasMagicNumber(StringRef Magic) const {
222   std::string actualMagic;
223   if (getMagicNumber(actualMagic, static_cast<unsigned>(Magic.size())))
224     return Magic == actualMagic;
225   return false;
226 }
227
228 static void getPathList(const char*path, std::vector<Path>& Paths) {
229   const char* at = path;
230   const char* delim = strchr(at, PathSeparator);
231   Path tmpPath;
232   while (delim != 0) {
233     std::string tmp(at, size_t(delim-at));
234     if (tmpPath.set(tmp))
235       if (tmpPath.canRead())
236         Paths.push_back(tmpPath);
237     at = delim + 1;
238     delim = strchr(at, PathSeparator);
239   }
240
241   if (*at != 0)
242     if (tmpPath.set(std::string(at)))
243       if (tmpPath.canRead())
244         Paths.push_back(tmpPath);
245 }
246
247 static StringRef getDirnameCharSep(StringRef path, const char *Sep) {
248   assert(Sep[0] != '\0' && Sep[1] == '\0' &&
249          "Sep must be a 1-character string literal.");
250   if (path.empty())
251     return ".";
252
253   // If the path is all slashes, return a single slash.
254   // Otherwise, remove all trailing slashes.
255
256   signed pos = static_cast<signed>(path.size()) - 1;
257
258   while (pos >= 0 && path[pos] == Sep[0])
259     --pos;
260
261   if (pos < 0)
262     return path[0] == Sep[0] ? Sep : ".";
263
264   // Any slashes left?
265   signed i = 0;
266
267   while (i < pos && path[i] != Sep[0])
268     ++i;
269
270   if (i == pos) // No slashes?  Return "."
271     return ".";
272
273   // There is at least one slash left.  Remove all trailing non-slashes.
274   while (pos >= 0 && path[pos] != Sep[0])
275     --pos;
276
277   // Remove any trailing slashes.
278   while (pos >= 0 && path[pos] == Sep[0])
279     --pos;
280
281   if (pos < 0)
282     return path[0] == Sep[0] ? Sep : ".";
283
284   return path.substr(0, pos+1);
285 }
286
287 // Include the truly platform-specific parts of this class.
288 #if defined(LLVM_ON_UNIX)
289 #include "Unix/Path.inc"
290 #endif
291 #if defined(LLVM_ON_WIN32)
292 #include "Windows/Path.inc"
293 #endif