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<File>(fd, File::eOpenOptionWrite, transfer_ownership);
29 }
30 
31 StreamFile::StreamFile(FILE *fh, bool transfer_ownership) : Stream() {
32   m_file_sp = std::make_shared<File>(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, uint32_t options, uint32_t permissions)
50     : Stream() {
51   auto file = FileSystem::Instance().Open(FileSpec(path), options, permissions);
52   if (file)
53     m_file_sp = std::move(file.get());
54   else {
55     // TODO refactor this so the error gets popagated up instead of logged here.
56     LLDB_LOG_ERROR(GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), file.takeError(),
57                    "Cannot open {1}: {0}", path);
58     m_file_sp = std::make_shared<File>();
59   }
60 }
61 
62 StreamFile::~StreamFile() {}
63 
64 void StreamFile::Flush() { m_file_sp->Flush(); }
65 
66 size_t StreamFile::WriteImpl(const void *s, size_t length) {
67   m_file_sp->Write(s, length);
68   return length;
69 }
70