1 
2 /*
3  * Copyright (C) 2020 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #include "src/profiling/symbolizer/scoped_read_mmap.h"
19 
20 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
21 
22 #include <Windows.h>
23 
24 namespace perfetto {
25 namespace profiling {
26 
ScopedReadMmap(const char * fName,size_t length)27 ScopedReadMmap::ScopedReadMmap(const char* fName, size_t length)
28     : length_(length), ptr_(nullptr) {
29   file_ = CreateFileA(fName, GENERIC_READ, FILE_SHARE_READ, nullptr,
30                       OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
31   if (file_ == INVALID_HANDLE_VALUE) {
32     PERFETTO_DLOG("Failed to open file: %s", fName);
33     return;
34   }
35   map_ = CreateFileMapping(file_, nullptr, PAGE_READONLY, 0, 0, nullptr);
36   if (map_ == INVALID_HANDLE_VALUE) {
37     PERFETTO_DLOG("Failed to mmap file");
38     return;
39   }
40   ptr_ = MapViewOfFile(map_, FILE_MAP_READ, 0, 0, length_);
41   if (ptr_ == nullptr) {
42     PERFETTO_DLOG("Failed to map view of file");
43   }
44 }
45 
~ScopedReadMmap()46 ScopedReadMmap::~ScopedReadMmap() {
47   if (ptr_ != nullptr) {
48     UnmapViewOfFile(ptr_);
49   }
50   if (map_ != nullptr && map_ != INVALID_HANDLE_VALUE) {
51     CloseHandle(map_);
52   }
53   if (file_ != nullptr && file_ != INVALID_HANDLE_VALUE) {
54     CloseHandle(file_);
55   }
56 }
57 
IsValid()58 bool ScopedReadMmap::IsValid() {
59   return ptr_ != nullptr;
60 }
61 
62 }  // namespace profiling
63 }  // namespace perfetto
64 
65 #endif  // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
66