1 //===-- Reproducer.h --------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLDB_UTILITY_REPRODUCER_H
10 #define LLDB_UTILITY_REPRODUCER_H
12 #include "lldb/Utility/FileSpec.h"
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/Support/Error.h"
15 #include "llvm/Support/FileCollector.h"
16 #include "llvm/Support/YAMLTraits.h"
22 namespace lldb_private {
27 enum class ReproducerMode {
33 /// The provider defines an interface for generating files needed for
36 /// Different components will implement different providers.
39 virtual ~ProviderBase() = default;
41 const FileSpec &GetRoot() const { return m_root; }
43 /// The Keep method is called when it is decided that we need to keep the
44 /// data in order to provide a reproducer.
45 virtual void Keep(){};
47 /// The Discard method is called when it is decided that we do not need to
48 /// keep any information and will not generate a reproducer.
49 virtual void Discard(){};
51 // Returns the class ID for this type.
52 static const void *ClassID() { return &ID; }
54 // Returns the class ID for the dynamic type of this Provider instance.
55 virtual const void *DynamicClassID() const = 0;
57 virtual llvm::StringRef GetName() const = 0;
58 virtual llvm::StringRef GetFile() const = 0;
61 ProviderBase(const FileSpec &root) : m_root(root) {}
64 /// Every provider knows where to dump its potential files.
67 virtual void anchor();
71 template <typename ThisProviderT> class Provider : public ProviderBase {
73 static const void *ClassID() { return &ThisProviderT::ID; }
75 const void *DynamicClassID() const override { return &ThisProviderT::ID; }
77 llvm::StringRef GetName() const override { return ThisProviderT::Info::name; }
78 llvm::StringRef GetFile() const override { return ThisProviderT::Info::file; }
81 using ProviderBase::ProviderBase; // Inherit constructor.
84 class FileProvider : public Provider<FileProvider> {
87 static const char *name;
88 static const char *file;
91 FileProvider(const FileSpec &directory)
92 : Provider(directory),
93 m_collector(std::make_shared<llvm::FileCollector>(
94 directory.CopyByAppendingPathComponent("root").GetPath(),
95 directory.GetPath())) {}
97 std::shared_ptr<llvm::FileCollector> GetFileCollector() {
101 void Keep() override {
102 auto mapping = GetRoot().CopyByAppendingPathComponent(Info::file);
103 // Temporary files that are removed during execution can cause copy errors.
104 if (auto ec = m_collector->copyFiles(/*stop_on_error=*/false))
106 m_collector->writeMapping(mapping.GetPath());
112 std::shared_ptr<llvm::FileCollector> m_collector;
115 /// Provider for the LLDB version number.
117 /// When the reproducer is kept, it writes the lldb version to a file named
118 /// version.txt in the reproducer root.
119 class VersionProvider : public Provider<VersionProvider> {
121 VersionProvider(const FileSpec &directory) : Provider(directory) {}
123 static const char *name;
124 static const char *file;
126 void SetVersion(std::string version) {
127 assert(m_version.empty());
128 m_version = std::move(version);
130 void Keep() override;
131 std::string m_version;
135 /// Provider for the LLDB current working directroy.
137 /// When the reproducer is kept, it writes lldb's current working directory to
138 /// a file named cwd.txt in the reproducer root.
139 class WorkingDirectoryProvider : public Provider<WorkingDirectoryProvider> {
141 WorkingDirectoryProvider(const FileSpec &directory) : Provider(directory) {
142 llvm::SmallString<128> cwd;
143 if (std::error_code EC = llvm::sys::fs::current_path(cwd))
148 static const char *name;
149 static const char *file;
151 void Keep() override;
158 DataRecorder(const FileSpec &filename, std::error_code &ec)
159 : m_filename(filename.GetFilename().GetStringRef()),
160 m_os(filename.GetPath(), ec, llvm::sys::fs::OF_Text), m_record(true) {}
162 static llvm::Expected<std::unique_ptr<DataRecorder>>
163 Create(const FileSpec &filename);
165 template <typename T> void Record(const T &t, bool newline = false) {
174 const FileSpec &GetFilename() { return m_filename; }
183 llvm::raw_fd_ostream m_os;
187 class CommandProvider : public Provider<CommandProvider> {
190 static const char *name;
191 static const char *file;
194 CommandProvider(const FileSpec &directory) : Provider(directory) {}
196 DataRecorder *GetNewDataRecorder();
198 void Keep() override;
199 void Discard() override;
204 std::vector<std::unique_ptr<DataRecorder>> m_data_recorders;
207 class ProcessGDBRemoteProvider
208 : public repro::Provider<ProcessGDBRemoteProvider> {
211 static const char *name;
212 static const char *file;
215 ProcessGDBRemoteProvider(const FileSpec &directory) : Provider(directory) {}
217 llvm::raw_ostream *GetHistoryStream();
219 void SetCallback(std::function<void()> callback) {
220 m_callback = std::move(callback);
223 void Keep() override { m_callback(); }
224 void Discard() override { m_callback(); }
229 std::function<void()> m_callback;
230 std::unique_ptr<llvm::raw_fd_ostream> m_stream_up;
233 /// The generator is responsible for the logic needed to generate a
234 /// reproducer. For doing so it relies on providers, who serialize data that
235 /// is necessary for reproducing a failure.
236 class Generator final {
239 Generator(FileSpec root);
242 /// Method to indicate we want to keep the reproducer. If reproducer
243 /// generation is disabled, this does nothing.
246 /// Method to indicate we do not want to keep the reproducer. This is
247 /// unaffected by whether or not generation reproduction is enabled, as we
248 /// might need to clean up files already written to disk.
251 /// Create and register a new provider.
252 template <typename T> T *Create() {
253 std::unique_ptr<ProviderBase> provider = std::make_unique<T>(m_root);
254 return static_cast<T *>(Register(std::move(provider)));
257 /// Get an existing provider.
258 template <typename T> T *Get() {
259 auto it = m_providers.find(T::ClassID());
260 if (it == m_providers.end())
262 return static_cast<T *>(it->second.get());
265 /// Get a provider if it exists, otherwise create it.
266 template <typename T> T &GetOrCreate() {
267 auto *provider = Get<T>();
273 const FileSpec &GetRoot() const;
278 ProviderBase *Register(std::unique_ptr<ProviderBase> provider);
280 /// Builds and index with provider info.
281 void AddProvidersToIndex();
283 /// Map of provider IDs to provider instances.
284 llvm::DenseMap<const void *, std::unique_ptr<ProviderBase>> m_providers;
285 std::mutex m_providers_mutex;
287 /// The reproducer root directory.
290 /// Flag to ensure that we never call both keep and discard.
296 Loader(FileSpec root);
298 template <typename T> FileSpec GetFile() {
299 if (!HasFile(T::file))
302 return GetRoot().CopyByAppendingPathComponent(T::file);
305 template <typename T> llvm::Expected<std::string> LoadBuffer() {
306 FileSpec file = GetFile<typename T::Info>();
307 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
308 llvm::vfs::getRealFileSystem()->getBufferForFile(file.GetPath());
310 return llvm::errorCodeToError(buffer.getError());
311 return (*buffer)->getBuffer().str();
314 llvm::Error LoadIndex();
316 const FileSpec &GetRoot() const { return m_root; }
319 bool HasFile(llvm::StringRef file);
322 std::vector<std::string> m_files;
326 /// The reproducer enables clients to obtain access to the Generator and
330 static Reproducer &Instance();
331 static llvm::Error Initialize(ReproducerMode mode,
332 llvm::Optional<FileSpec> root);
333 static bool Initialized();
334 static void Terminate();
336 Reproducer() = default;
338 Generator *GetGenerator();
341 const Generator *GetGenerator() const;
342 const Loader *GetLoader() const;
344 FileSpec GetReproducerPath() const;
346 bool IsCapturing() { return static_cast<bool>(m_generator); };
347 bool IsReplaying() { return static_cast<bool>(m_loader); };
350 llvm::Error SetCapture(llvm::Optional<FileSpec> root);
351 llvm::Error SetReplay(llvm::Optional<FileSpec> root);
354 static llvm::Optional<Reproducer> &InstanceImpl();
356 llvm::Optional<Generator> m_generator;
357 llvm::Optional<Loader> m_loader;
359 mutable std::mutex m_mutex;
362 /// Helper class for replaying commands through the reproducer.
363 class CommandLoader {
365 CommandLoader(std::vector<std::string> files) : m_files(files) {}
367 static std::unique_ptr<CommandLoader> Create(Loader *loader);
368 llvm::Optional<std::string> GetNextFile();
371 std::vector<std::string> m_files;
372 unsigned m_index = 0;
376 } // namespace lldb_private
378 #endif // LLDB_UTILITY_REPRODUCER_H