1 : // Copyright 2012 Google Inc. All Rights Reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // http://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : #include "syzygy/pdb/pdb_file_stream.h"
16 :
17 : #include <algorithm>
18 :
19 : #include "base/logging.h"
20 :
21 : namespace pdb {
22 :
23 : PdbFileStream::PdbFileStream(RefCountedFILE* file,
24 : size_t length,
25 : const uint32* pages,
26 : size_t page_size)
27 : : PdbStream(length),
28 : file_(file),
29 E : page_size_(page_size) {
30 E : size_t num_pages = (length + page_size - 1) / page_size;
31 E : pages_.assign(pages, pages + num_pages);
32 E : }
33 :
34 E : PdbFileStream::~PdbFileStream() {
35 E : }
36 :
37 E : bool PdbFileStream::ReadBytes(void* dest, size_t count, size_t* bytes_read) {
38 E : DCHECK(dest != NULL);
39 E : DCHECK(bytes_read != NULL);
40 :
41 : // Return 0 once we've reached the end of the stream.
42 E : if (pos() == length()) {
43 i : *bytes_read = 0;
44 i : return true;
45 : }
46 :
47 : // Don't read beyond the end of the known stream length.
48 E : count = std::min(count, length() - pos());
49 E : *bytes_read = count;
50 :
51 : // Read the stream.
52 E : while (count > 0) {
53 E : size_t page_index = pos() / page_size_;
54 E : size_t offset = pos() % page_size_;
55 E : size_t chunk_size = std::min(count, page_size_ - (pos() % page_size_));
56 E : if (!ReadFromPage(dest, pages_[page_index], offset, chunk_size))
57 i : return false;
58 :
59 E : count -= chunk_size;
60 E : Seek(pos() + chunk_size);
61 E : dest = reinterpret_cast<uint8*>(dest) + chunk_size;
62 E : }
63 :
64 E : return true;
65 E : }
66 :
67 : bool PdbFileStream::ReadFromPage(void* dest, uint32 page_num, size_t offset,
68 E : size_t count) {
69 E : DCHECK(dest != NULL);
70 E : DCHECK(offset + count <= page_size_);
71 :
72 E : size_t page_offset = page_size_ * page_num;
73 E : if (fseek(file_->file(), page_offset + offset, SEEK_SET) != 0) {
74 i : LOG(ERROR) << "Page seek failed";
75 i : return false;
76 : }
77 :
78 E : if (fread(dest, 1, count, file_->file()) != static_cast<size_t>(count)) {
79 i : LOG(ERROR) << "Page read failed";
80 i : return false;
81 : }
82 :
83 E : return true;
84 E : }
85 :
86 : } // namespace pdb
|