• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2023-2025 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         // Atomic with release order reason: To ensure start store correctly
64         isActive_.store(true, std::memory_order_release);
65 
66         // All prepairing actions should be done before this thread is started
67         samplerThread_ = std::make_unique<std::thread>(&Sampler::SamplerThreadEntry, this);
68         return true;
69     }
70 
Stop()71     void Stop()
72     {
73         if (!samplerThread_->joinable()) {
74             LOG(FATAL, PROFILER) << "Sampling profiler thread unexpectedly disappeared";
75             UNREACHABLE();
76         }
77 
78         // Atomic with release order reason: To ensure stop store correctly
79         isActive_.store(false, std::memory_order_release);
80 
81         samplerThread_->join();
82     }
83 
84 private:
SamplerThreadEntry()85     void SamplerThreadEntry()
86     {
87         struct sigaction action {};
88         action.sa_handler = SigProfSamplingProfilerHandler;
89         action.sa_flags = 0;
90         // Clear signal set
91         sigemptyset(&action.sa_mask);
92         // Ignore incoming sigprof if handler isn't completed
93         sigaddset(&action.sa_mask, SIGPROF);
94 
95         struct sigaction oldAction {};
96 
97         if (sigaction(SIGPROF, &action, &oldAction) == -1) {
98             LOG(FATAL, PROFILER) << "Sigaction failed, can't start profiling";
99             UNREACHABLE();
100         }
101 
102         auto pid = getpid();
103         // Atomic with acquire order reason: To ensure start/stop load correctly
104         while (isActive_.load(std::memory_order_acquire)) {
105             {
106                 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
107                 if (syscall(SYS_tgkill, pid, managedThread_, SIGPROF) != 0) {
108                     LOG(ERROR, PROFILER) << "Can't send signal to thread";
109                 }
110             }
111             os::thread::NativeSleepUS(sampleInterval_);
112         }
113     }
114 
115     std::unique_ptr<std::thread> samplerThread_ {nullptr};
116 
117     std::atomic<bool> isActive_ {false};
118 
119     std::chrono::microseconds sampleInterval_ {200};  // NOLINT(readability-magic-numbers)
120 
121     os::thread::ThreadId managedThread_ = 0;
122 
123     NO_COPY_SEMANTIC(Sampler);
124     NO_MOVE_SEMANTIC(Sampler);
125 };
126 
127 class SignalHandlerTest : public testing::Test {
128 public:
SignalHandlerTest()129     SignalHandlerTest()
130     {
131         RuntimeOptions options;
132         options.SetLoadRuntimes({"core"});
133         auto execPath = ark::os::file::File::GetExecutablePath();
134         std::string pandaStdLib =
135             execPath.Value() + Separator() + ".." + Separator() + "pandastdlib" + Separator() + "arkstdlib.abc";
136         options.SetBootPandaFiles({pandaStdLib});
137         options.SetGcType("epsilon");
138         options.SetCompilerEnableJit(false);
139         options.SetCompilerEnableOsr(false);
140         Runtime::Create(options);
141 
142         thread_ = MTManagedThread::GetCurrent();
143     }
144 
~SignalHandlerTest()145     ~SignalHandlerTest() override
146     {
147         Runtime::Destroy();
148     }
149 
150     NO_COPY_SEMANTIC(SignalHandlerTest);
151     NO_MOVE_SEMANTIC(SignalHandlerTest);
152 
153 private:
154     MTManagedThread *thread_;
155 };
156 
157 static auto g_callTestSource = R"(
158     .record Math <external>
159     .function f64 Math.pow (f64 a0, f64 a1) <external>
160     .function f64 Math.absF64 (f64 a0) <external>
161 
162     .function void main_short() {
163         movi v0, 100000           #loop_counter
164         call.short main, v0
165         return.void
166     }
167     .function void main_long() {
168         movi v0, 10000000          #loop_counter
169         call.short main, v0
170         return.void
171     }
172     .function i32 main(i64 a0) {
173     movi v5, 0
174     loop:
175         lda v5
176         jeq a0, loop_exit
177         fmovi.64 v0, 2.5
178         fmovi.64 v1, 24.7052942201
179         fmovi.64 v2, 1e-6
180         fmovi.64 v3, 3.5
181         call.short Math.pow, v0, v3
182         fsub2.64 v1
183         sta.64 v1
184         call.short Math.absF64, v1, v1
185         fcmpl.64 v2
186         jgez exit_failure
187         inci v5, 1
188         jmp loop
189     loop_exit:
190         ldai 0
191         return
192     exit_failure:
193         ldai 1
194         return
195     }
196     )";
197 
TEST_F(SignalHandlerTest,CallTest)198 TEST_F(SignalHandlerTest, CallTest)
199 {
200     auto source = g_callTestSource;
201 
202     pandasm::Parser parser;
203     auto res = parser.Parse(source);
204     ASSERT_TRUE(res);
205     auto pf = pandasm::AsmEmitter::Emit(res.Value());
206     Runtime::GetCurrent()->GetClassLinker()->AddPandaFile(std::move(pf));
207 
208     Sampler sp;
209     ASSERT_EQ(sp.Start(), true);
210 #ifdef PANDA_TARGET_ARM32
211     Runtime::GetCurrent()->Execute("_GLOBAL::main_short", {});
212 #else
213     Runtime::GetCurrent()->Execute("_GLOBAL::main_long", {});
214 #endif
215 
216     sp.Stop();
217     ASSERT_NE(g_counter, 0);
218 }
219 
220 }  // namespace ark::test
221