1 /*
2 * Copyright (c) 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 #include "thread_sampler_api.h"
16
17 #include <cstring>
18
19 namespace OHOS {
20 namespace HiviewDFX {
21 namespace {
22 constexpr int SUCCESS = 0;
23 constexpr int FAIL = -1;
24 } // namespace
ThreadSamplerInit(int collectStackCount)25 int ThreadSamplerInit(int collectStackCount)
26 {
27 return ThreadSampler::GetInstance().Init(collectStackCount) ? SUCCESS : FAIL;
28 }
29
ThreadSamplerSample()30 int32_t ThreadSamplerSample()
31 {
32 return ThreadSampler::GetInstance().Sample();
33 }
34
ThreadSamplerCollect(char * stack,char * heaviestStack,size_t stackSize,size_t heaviestSize,int treeFormat)35 int ThreadSamplerCollect(char* stack, char* heaviestStack, size_t stackSize, size_t heaviestSize, int treeFormat)
36 {
37 bool enableTreeFormat = (treeFormat == 1);
38 std::string stk;
39 int success = (ThreadSampler::GetInstance().CollectStack(stk, enableTreeFormat) ? SUCCESS : FAIL);
40 size_t len = (stk.size() >= stackSize ? stackSize - 1 : stk.size());
41 if (strncpy_s(stack, stackSize, stk.c_str(), len) != EOK) {
42 return FAIL;
43 }
44 if (enableTreeFormat) {
45 std::string heaviest = ThreadSampler::GetInstance().GetHeaviestStack();
46 size_t heaviestLen = (heaviest.size() >= heaviestSize ? heaviestSize - 1 : heaviest.size());
47 if (strncpy_s(heaviestStack, heaviestSize, heaviest.c_str(), heaviestLen) != EOK) {
48 return FAIL;
49 }
50 }
51 return success;
52 }
53
ThreadSamplerDeinit()54 int ThreadSamplerDeinit()
55 {
56 return ThreadSampler::GetInstance().Deinit() ? SUCCESS : FAIL;
57 }
58
ThreadSamplerSigHandler(int sig,siginfo_t * si,void * context)59 void ThreadSamplerSigHandler(int sig, siginfo_t* si, void* context)
60 {
61 ThreadSampler::ThreadSamplerSignalHandler(sig, si, context);
62 }
63 } // namespace HiviewDFX
64 } // namespace OHOS
65