• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "CrashHandler.h"
17 
18 #include <csignal>
19 #include <cstdlib>
20 #include <execinfo.h>
21 #include <sstream>
22 #include <unistd.h>
23 
24 #include "PreviewerEngineLog.h"
25 #include "PublicMethods.h"
26 
27 using namespace std;
28 
29 static void *oldBacetrace[10] = { nullptr };
30 static size_t oldSize = 0;
31 
InitExceptionHandler()32 void CrashHandler::InitExceptionHandler()
33 {
34     if (signal(SIGSEGV, ApplicationCrashHandler) == SIG_ERR) {
35         ELOG("InitExceptionHandler failed");
36         return;
37     }
38 }
39 
ApplicationCrashHandler(int signal)40 void CrashHandler::ApplicationCrashHandler(int signal)
41 {
42     // get void*'s for all entries on the stack
43     const uint32_t MAX_STACK_SIZE = 128;
44     int len = 10;
45     void *array[len];
46     size_t size = backtrace(array, MAX_STACK_SIZE);
47     bool isSame = true;
48     if (oldSize == size) {
49         for (size_t i = 0; i < size; i++) {
50             if (oldBacetrace[i] != array[i]) {
51                 isSame = false;
52             }
53         }
54     }
55     if (isSame) {
56         return;
57     }
58     // print crash log head
59     int8_t crashBeginLog[] = "[JsEngine Crash]Engine Crash Info Begin.\n";
60     write(STDERR_FILENO, crashBeginLog, sizeof(crashBeginLog) - 1);
61     int8_t stackIntLog[PublicMethods::MAX_ITOA_BIT] = {0};
62     uint32_t itoaLength = PublicMethods::Ulltoa(signal, stackIntLog);
63     int8_t signalLog[] = "[JsEngine Crash]Error: signal : 0x";
64     write(STDERR_FILENO, signalLog, sizeof(signalLog) - 1);
65     write(STDERR_FILENO, stackIntLog, itoaLength);
66     // print out all the frames to stdout
67     backtrace_symbols_fd(array, size, STDERR_FILENO);
68     std::fill(oldBacetrace, oldBacetrace + len, nullptr);
69     std::copy(array, array + len, oldBacetrace);
70     oldSize = size;
71     // print crash log end
72     int8_t crashEndLog[] = "\n[JsEngine Crash]Engine Crash Info End.\n";
73     write(STDERR_FILENO, crashEndLog, sizeof(crashEndLog) - 1);
74 }