1/*
2 * Copyright (C) 2015 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 _DEBUGGERD_TEST_BACKTRACE_MOCK_H
18#define _DEBUGGERD_TEST_BACKTRACE_MOCK_H
19
20#include <stdint.h>
21#include <stdlib.h>
22#include <string.h>
23#include <sys/ucontext.h>
24
25#include <string>
26#include <vector>
27
28#include <backtrace/Backtrace.h>
29#include <backtrace/BacktraceMap.h>
30
31class BacktraceMapMock : public BacktraceMap {
32 public:
33  BacktraceMapMock() : BacktraceMap(0) {}
34  virtual ~BacktraceMapMock() {}
35
36  void AddMap(backtrace_map_t& map) {
37    maps_.push_back(map);
38  }
39};
40
41
42class BacktraceMock : public Backtrace {
43 public:
44  BacktraceMock(BacktraceMapMock* map) : Backtrace(0, 0, map) {
45    if (map_ == nullptr) {
46      abort();
47    }
48  }
49  virtual ~BacktraceMock() {}
50
51  virtual bool Unwind(size_t, ucontext_t*) { return false; }
52  virtual bool ReadWord(uintptr_t, word_t*) { return false;}
53
54  virtual std::string GetFunctionNameRaw(uintptr_t, uintptr_t*) { return ""; }
55
56  virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
57    size_t offset = 0;
58    if (last_read_addr_ > 0) {
59      offset = addr - last_read_addr_;
60    }
61    size_t bytes_available = buffer_.size() - offset;
62
63    if (bytes_partial_read_ > 0) {
64      // Do a partial read.
65      if (bytes > bytes_partial_read_) {
66        bytes = bytes_partial_read_;
67      }
68      bytes_partial_read_ -= bytes;
69    } else if (bytes > bytes_available) {
70      bytes = bytes_available;
71    }
72
73    if (bytes > 0) {
74      memcpy(buffer, buffer_.data() + offset, bytes);
75    }
76
77    last_read_addr_ = addr;
78    return bytes;
79  }
80
81  void SetReadData(uint8_t* buffer, size_t bytes) {
82    buffer_.resize(bytes);
83    memcpy(buffer_.data(), buffer, bytes);
84    bytes_partial_read_ = 0;
85    last_read_addr_ = 0;
86  }
87
88  void SetPartialReadAmount(size_t bytes) {
89    if (bytes > buffer_.size()) {
90      abort();
91    }
92    bytes_partial_read_ = bytes;
93  }
94
95 private:
96  std::vector<uint8_t> buffer_;
97  size_t bytes_partial_read_ = 0;
98  uintptr_t last_read_addr_ = 0;
99};
100
101#endif //  _DEBUGGERD_TEST_BACKTRACE_MOCK_H
102