LIEF: Library to Instrument Executable Formats Version 0.15.0
Loading...
Searching...
No Matches
FileStream.hpp
1/* Copyright 2017 - 2024 R. Thomas
2 * Copyright 2017 - 2024 Quarkslab
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef LIEF_FILE_STREAM_H
17#define LIEF_FILE_STREAM_H
18
19#include <vector>
20#include <string>
21#include <fstream>
22
23#include "LIEF/errors.hpp"
24#include "LIEF/BinaryStream/BinaryStream.hpp"
25namespace LIEF {
26
28class FileStream : public BinaryStream {
29 public:
30 static result<FileStream> from_file(const std::string& file);
31 FileStream(std::ifstream fs, uint64_t size) :
32 BinaryStream(STREAM_TYPE::FILE),
33 ifs_(std::move(fs)),
34 size_(size)
35 {}
36
37 FileStream() = delete;
38
39 // VectorStream should not be copyable for performances reasons
40 FileStream(const FileStream&) = delete;
41 FileStream& operator=(const FileStream&) = delete;
42
43 FileStream(FileStream&& other) noexcept = default;
44 FileStream& operator=(FileStream&& other) noexcept = default;
45
46 uint64_t size() const override {
47 return size_;
48 }
49
50 std::vector<uint8_t> content() const;
51 ~FileStream() override = default;
52
53 static bool classof(const BinaryStream& stream) {
54 return stream.type() == STREAM_TYPE::FILE;
55 }
56
57 protected:
58 ok_error_t peek_in(void* dst, uint64_t offset, uint64_t size) const override {
59 if (offset > size_ || offset + size > size_) {
60 return make_error_code(lief_errors::read_error);
61 }
62 const auto pos = ifs_.tellg();
63 ifs_.seekg(offset);
64 ifs_.read(static_cast<char*>(dst), size);
65 ifs_.seekg(pos);
66 return ok();
67 }
68 result<const void*> read_at(uint64_t, uint64_t) const override {
69 return make_error_code(lief_errors::not_supported);
70 }
71 mutable std::ifstream ifs_;
72 uint64_t size_ = 0;
73};
74}
75
76#endif
Class that is used to a read stream of data from different sources.
Definition BinaryStream.hpp:34
Stream interface over a std::ifstream.
Definition FileStream.hpp:28
LIEF namespace.
Definition Abstract/Binary.hpp:32
result< ok_t > ok_error_t
Opaque structure that is used by LIEF to avoid writing result<void> f(...). Instead,...
Definition errors.hpp:106
ok_t ok()
Return success for function with return type ok_error_t.
Definition errors.hpp:90
tl::expected< T, lief_errors > result
Wrapper that contains an Object (T) or an error.
Definition errors.hpp:72