1 : // Copyright 2013 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/trace/service/mapped_buffer.h"
16 :
17 : #include "syzygy/common/align.h"
18 : #include "syzygy/common/com_utils.h"
19 : #include "syzygy/trace/service/buffer_pool.h"
20 :
21 : namespace trace {
22 : namespace service {
23 :
24 : // Maps the current buffer. Logs an error message on failure.
25 : // @returns true on success, false otherwise.
26 E : bool MappedBuffer::Map() {
27 E : if (data_ != NULL)
28 E : return true;
29 :
30 E : BufferPool* pool = buffer_->pool;
31 :
32 E : SYSTEM_INFO sys_info = {};
33 E : ::GetSystemInfo(&sys_info);
34 :
35 E : DWORD start = buffer_->buffer_offset;
36 E : DWORD end = buffer_->buffer_offset + buffer_->buffer_size;
37 :
38 : // Mapped views of a file have be in chunks that respect the allocation
39 : // granularity. We choose a view of the file that respects the granularity
40 : // but also spans the area of interest.
41 E : start = common::AlignDown(start, sys_info.dwAllocationGranularity);
42 :
43 : // Map a view of the shared memory file into this process. We only bring in
44 : // the portion of the mapping that corresponds to this buffer.
45 E : base_ = reinterpret_cast<uint8_t*>(::MapViewOfFile(
46 : pool->handle(), FILE_MAP_ALL_ACCESS, 0, start, end - start));
47 :
48 E : if (base_ == NULL) {
49 i : DWORD error = ::GetLastError();
50 i : LOG(ERROR) << "Failed mapping buffer: " << ::common::LogWe(error) << ".";
51 i : return false;
52 : }
53 :
54 : // Grab the offset in the mapping that corresponds to this buffer.
55 E : data_ = base_ + buffer_->buffer_offset - start;
56 :
57 E : return true;
58 E : }
59 :
60 : // Unmaps the current buffer. Logs an error message on failure.
61 : // @returns true on success, false otherwise.
62 E : bool MappedBuffer::Unmap() {
63 E : if (data_ == NULL)
64 E : return true;
65 :
66 E : BufferPool* pool = buffer_->pool;
67 E : DCHECK(pool->handle() != INVALID_HANDLE_VALUE);
68 :
69 E : if (base_ && !::UnmapViewOfFile(base_)) {
70 i : DWORD error = ::GetLastError();
71 i : LOG(WARNING) << "Failed to unmap buffer: " << ::common::LogWe(error) << ".";
72 i : return false;
73 : }
74 E : base_ = NULL;
75 E : data_ = NULL;
76 :
77 E : return true;
78 E : }
79 :
80 : } // namespace service
81 : } // namespace trace
|