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