1 //===- DebugTypes.cpp -----------------------------------------------------===//
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 "DebugTypes.h"
10 #include "Driver.h"
11 #include "InputFiles.h"
12 #include "lld/Common/ErrorHandler.h"
13 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
14 #include "llvm/DebugInfo/PDB/GenericError.h"
15 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
16 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
17 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
18 #include "llvm/Support/Path.h"
19 
20 using namespace llvm;
21 using namespace llvm::codeview;
22 
23 namespace lld {
24 namespace coff {
25 
26 namespace {
27 // The TypeServerSource class represents a PDB type server, a file referenced by
28 // OBJ files compiled with MSVC /Zi. A single PDB can be shared by several OBJ
29 // files, therefore there must be only once instance per OBJ lot. The file path
30 // is discovered from the dependent OBJ's debug type stream. The
31 // TypeServerSource object is then queued and loaded by the COFF Driver. The
32 // debug type stream for such PDB files will be merged first in the final PDB,
33 // before any dependent OBJ.
34 class TypeServerSource : public TpiSource {
35 public:
36   explicit TypeServerSource(MemoryBufferRef m, llvm::pdb::NativeSession *s)
37       : TpiSource(PDB, nullptr), session(s), mb(m) {}
38 
39   // Queue a PDB type server for loading in the COFF Driver
40   static void enqueue(const ObjFile *dependentFile,
41                       const TypeServer2Record &ts);
42 
43   // Create an instance
44   static Expected<TypeServerSource *> getInstance(MemoryBufferRef m);
45 
46   // Fetch the PDB instance loaded for a corresponding dependent OBJ.
47   static Expected<TypeServerSource *>
48   findFromFile(const ObjFile *dependentFile);
49 
50   static std::map<std::string, std::pair<std::string, TypeServerSource *>>
51       instances;
52 
53   // The interface to the PDB (if it was opened successfully)
54   std::unique_ptr<llvm::pdb::NativeSession> session;
55 
56 private:
57   MemoryBufferRef mb;
58 };
59 
60 // This class represents the debug type stream of an OBJ file that depends on a
61 // PDB type server (see TypeServerSource).
62 class UseTypeServerSource : public TpiSource {
63 public:
64   UseTypeServerSource(const ObjFile *f, const TypeServer2Record *ts)
65       : TpiSource(UsingPDB, f), typeServerDependency(*ts) {}
66 
67   // Information about the PDB type server dependency, that needs to be loaded
68   // in before merging this OBJ.
69   TypeServer2Record typeServerDependency;
70 };
71 
72 // This class represents the debug type stream of a Microsoft precompiled
73 // headers OBJ (PCH OBJ). This OBJ kind needs to be merged first in the output
74 // PDB, before any other OBJs that depend on this. Note that only MSVC generate
75 // such files, clang does not.
76 class PrecompSource : public TpiSource {
77 public:
78   PrecompSource(const ObjFile *f) : TpiSource(PCH, f) {}
79 };
80 
81 // This class represents the debug type stream of an OBJ file that depends on a
82 // Microsoft precompiled headers OBJ (see PrecompSource).
83 class UsePrecompSource : public TpiSource {
84 public:
85   UsePrecompSource(const ObjFile *f, const PrecompRecord *precomp)
86       : TpiSource(UsingPCH, f), precompDependency(*precomp) {}
87 
88   // Information about the Precomp OBJ dependency, that needs to be loaded in
89   // before merging this OBJ.
90   PrecompRecord precompDependency;
91 };
92 } // namespace
93 
94 static std::vector<std::unique_ptr<TpiSource>> GC;
95 
96 TpiSource::TpiSource(TpiKind k, const ObjFile *f) : kind(k), file(f) {
97   GC.push_back(std::unique_ptr<TpiSource>(this));
98 }
99 
100 TpiSource *makeTpiSource(const ObjFile *f) {
101   return new TpiSource(TpiSource::Regular, f);
102 }
103 
104 TpiSource *makeUseTypeServerSource(const ObjFile *f,
105                                               const TypeServer2Record *ts) {
106   TypeServerSource::enqueue(f, *ts);
107   return new UseTypeServerSource(f, ts);
108 }
109 
110 TpiSource *makePrecompSource(const ObjFile *f) {
111   return new PrecompSource(f);
112 }
113 
114 TpiSource *makeUsePrecompSource(const ObjFile *f,
115                                            const PrecompRecord *precomp) {
116   return new UsePrecompSource(f, precomp);
117 }
118 
119 template <>
120 const PrecompRecord &retrieveDependencyInfo(const TpiSource *source) {
121   assert(source->kind == TpiSource::UsingPCH);
122   return ((const UsePrecompSource *)source)->precompDependency;
123 }
124 
125 template <>
126 const TypeServer2Record &retrieveDependencyInfo(const TpiSource *source) {
127   assert(source->kind == TpiSource::UsingPDB);
128   return ((const UseTypeServerSource *)source)->typeServerDependency;
129 }
130 
131 std::map<std::string, std::pair<std::string, TypeServerSource *>>
132     TypeServerSource::instances;
133 
134 // Make a PDB path assuming the PDB is in the same folder as the OBJ
135 static std::string getPdbBaseName(const ObjFile *file, StringRef tSPath) {
136   StringRef localPath =
137       !file->parentName.empty() ? file->parentName : file->getName();
138   SmallString<128> path = sys::path::parent_path(localPath);
139 
140   // Currently, type server PDBs are only created by MSVC cl, which only runs
141   // on Windows, so we can assume type server paths are Windows style.
142   sys::path::append(path, sys::path::filename(tSPath, sys::path::Style::windows));
143   return path.str();
144 }
145 
146 // The casing of the PDB path stamped in the OBJ can differ from the actual path
147 // on disk. With this, we ensure to always use lowercase as a key for the
148 // PDBInputFile::Instances map, at least on Windows.
149 static std::string normalizePdbPath(StringRef path) {
150 #if defined(_WIN32)
151   return path.lower();
152 #else // LINUX
153   return path;
154 #endif
155 }
156 
157 // If existing, return the actual PDB path on disk.
158 static Optional<std::string> findPdbPath(StringRef pdbPath,
159                                          const ObjFile *dependentFile) {
160   // Ensure the file exists before anything else. In some cases, if the path
161   // points to a removable device, Driver::enqueuePath() would fail with an
162   // error (EAGAIN, "resource unavailable try again") which we want to skip
163   // silently.
164   if (llvm::sys::fs::exists(pdbPath))
165     return normalizePdbPath(pdbPath);
166   std::string ret = getPdbBaseName(dependentFile, pdbPath);
167   if (llvm::sys::fs::exists(ret))
168     return normalizePdbPath(ret);
169   return None;
170 }
171 
172 // Fetch the PDB instance that was already loaded by the COFF Driver.
173 Expected<TypeServerSource *>
174 TypeServerSource::findFromFile(const ObjFile *dependentFile) {
175   const TypeServer2Record &ts =
176       retrieveDependencyInfo<TypeServer2Record>(dependentFile->debugTypesObj);
177 
178   Optional<std::string> p = findPdbPath(ts.Name, dependentFile);
179   if (!p)
180     return createFileError(ts.Name, errorCodeToError(std::error_code(
181                                         ENOENT, std::generic_category())));
182 
183   auto it = TypeServerSource::instances.find(*p);
184   // The PDB file exists on disk, at this point we expect it to have been
185   // inserted in the map by TypeServerSource::loadPDB()
186   assert(it != TypeServerSource::instances.end());
187 
188   std::pair<std::string, TypeServerSource *> &pdb = it->second;
189 
190   if (!pdb.second)
191     return createFileError(
192         *p, createStringError(inconvertibleErrorCode(), pdb.first.c_str()));
193 
194   pdb::PDBFile &pdbFile = (pdb.second)->session->getPDBFile();
195   pdb::InfoStream &info = cantFail(pdbFile.getPDBInfoStream());
196 
197   // Just because a file with a matching name was found doesn't mean it can be
198   // used. The GUID must match between the PDB header and the OBJ
199   // TypeServer2 record. The 'Age' is used by MSVC incremental compilation.
200   if (info.getGuid() != ts.getGuid())
201     return createFileError(
202         ts.Name,
203         make_error<pdb::PDBError>(pdb::pdb_error_code::signature_out_of_date));
204 
205   return pdb.second;
206 }
207 
208 // FIXME: Temporary interface until PDBLinker::maybeMergeTypeServerPDB() is
209 // moved here.
210 Expected<llvm::pdb::NativeSession *> findTypeServerSource(const ObjFile *f) {
211   Expected<TypeServerSource *> ts = TypeServerSource::findFromFile(f);
212   if (!ts)
213     return ts.takeError();
214   return ts.get()->session.get();
215 }
216 
217 // Queue a PDB type server for loading in the COFF Driver
218 void TypeServerSource::enqueue(const ObjFile *dependentFile,
219                                const TypeServer2Record &ts) {
220   // Start by finding where the PDB is located (either the record path or next
221   // to the OBJ file)
222   Optional<std::string> p = findPdbPath(ts.Name, dependentFile);
223   if (!p)
224     return;
225   auto it = TypeServerSource::instances.emplace(
226       *p, std::pair<std::string, TypeServerSource *>{});
227   if (!it.second)
228     return; // another OBJ already scheduled this PDB for load
229 
230   driver->enqueuePath(*p, false, false);
231 }
232 
233 // Create an instance of TypeServerSource or an error string if the PDB couldn't
234 // be loaded. The error message will be displayed later, when the referring OBJ
235 // will be merged in. NOTE - a PDB load failure is not a link error: some
236 // debug info will simply be missing from the final PDB - that is the default
237 // accepted behavior.
238 void loadTypeServerSource(llvm::MemoryBufferRef m) {
239   std::string path = normalizePdbPath(m.getBufferIdentifier());
240 
241   Expected<TypeServerSource *> ts = TypeServerSource::getInstance(m);
242   if (!ts)
243     TypeServerSource::instances[path] = {toString(ts.takeError()), nullptr};
244   else
245     TypeServerSource::instances[path] = {{}, *ts};
246 }
247 
248 Expected<TypeServerSource *> TypeServerSource::getInstance(MemoryBufferRef m) {
249   std::unique_ptr<llvm::pdb::IPDBSession> iSession;
250   Error err = pdb::NativeSession::createFromPdb(
251       MemoryBuffer::getMemBuffer(m, false), iSession);
252   if (err)
253     return std::move(err);
254 
255   std::unique_ptr<llvm::pdb::NativeSession> session(
256       static_cast<pdb::NativeSession *>(iSession.release()));
257 
258   pdb::PDBFile &pdbFile = session->getPDBFile();
259   Expected<pdb::InfoStream &> info = pdbFile.getPDBInfoStream();
260   // All PDB Files should have an Info stream.
261   if (!info)
262     return info.takeError();
263   return new TypeServerSource(m, session.release());
264 }
265 
266 } // namespace coff
267 } // namespace lld
268