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 #include "berberis/lite_translator/lite_translate_region.h"
17 
18 #include <cstdint>
19 #include <limits>
20 #include <tuple>
21 
22 #include "berberis/assembler/machine_code.h"
23 #include "berberis/base/checks.h"
24 #include "berberis/code_gen_lib/code_gen_lib.h"
25 #include "berberis/decoder/riscv64/decoder.h"
26 #include "berberis/decoder/riscv64/semantics_player.h"
27 #include "berberis/guest_state/guest_addr.h"
28 
29 #include "riscv64_to_x86_64/lite_translator.h"
30 
31 namespace berberis {
32 
33 namespace {
34 
Finalize(LiteTranslator * translator,GuestAddr pc)35 void Finalize(LiteTranslator* translator, GuestAddr pc) {
36   translator->ExitRegion(pc);
37   translator->as()->Finalize();
38 }
39 
GenIncrementProfileCounter(x86_64::Assembler * as,const LiteTranslateParams & params)40 void GenIncrementProfileCounter(x86_64::Assembler* as, const LiteTranslateParams& params) {
41   CHECK(params.counter_location);
42   *params.counter_location = 0;
43 
44   // Ideally for thread safety the counter subtraction needs to be atomic. But,
45   // our experiments showed that the overhead from LOCK prefix here is too high
46   // (b/222363018#comment3).
47   // The threshold for the counter is an heuristic though. The worst what can
48   // happen due to racing threads is counter inadvertently rolling back to a
49   // value a few increments before, which we consider acceptable.
50   // WARNING: do not clobber rax, since insn_addr held in it is used in case of
51   // the reached threshold.
52   as->Movq(as->rcx, bit_cast<int64_t>(params.counter_location));
53   static_assert(sizeof(*params.counter_location) == 4);
54   as->Addl({.base = as->rcx}, 1);
55   as->Cmpl({.base = as->rcx}, params.counter_threshold);
56   as->Jcc(x86_64::Assembler::Condition::kGreater, params.counter_threshold_callback);
57 }
58 
59 // Returns the success status and
60 // - in case of success, the pc of the next instruction past the translated region
61 // - in case of failure, the pc of the failed instruction
62 // Specifically, returnes input pc if we cannot translate even the first instruction.
TryLiteTranslateRegionImpl(GuestAddr start_pc,GuestAddr end_pc,MachineCode * machine_code,LiteTranslateParams params)63 std::tuple<bool, GuestAddr> TryLiteTranslateRegionImpl(GuestAddr start_pc,
64                                                        GuestAddr end_pc,
65                                                        MachineCode* machine_code,
66                                                        LiteTranslateParams params) {
67   CHECK_LT(start_pc, end_pc);
68   LiteTranslator translator(machine_code, start_pc, params);
69   SemanticsPlayer sem_player(&translator);
70   Decoder decoder(&sem_player);
71 
72   if (params.enable_self_profiling) {
73     GenIncrementProfileCounter(translator.as(), params);
74   }
75 
76   while (translator.GetInsnAddr() != end_pc && !translator.is_region_end_reached()) {
77     uint8_t insn_size = decoder.Decode(ToHostAddr<const uint16_t>(translator.GetInsnAddr()));
78     if (!translator.success()) {
79       return {false, translator.GetInsnAddr()};
80     }
81     translator.FreeTempRegs();
82     translator.IncrementInsnAddr(insn_size);
83   }
84 
85   Finalize(&translator, translator.GetInsnAddr());
86 
87   return {translator.success(), translator.GetInsnAddr()};
88 }
89 
90 }  // namespace
91 
LiteTranslateRange(GuestAddr start_pc,GuestAddr end_pc,MachineCode * machine_code,LiteTranslateParams params)92 bool LiteTranslateRange(GuestAddr start_pc,
93                         GuestAddr end_pc,
94                         MachineCode* machine_code,
95                         LiteTranslateParams params) {
96   auto [success, stop_pc] = TryLiteTranslateRegionImpl(start_pc, end_pc, machine_code, params);
97   return success;
98 }
99 
TryLiteTranslateRegion(GuestAddr start_pc,MachineCode * machine_code,LiteTranslateParams params)100 std::tuple<bool, GuestAddr> TryLiteTranslateRegion(GuestAddr start_pc,
101                                                    MachineCode* machine_code,
102                                                    LiteTranslateParams params) {
103   // This effectively makes translating code at max guest address impossible, but we
104   // assume that it's not practically significant.
105   return TryLiteTranslateRegionImpl(
106       start_pc, std::numeric_limits<GuestAddr>::max(), machine_code, params);
107 }
108 
109 }  // namespace berberis
110