1 //===-- FileCache.cpp -----------------------------------------------------===//
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 #include "lldb/Host/FileCache.h"
11 #include "lldb/Host/File.h"
12 #include "lldb/Host/FileSystem.h"
15 using namespace lldb_private
;
17 FileCache
*FileCache::m_instance
= nullptr;
19 FileCache
&FileCache::GetInstance() {
20 if (m_instance
== nullptr)
21 m_instance
= new FileCache();
26 lldb::user_id_t
FileCache::OpenFile(const FileSpec
&file_spec
,
27 File::OpenOptions flags
, uint32_t mode
,
30 error
.SetErrorString("empty path");
33 auto file
= FileSystem::Instance().Open(file_spec
, flags
, mode
);
35 error
= file
.takeError();
38 lldb::user_id_t fd
= file
.get()->GetDescriptor();
39 m_cache
[fd
] = std::move(file
.get());
43 bool FileCache::CloseFile(lldb::user_id_t fd
, Status
&error
) {
44 if (fd
== UINT64_MAX
) {
45 error
.SetErrorString("invalid file descriptor");
48 FDToFileMap::iterator pos
= m_cache
.find(fd
);
49 if (pos
== m_cache
.end()) {
50 error
.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64
, fd
);
53 FileUP
&file_up
= pos
->second
;
55 error
.SetErrorString("invalid host backing file");
58 error
= file_up
->Close();
60 return error
.Success();
63 uint64_t FileCache::WriteFile(lldb::user_id_t fd
, uint64_t offset
,
64 const void *src
, uint64_t src_len
,
66 if (fd
== UINT64_MAX
) {
67 error
.SetErrorString("invalid file descriptor");
70 FDToFileMap::iterator pos
= m_cache
.find(fd
);
71 if (pos
== m_cache
.end()) {
72 error
.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64
, fd
);
75 FileUP
&file_up
= pos
->second
;
77 error
.SetErrorString("invalid host backing file");
80 if (static_cast<uint64_t>(file_up
->SeekFromStart(offset
, &error
)) != offset
||
83 size_t bytes_written
= src_len
;
84 error
= file_up
->Write(src
, bytes_written
);
90 uint64_t FileCache::ReadFile(lldb::user_id_t fd
, uint64_t offset
, void *dst
,
91 uint64_t dst_len
, Status
&error
) {
92 if (fd
== UINT64_MAX
) {
93 error
.SetErrorString("invalid file descriptor");
96 FDToFileMap::iterator pos
= m_cache
.find(fd
);
97 if (pos
== m_cache
.end()) {
98 error
.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64
, fd
);
101 FileUP
&file_up
= pos
->second
;
103 error
.SetErrorString("invalid host backing file");
106 if (static_cast<uint64_t>(file_up
->SeekFromStart(offset
, &error
)) != offset
||
109 size_t bytes_read
= dst_len
;
110 error
= file_up
->Read(dst
, bytes_read
);