• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <gtest/gtest.h>
17 #include <csignal>
18 #include <string>
19 #include <vector>
20 
21 #include "libpandafile/file_items.h"
22 #include "libpandafile/value.h"
23 #include "runtime/include/runtime.h"
24 #include "runtime/include/thread.h"
25 #include "libpandabase/macros.h"
26 #include "libpandabase/utils/utils.h"
27 #include "os/thread.h"
28 #include "runtime/include/managed_thread.h"
29 #include <sys/syscall.h>
30 #include "assembly-parser.h"
31 #include "assembly-emitter.h"
32 
33 namespace ark::test {
34 
Separator()35 inline std::string Separator()
36 {
37 #ifdef _WIN32
38     return "\\";
39 #else
40     return "/";
41 #endif
42 }
43 
44 static int g_counter = 0;
45 
SigProfSamplingProfilerHandler(int signum)46 void SigProfSamplingProfilerHandler([[maybe_unused]] int signum)
47 {
48     g_counter++;
49     std::array<volatile int, 100UL> a {};  // NOLINT(readability-magic-numbers)
50     for (int i = 0; i < 100_I; i++) {      // NOLINT(readability-magic-numbers)
51         a[i] = i;
52     }
53 }
54 
55 class Sampler final {
56 public:
57     Sampler() = default;
58     ~Sampler() = default;
59 
Start()60     bool Start()
61     {
62         managedThread_ = os::thread::GetCurrentThreadId();
63         isActive_ = true;
64 
65         // All prepairing actions should be done before this thread is started
66         samplerThread_ = std::make_unique<std::thread>(&Sampler::SamplerThreadEntry, this);
67         return true;
68     }
69 
Stop()70     void Stop()
71     {
72         if (!samplerThread_->joinable()) {
73             LOG(FATAL, PROFILER) << "Sampling profiler thread unexpectedly disappeared";
74             UNREACHABLE();
75         }
76 
77         isActive_ = false;
78 
79         samplerThread_->join();
80     }
81 
82 private:
SamplerThreadEntry()83     void SamplerThreadEntry()
84     {
85         struct sigaction action {};
86         action.sa_handler = SigProfSamplingProfilerHandler;
87         action.sa_flags = 0;
88         // Clear signal set
89         sigemptyset(&action.sa_mask);
90         // Ignore incoming sigprof if handler isn't completed
91         sigaddset(&action.sa_mask, SIGPROF);
92 
93         struct sigaction oldAction {};
94 
95         if (sigaction(SIGPROF, &action, &oldAction) == -1) {
96             LOG(FATAL, PROFILER) << "Sigaction failed, can't start profiling";
97             UNREACHABLE();
98         }
99 
100         auto pid = getpid();
101         // Atomic with relaxed order reason: data race with is_active_
102         while (isActive_.load(std::memory_order_relaxed)) {
103             {
104                 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
105                 if (syscall(SYS_tgkill, pid, managedThread_, SIGPROF) != 0) {
106                     LOG(ERROR, PROFILER) << "Can't send signal to thread";
107                 }
108             }
109             os::thread::NativeSleepUS(sampleInterval_);
110         }
111     }
112 
113     std::unique_ptr<std::thread> samplerThread_ {nullptr};
114 
115     std::atomic<bool> isActive_ = false;
116 
117     std::chrono::microseconds sampleInterval_ {200};  // NOLINT(readability-magic-numbers)
118 
119     os::thread::ThreadId managedThread_ = 0;
120 
121     NO_COPY_SEMANTIC(Sampler);
122     NO_MOVE_SEMANTIC(Sampler);
123 };
124 
125 class SignalHandlerTest : public testing::Test {
126 public:
SignalHandlerTest()127     SignalHandlerTest()
128     {
129         RuntimeOptions options;
130         options.SetLoadRuntimes({"core"});
131         auto execPath = ark::os::file::File::GetExecutablePath();
132         std::string pandaStdLib =
133             execPath.Value() + Separator() + ".." + Separator() + "pandastdlib" + Separator() + "arkstdlib.abc";
134         options.SetBootPandaFiles({pandaStdLib});
135         options.SetGcType("epsilon");
136         options.SetCompilerEnableJit(false);
137         options.SetCompilerEnableOsr(false);
138         Runtime::Create(options);
139 
140         thread_ = MTManagedThread::GetCurrent();
141     }
142 
~SignalHandlerTest()143     ~SignalHandlerTest() override
144     {
145         Runtime::Destroy();
146     }
147 
148     NO_COPY_SEMANTIC(SignalHandlerTest);
149     NO_MOVE_SEMANTIC(SignalHandlerTest);
150 
151 private:
152     MTManagedThread *thread_;
153 };
154 
155 static auto g_callTestSource = R"(
156     .record Math <external>
157     .function f64 Math.pow (f64 a0, f64 a1) <external>
158     .function f64 Math.absF64 (f64 a0) <external>
159 
160     .function void main_short() {
161         movi v0, 100000           #loop_counter
162         call.short main, v0
163         return.void
164     }
165     .function void main_long() {
166         movi v0, 10000000          #loop_counter
167         call.short main, v0
168         return.void
169     }
170     .function i32 main(i64 a0) {
171     movi v5, 0
172     loop:
173         lda v5
174         jeq a0, loop_exit
175         fmovi.64 v0, 2.5
176         fmovi.64 v1, 24.7052942201
177         fmovi.64 v2, 1e-6
178         fmovi.64 v3, 3.5
179         call.short Math.pow, v0, v3
180         fsub2.64 v1
181         sta.64 v1
182         call.short Math.absF64, v1, v1
183         fcmpl.64 v2
184         jgez exit_failure
185         inci v5, 1
186         jmp loop
187     loop_exit:
188         ldai 0
189         return
190     exit_failure:
191         ldai 1
192         return
193     }
194     )";
195 
TEST_F(SignalHandlerTest,CallTest)196 TEST_F(SignalHandlerTest, CallTest)
197 {
198     auto source = g_callTestSource;
199 
200     pandasm::Parser parser;
201     auto res = parser.Parse(source);
202     ASSERT_TRUE(res);
203     auto pf = pandasm::AsmEmitter::Emit(res.Value());
204     Runtime::GetCurrent()->GetClassLinker()->AddPandaFile(std::move(pf));
205 
206     Sampler sp;
207     ASSERT_EQ(sp.Start(), true);
208 #ifdef PANDA_TARGET_ARM32
209     Runtime::GetCurrent()->Execute("_GLOBAL::main_short", {});
210 #else
211     Runtime::GetCurrent()->Execute("_GLOBAL::main_long", {});
212 #endif
213 
214     sp.Stop();
215     ASSERT_NE(g_counter, 0);
216 }
217 
218 }  // namespace ark::test
219