• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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 #include "berberis/runtime_primitives/guest_function_wrapper_impl.h"
18 
19 #include <mutex>
20 #include <string>
21 #include <tuple>
22 #include <utility>
23 
24 #include "berberis/assembler/machine_code.h"
25 #include "berberis/base/forever_map.h"
26 #include "berberis/base/logging.h"
27 #include "berberis/code_gen_lib/gen_wrapper.h"
28 #include "berberis/guest_abi/guest_type.h"
29 #include "berberis/guest_state/guest_addr.h"
30 #include "berberis/runtime_primitives/code_pool.h"
31 #include "berberis/runtime_primitives/host_code.h"
32 #include "berberis/runtime_primitives/translation_cache.h"  // LookupGuestPC
33 
34 namespace berberis {
35 
36 namespace {
37 
38 // Guest function wrappers are identified by guest function address, signature
39 // string and guest runner. The guest function address alone is not enough.
40 //
41 // Example: on RISC-V soft float guest, these functions are binary equal:
42 //   float foo(float x, float y) { return y; }
43 //   int bar(int x, int y) { return y; }
44 // And it is possible that guest compiler generates code only once and sets
45 // both foo and bar to it. However, on x86 hosts and RISC-V hard float guest,
46 // foo and bar need different wrappers, as floats and ints are passed and
47 // returned in differently.
48 //
49 // Example: imagine we wrap thread_func to run from pthread_create.
50 // In addition to running thread_func, the guest runner we provide also cleans
51 // up guest thread on exit. If we also want to call thread_func in regular way,
52 // we need another guest runner, otherwise we'll get an unexpected thread
53 // cleanup.
54 //
55 // TODO(b/232598137): implementation is inefficient, check if that matters!
56 class WrapperCache {
57  public:
GetInstance()58   static WrapperCache* GetInstance() {
59     static WrapperCache g_wrapper_cache;
60     return &g_wrapper_cache;
61   }
62 
Find(GuestAddr pc,const char * signature,HostCode guest_runner) const63   HostCode Find(GuestAddr pc, const char* signature, HostCode guest_runner) const {
64     std::lock_guard<std::mutex> lock(mutex_);
65     auto it = map_.find(std::make_tuple(pc, signature, guest_runner));
66     if (it != map_.end()) {
67       return it->second;
68     }
69     return nullptr;
70   }
71 
72   // Another thread might have already inserted a wrapper for this key.
73   // In this case, discard the new wrapper and return the existing one.
Insert(GuestAddr pc,const char * signature,HostCode guest_runner,MachineCode * mc)74   HostCode Insert(GuestAddr pc, const char* signature, HostCode guest_runner, MachineCode* mc) {
75     std::lock_guard<std::mutex> lock(mutex_);
76     std::pair<WrapperMap::iterator, bool> res = map_.insert(
77         std::make_pair(std::make_tuple(pc, std::string(signature), guest_runner), nullptr));
78     if (res.second) {
79       res.first->second = GetFunctionWrapperCodePoolInstance()->Add(mc);
80     }
81     return res.first->second;
82   }
83 
SlowFindGuestAddrByWrapperAddr(void * wrapper_addr)84   GuestAddr SlowFindGuestAddrByWrapperAddr(void* wrapper_addr) {
85     std::lock_guard<std::mutex> lock(mutex_);
86     for (auto& entry : map_) {
87       if (entry.second == wrapper_addr) {
88         // Return pc.
89         return std::get<0>(entry.first);
90       }
91     }
92     return 0;
93   }
94 
95  private:
96   using WrapperKey = std::tuple<GuestAddr, std::string, HostCode>;
97   using WrapperMap = ForeverMap<WrapperKey, HostCode>;
98 
99   WrapperCache() = default;
100 
101   WrapperMap map_;
102   mutable std::mutex mutex_;
103 };
104 
105 IsAddressGuestExecutableFunc g_is_address_guest_executable_func = nullptr;
106 
107 }  // namespace
108 
InitGuestFunctionWrapper(IsAddressGuestExecutableFunc func)109 void InitGuestFunctionWrapper(IsAddressGuestExecutableFunc func) {
110   g_is_address_guest_executable_func = func;
111 }
112 
WrapGuestFunctionImpl(GuestAddr pc,const char * signature,GuestRunnerFunc runner,const char * name)113 HostCode WrapGuestFunctionImpl(GuestAddr pc,
114                                const char* signature,
115                                GuestRunnerFunc runner,
116                                const char* name) {
117   if (!pc) {
118     return nullptr;
119   }
120 
121   HostCode guest_runner = AsHostCode(runner);
122   WrapperCache* wrapper_cache = WrapperCache::GetInstance();
123   HostCode wrapper = wrapper_cache->Find(pc, signature, guest_runner);
124   if (!wrapper) {
125     // We can only wrap executable guest address! Even though execution will still fail, an early
126     // check here helps a lot when debugging.
127     // One special case is  wrapped host function (trampoline) that is passed back to the host.
128     // It should still go through the guest function wrapper and call trampoline code.
129     CHECK(g_is_address_guest_executable_func);
130     if (!g_is_address_guest_executable_func(pc) &&
131         !TranslationCache::GetInstance()->IsHostFunctionWrapped(pc)) {
132       LOG_ALWAYS_FATAL("Trying to wrap non-executable guest address 0x%zx", pc);
133     }
134     MachineCode mc;
135     GenWrapGuestFunction(&mc, pc, signature, guest_runner, name);
136     wrapper = wrapper_cache->Insert(pc, signature, guest_runner, &mc);
137   }
138   return wrapper;
139 }
140 
SlowFindGuestAddrByWrapperAddr(void * wrapper_addr)141 GuestAddr SlowFindGuestAddrByWrapperAddr(void* wrapper_addr) {
142   return WrapperCache::GetInstance()->SlowFindGuestAddrByWrapperAddr(wrapper_addr);
143 }
144 
145 }  // namespace berberis
146