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