1 //===-- StreamFile.cpp ------------------------------------------*- 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 "lldb/Core/StreamFile.h"
10 #include "lldb/Host/FileSystem.h"
11 #include "lldb/Utility/Log.h"
12 
13 #include <stdio.h>
14 
15 using namespace lldb;
16 using namespace lldb_private;
17 
18 // StreamFile constructor
19 StreamFile::StreamFile() : Stream() { m_file_sp = std::make_shared<File>(); }
20 
21 StreamFile::StreamFile(uint32_t flags, uint32_t addr_size, ByteOrder byte_order)
22     : Stream(flags, addr_size, byte_order) {
23   m_file_sp = std::make_shared<File>();
24 }
25 
26 StreamFile::StreamFile(int fd, bool transfer_ownership) : Stream() {
27   m_file_sp =
28       std::make_shared<NativeFile>(fd, File::eOpenOptionWrite, transfer_ownership);
29 }
30 
31 StreamFile::StreamFile(FILE *fh, bool transfer_ownership) : Stream() {
32   m_file_sp = std::make_shared<NativeFile>(fh, transfer_ownership);
33 }
34 
35 StreamFile::StreamFile(const char *path) : Stream() {
36   auto file = FileSystem::Instance().Open(
37       FileSpec(path), File::eOpenOptionWrite | File::eOpenOptionCanCreate |
38                           File::eOpenOptionCloseOnExec);
39   if (file)
40     m_file_sp = std::move(file.get());
41   else {
42     // TODO refactor this so the error gets popagated up instead of logged here.
43     LLDB_LOG_ERROR(GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), file.takeError(),
44                    "Cannot open {1}: {0}", path);
45     m_file_sp = std::make_shared<File>();
46   }
47 }
48 
49 StreamFile::StreamFile(const char *path, File::OpenOptions options,
50                        uint32_t permissions)
51     : Stream() {
52   auto file = FileSystem::Instance().Open(FileSpec(path), options, permissions);
53   if (file)
54     m_file_sp = std::move(file.get());
55   else {
56     // TODO refactor this so the error gets popagated up instead of logged here.
57     LLDB_LOG_ERROR(GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), file.takeError(),
58                    "Cannot open {1}: {0}", path);
59     m_file_sp = std::make_shared<File>();
60   }
61 }
62 
63 StreamFile::~StreamFile() {}
64 
65 void StreamFile::Flush() { m_file_sp->Flush(); }
66 
67 size_t StreamFile::WriteImpl(const void *s, size_t length) {
68   m_file_sp->Write(s, length);
69   return length;
70 }
71