• 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/host_function_wrapper_impl.h"
18 
19 #include "berberis/assembler/machine_code.h"
20 #include "berberis/base/tracing.h"
21 #include "berberis/code_gen_lib/gen_adaptor.h"
22 #include "berberis/guest_state/guest_addr.h"
23 #include "berberis/runtime_primitives/checks.h"
24 #include "berberis/runtime_primitives/code_pool.h"
25 #include "berberis/runtime_primitives/host_code.h"
26 #include "berberis/runtime_primitives/translation_cache.h"
27 
28 namespace berberis {
29 
MakeTrampolineCallable(GuestAddr pc,bool is_host_func,TrampolineFunc func,HostCode arg,const char * name)30 void MakeTrampolineCallable(GuestAddr pc,
31                             bool is_host_func,
32                             TrampolineFunc func,
33                             HostCode arg,
34                             const char* name) {
35   if (!pc) {
36     return;
37   }
38 
39   // Guest address for wrapped host function must be properly aligned, otherwise
40   // the guest simply can't encode it to call by immediate. We are unlikely affected,
41   // as calling an external symbol by immediate requires text relocation, but
42   // we should still issue an error.
43   if (!IsProgramCounterProperlyAlignedForArch(pc)) {
44     TRACE("address %p of wrapped host function '%s' is not aligned", ToHostAddr<void>(pc), name);
45   }
46   TranslationCache* cache = TranslationCache::GetInstance();
47   GuestCodeEntry* entry = cache->AddAndLockForWrapping(pc);
48   if (entry) {
49     MachineCode mc;
50     GenTrampolineAdaptor(&mc, pc, AsHostCode(func), arg, name);
51     cache->SetWrappedAndUnlock(pc,
52                                entry,
53                                is_host_func,
54                                // TODO(b/232598137): Maybe use ColdCodePool?
55                                {GetDefaultCodePoolInstance()->Add(&mc), mc.install_size()});
56   }
57 }
58 
UnwrapHostFunction(GuestAddr pc)59 void* UnwrapHostFunction(GuestAddr pc) {
60   if (TranslationCache::GetInstance()->IsHostFunctionWrapped(pc)) {
61     // Wrapped entry.
62     return ToHostAddr<void>(pc);
63   }
64   return nullptr;
65 }
66 
67 }  // namespace berberis
68