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 : base_ = reinterpret_cast<uint8*>(
46 : ::MapViewOfFile(pool->handle(),
47 : FILE_MAP_ALL_ACCESS,
48 : 0,
49 : start,
50 E : end - start));
51 :
52 E : if (base_ == NULL) {
53 i : DWORD error = ::GetLastError();
54 i : LOG(ERROR) << "Failed mapping buffer: " << ::common::LogWe(error) << ".";
55 i : return false;
56 : }
57 :
58 : // Grab the offset in the mapping that corresponds to this buffer.
59 E : data_ = base_ + buffer_->buffer_offset - start;
60 :
61 E : return true;
62 E : }
63 :
64 : // Unmaps the current buffer. Logs an error message on failure.
65 : // @returns true on success, false otherwise.
66 E : bool MappedBuffer::Unmap() {
67 E : if (data_ == NULL)
68 E : return true;
69 :
70 E : BufferPool* pool = buffer_->pool;
71 E : DCHECK(pool->handle() != INVALID_HANDLE_VALUE);
72 :
73 E : if (base_ && !::UnmapViewOfFile(base_)) {
74 i : DWORD error = ::GetLastError();
75 i : LOG(WARNING) << "Failed to unmap buffer: " << ::common::LogWe(error) << ".";
76 i : return false;
77 : }
78 E : base_ = NULL;
79 E : data_ = NULL;
80 :
81 E : return true;
82 E : }
83 :
84 : } // namespace service
85 : } // namespace trace
|