1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef _LIBUNWINDSTACK_TESTS_MEMORY_FAKE_H
18 #define _LIBUNWINDSTACK_TESTS_MEMORY_FAKE_H
19 
20 #include <stdint.h>
21 
22 #include <string>
23 #include <vector>
24 #include <unordered_map>
25 
26 #include <unwindstack/Memory.h>
27 
28 namespace unwindstack {
29 
30 class MemoryFake : public Memory {
31  public:
32   MemoryFake() = default;
33   virtual ~MemoryFake() = default;
34 
35   size_t Read(uint64_t addr, void* buffer, size_t size) override;
36 
37   void SetMemory(uint64_t addr, const void* memory, size_t length);
38 
39   void SetMemoryBlock(uint64_t addr, size_t length, uint8_t value);
40 
SetData8(uint64_t addr,uint8_t value)41   void SetData8(uint64_t addr, uint8_t value) {
42     SetMemory(addr, &value, sizeof(value));
43   }
44 
SetData16(uint64_t addr,uint16_t value)45   void SetData16(uint64_t addr, uint16_t value) {
46     SetMemory(addr, &value, sizeof(value));
47   }
48 
SetData32(uint64_t addr,uint32_t value)49   void SetData32(uint64_t addr, uint32_t value) {
50     SetMemory(addr, &value, sizeof(value));
51   }
52 
SetData64(uint64_t addr,uint64_t value)53   void SetData64(uint64_t addr, uint64_t value) {
54     SetMemory(addr, &value, sizeof(value));
55   }
56 
SetMemory(uint64_t addr,std::vector<uint8_t> values)57   void SetMemory(uint64_t addr, std::vector<uint8_t> values) {
58     SetMemory(addr, values.data(), values.size());
59   }
60 
SetMemory(uint64_t addr,std::string string)61   void SetMemory(uint64_t addr, std::string string) {
62     SetMemory(addr, string.c_str(), string.size() + 1);
63   }
64 
Clear()65   void Clear() { data_.clear(); }
66 
67  private:
68   std::unordered_map<uint64_t, uint8_t> data_;
69 };
70 
71 class MemoryFakeAlwaysReadZero : public Memory {
72  public:
73   MemoryFakeAlwaysReadZero() = default;
74   virtual ~MemoryFakeAlwaysReadZero() = default;
75 
Read(uint64_t,void * buffer,size_t size)76   size_t Read(uint64_t, void* buffer, size_t size) override {
77     memset(buffer, 0, size);
78     return size;
79   }
80 };
81 
82 }  // namespace unwindstack
83 
84 #endif  // _LIBUNWINDSTACK_TESTS_MEMORY_FAKE_H
85