xref: /freebsd/contrib/llvm-project/llvm/lib/BinaryFormat/Magic.cpp (revision 13ec1e3155c7e9bf037b12af186351b7fa9b9450)
1 //===- llvm/BinaryFormat/Magic.cpp - File magic identification --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/BinaryFormat/Magic.h"
10 #include "llvm/ADT/StringRef.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/BinaryFormat/COFF.h"
13 #include "llvm/BinaryFormat/ELF.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/Support/Endian.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 
19 #if !defined(_MSC_VER) && !defined(__MINGW32__)
20 #include <unistd.h>
21 #else
22 #include <io.h>
23 #endif
24 
25 using namespace llvm;
26 using namespace llvm::support::endian;
27 using namespace llvm::sys::fs;
28 
29 template <size_t N>
30 static bool startswith(StringRef Magic, const char (&S)[N]) {
31   return Magic.startswith(StringRef(S, N - 1));
32 }
33 
34 /// Identify the magic in magic.
35 file_magic llvm::identify_magic(StringRef Magic) {
36   if (Magic.size() < 4)
37     return file_magic::unknown;
38   switch ((unsigned char)Magic[0]) {
39   case 0x00: {
40     // COFF bigobj, CL.exe's LTO object file, or short import library file
41     if (startswith(Magic, "\0\0\xFF\xFF")) {
42       size_t MinSize =
43           offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
44       if (Magic.size() < MinSize)
45         return file_magic::coff_import_library;
46 
47       const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
48       if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) == 0)
49         return file_magic::coff_object;
50       if (memcmp(Start, COFF::ClGlObjMagic, sizeof(COFF::BigObjMagic)) == 0)
51         return file_magic::coff_cl_gl_object;
52       return file_magic::coff_import_library;
53     }
54     // Windows resource file
55     if (Magic.size() >= sizeof(COFF::WinResMagic) &&
56         memcmp(Magic.data(), COFF::WinResMagic, sizeof(COFF::WinResMagic)) == 0)
57       return file_magic::windows_resource;
58     // 0x0000 = COFF unknown machine type
59     if (Magic[1] == 0)
60       return file_magic::coff_object;
61     if (startswith(Magic, "\0asm"))
62       return file_magic::wasm_object;
63     break;
64   }
65 
66   case 0x01:
67     // XCOFF format
68     if (startswith(Magic, "\x01\xDF"))
69       return file_magic::xcoff_object_32;
70     if (startswith(Magic, "\x01\xF7"))
71       return file_magic::xcoff_object_64;
72     break;
73 
74   case 0x03:
75     if (startswith(Magic, "\x03\xF0\x00"))
76       return file_magic::goff_object;
77     break;
78 
79   case 0xDE: // 0x0B17C0DE = BC wraper
80     if (startswith(Magic, "\xDE\xC0\x17\x0B"))
81       return file_magic::bitcode;
82     break;
83   case 'B':
84     if (startswith(Magic, "BC\xC0\xDE"))
85       return file_magic::bitcode;
86     break;
87   case '!':
88     if (startswith(Magic, "!<arch>\n") || startswith(Magic, "!<thin>\n"))
89       return file_magic::archive;
90     break;
91 
92   case '\177':
93     if (startswith(Magic, "\177ELF") && Magic.size() >= 18) {
94       bool Data2MSB = Magic[5] == 2;
95       unsigned high = Data2MSB ? 16 : 17;
96       unsigned low = Data2MSB ? 17 : 16;
97       if (Magic[high] == 0) {
98         switch (Magic[low]) {
99         default:
100           return file_magic::elf;
101         case 1:
102           return file_magic::elf_relocatable;
103         case 2:
104           return file_magic::elf_executable;
105         case 3:
106           return file_magic::elf_shared_object;
107         case 4:
108           return file_magic::elf_core;
109         }
110       }
111       // It's still some type of ELF file.
112       return file_magic::elf;
113     }
114     break;
115 
116   case 0xCA:
117     if (startswith(Magic, "\xCA\xFE\xBA\xBE") ||
118         startswith(Magic, "\xCA\xFE\xBA\xBF")) {
119       // This is complicated by an overlap with Java class files.
120       // See the Mach-O section in /usr/share/file/magic for details.
121       if (Magic.size() >= 8 && Magic[7] < 43)
122         return file_magic::macho_universal_binary;
123     }
124     break;
125 
126   // The two magic numbers for mach-o are:
127   // 0xfeedface - 32-bit mach-o
128   // 0xfeedfacf - 64-bit mach-o
129   case 0xFE:
130   case 0xCE:
131   case 0xCF: {
132     uint16_t type = 0;
133     if (startswith(Magic, "\xFE\xED\xFA\xCE") ||
134         startswith(Magic, "\xFE\xED\xFA\xCF")) {
135       /* Native endian */
136       size_t MinSize;
137       if (Magic[3] == char(0xCE))
138         MinSize = sizeof(MachO::mach_header);
139       else
140         MinSize = sizeof(MachO::mach_header_64);
141       if (Magic.size() >= MinSize)
142         type = Magic[12] << 24 | Magic[13] << 12 | Magic[14] << 8 | Magic[15];
143     } else if (startswith(Magic, "\xCE\xFA\xED\xFE") ||
144                startswith(Magic, "\xCF\xFA\xED\xFE")) {
145       /* Reverse endian */
146       size_t MinSize;
147       if (Magic[0] == char(0xCE))
148         MinSize = sizeof(MachO::mach_header);
149       else
150         MinSize = sizeof(MachO::mach_header_64);
151       if (Magic.size() >= MinSize)
152         type = Magic[15] << 24 | Magic[14] << 12 | Magic[13] << 8 | Magic[12];
153     }
154     switch (type) {
155     default:
156       break;
157     case 1:
158       return file_magic::macho_object;
159     case 2:
160       return file_magic::macho_executable;
161     case 3:
162       return file_magic::macho_fixed_virtual_memory_shared_lib;
163     case 4:
164       return file_magic::macho_core;
165     case 5:
166       return file_magic::macho_preload_executable;
167     case 6:
168       return file_magic::macho_dynamically_linked_shared_lib;
169     case 7:
170       return file_magic::macho_dynamic_linker;
171     case 8:
172       return file_magic::macho_bundle;
173     case 9:
174       return file_magic::macho_dynamically_linked_shared_lib_stub;
175     case 10:
176       return file_magic::macho_dsym_companion;
177     case 11:
178       return file_magic::macho_kext_bundle;
179     }
180     break;
181   }
182   case 0xF0: // PowerPC Windows
183   case 0x83: // Alpha 32-bit
184   case 0x84: // Alpha 64-bit
185   case 0x66: // MPS R4000 Windows
186   case 0x50: // mc68K
187   case 0x4c: // 80386 Windows
188   case 0xc4: // ARMNT Windows
189     if (Magic[1] == 0x01)
190       return file_magic::coff_object;
191     LLVM_FALLTHROUGH;
192 
193   case 0x90: // PA-RISC Windows
194   case 0x68: // mc68K Windows
195     if (Magic[1] == 0x02)
196       return file_magic::coff_object;
197     break;
198 
199   case 'M': // Possible MS-DOS stub on Windows PE file, MSF/PDB file or a
200             // Minidump file.
201     if (startswith(Magic, "MZ") && Magic.size() >= 0x3c + 4) {
202       uint32_t off = read32le(Magic.data() + 0x3c);
203       // PE/COFF file, either EXE or DLL.
204       if (Magic.substr(off).startswith(
205               StringRef(COFF::PEMagic, sizeof(COFF::PEMagic))))
206         return file_magic::pecoff_executable;
207     }
208     if (Magic.startswith("Microsoft C/C++ MSF 7.00\r\n"))
209       return file_magic::pdb;
210     if (startswith(Magic, "MDMP"))
211       return file_magic::minidump;
212     break;
213 
214   case 0x64: // x86-64 or ARM64 Windows.
215     if (Magic[1] == char(0x86) || Magic[1] == char(0xaa))
216       return file_magic::coff_object;
217     break;
218 
219   case 0x2d: // YAML '-'
220     if (startswith(Magic, "--- !tapi") || startswith(Magic, "---\narchs:"))
221       return file_magic::tapi_file;
222     break;
223 
224   default:
225     break;
226   }
227   return file_magic::unknown;
228 }
229 
230 std::error_code llvm::identify_magic(const Twine &Path, file_magic &Result) {
231   auto FileOrError = MemoryBuffer::getFile(Path, /*IsText=*/false,
232                                            /*RequiresNullTerminator=*/false);
233   if (!FileOrError)
234     return FileOrError.getError();
235 
236   std::unique_ptr<MemoryBuffer> FileBuffer = std::move(*FileOrError);
237   Result = identify_magic(FileBuffer->getBuffer());
238 
239   return std::error_code();
240 }
241