1/*
2 * Copyright (c) 2023 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 "ecmascript/platform/backtrace.h"
17
18#include <execinfo.h>
19#include <unistd.h>
20
21#include "ecmascript/mem/mem.h"
22
23namespace panda::ecmascript {
24static const int MAX_STACK_SIZE = 256;
25static const int FRAMES_LEN = 16;
26
27void Backtrace(std::ostringstream &stack, [[maybe_unused]] bool enableCache)
28{
29    void *buffer[MAX_STACK_SIZE];
30    char **stackList = nullptr;
31    int framesLen = backtrace(buffer, MAX_STACK_SIZE);
32    stackList = backtrace_symbols(buffer, framesLen);
33    if (stackList == nullptr) {
34        return;
35    }
36
37    stack << "=====================Backtrace========================";
38    for (int i = 0; i < FRAMES_LEN; ++i) {
39        if (stackList[i] == nullptr) {
40            break;
41        }
42        stack << stackList[i];
43    }
44
45    free(stackList);
46}
47} // namespace panda::ecmascript
48