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 "base/logging.h"
18 :
19 : namespace pdb {
20 :
21 : PdbFileStream::PdbFileStream(RefCountedFILE* file,
22 : size_t length,
23 : const uint32* pages,
24 : size_t page_size)
25 : : PdbStream(length),
26 : file_(file),
27 E : page_size_(page_size) {
28 E : size_t num_pages = (length + page_size - 1) / page_size;
29 E : pages_.assign(pages, pages + num_pages);
30 E : }
31 :
32 E : PdbFileStream::~PdbFileStream() {
33 E : }
34 :
35 E : bool PdbFileStream::ReadBytes(void* dest, size_t count, size_t* bytes_read) {
36 E : DCHECK(dest != NULL);
37 E : DCHECK(bytes_read != NULL);
38 :
39 : // Return 0 once we've reached the end of the stream.
40 E : if (pos() == length()) {
41 i : *bytes_read = 0;
42 i : return true;
43 : }
44 :
45 : // Don't read beyond the end of the known stream length.
46 E : count = std::min(count, length() - pos());
47 E : *bytes_read = count;
48 :
49 : // Read the stream.
50 E : while (count > 0) {
51 E : size_t page_index = pos() / page_size_;
52 E : size_t offset = pos() % page_size_;
53 E : size_t chunk_size = std::min(count, page_size_ - (pos() % page_size_));
54 E : if (!ReadFromPage(dest, pages_[page_index], offset, chunk_size))
55 i : return false;
56 :
57 E : count -= chunk_size;
58 E : Seek(pos() + chunk_size);
59 E : dest = reinterpret_cast<uint8*>(dest) + chunk_size;
60 E : }
61 :
62 E : return true;
63 E : }
64 :
65 : bool PdbFileStream::ReadFromPage(void* dest, uint32 page_num, size_t offset,
66 E : size_t count) {
67 E : DCHECK(dest != NULL);
68 E : DCHECK(offset + count <= page_size_);
69 :
70 E : size_t page_offset = page_size_ * page_num;
71 E : if (fseek(file_->file(), page_offset + offset, SEEK_SET) != 0) {
72 i : LOG(ERROR) << "Page seek failed";
73 i : return false;
74 : }
75 :
76 E : if (fread(dest, 1, count, file_->file()) != static_cast<size_t>(count)) {
77 i : LOG(ERROR) << "Page read failed";
78 i : return false;
79 : }
80 :
81 E : return true;
82 E : }
83 :
84 : } // namespace pdb
|