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/runtime_library.h"
18 
19 #include <csetjmp>
20 
21 #include "berberis/base/checks.h"
22 #include "berberis/base/logging.h"
23 #include "berberis/base/tracing.h"
24 #include "berberis/guest_os_primitives/guest_thread.h"
25 #include "berberis/guest_state/guest_state_opaque.h"
26 #include "berberis/runtime/execute_guest.h"
27 
28 namespace berberis {
29 
ExecuteGuestCall(ThreadState * state)30 void ExecuteGuestCall(ThreadState* state) {
31   CHECK(state);
32   auto* thread = GetGuestThread(*state);
33   GuestCallExecution guest_call_execution{.parent = thread->guest_call_execution(),
34                                           .sp = GetStackRegister(GetCPUState(*state))};
35 
36   // ATTENTION: don't save/restore signal mask, this is done by guest!
37   sigsetjmp(guest_call_execution.buf, 0);
38   // Set current execution for normal flow, or reset it after a longjmp.
39   thread->set_guest_call_execution(&guest_call_execution);
40 
41   ExecuteGuest(state);
42 
43   thread->set_guest_call_execution(guest_call_execution.parent);
44 
45   if (guest_call_execution.sp == GetStackRegister(GetCPUState(*state))) {
46     return;
47   }
48 
49   // Stack pointer may not be restored if guest executed a statically linked longjmp.
50   // Search parent executions for current sp.
51   for (auto* curr = thread->guest_call_execution(); curr; curr = curr->parent) {
52     // TODO(b/232598137): It'd be more reliable to also check (stop_pc ==
53     // insn_addr) for the matching execution, but currently stop_pc is always the
54     // same for all executions.
55     if (curr->sp == GetStackRegister(GetCPUState(*state))) {
56       TRACE("Detected statically linked longjmp");
57       siglongjmp(curr->buf, 1);
58     }
59   }
60 
61   LOG_ALWAYS_FATAL("Guest call didn't restore sp: expected %p, actual %p",
62                    ToHostAddr<void>(guest_call_execution.sp),
63                    ToHostAddr<void>(GetStackRegister(GetCPUState(*state))));
64 }
65 
66 }  // namespace berberis
67