• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 #ifndef DFX_UNIQUE_CRASH_OBJ
17 #define DFX_UNIQUE_CRASH_OBJ
18 
19 #include "dfx_signal_handler.h"
20 
21 namespace OHOS {
22 namespace HiviewDFX {
23 
24 /**
25  * @brief RAII wrapper for managing crash diagnostic objects
26  *
27  * Automatically attaches and detaches diagnostic information to the crash context
28  * using the Resource Acquisition Is Initialization (RAII) pattern. This ensures
29  * that diagnostic data is properly registered on construction and unregistered
30  * on destruction, even if exceptions occur.
31  *
32  * @warning The diagnostic data buffer pointed to by the constructor argument
33  *          must remain valid for the lifetime of this object.
34  *
35  * Example Usage:
36  * @code
37  * void ProcessRequest(const std::string& requestId)
38  * {
39  *     // Attach request ID to crash context for diagnostic purposes
40  *     UniqueCrashObj crashInfo(OBJ_STRING, requestId.c_str());
41  *     // ... perform operations that might crash ...
42  * } // crashInfo is automatically detached here
43  * @endcode
44  *
45  * @dependency Add the following to your BUILD.gn:
46  * @code
47  * external_deps += [ "faultloggerd:dfx_signalhandler" ]
48  * @endcode
49  */
50 class UniqueCrashObj final {
51 public:
52     /**
53      * @brief Constructs a UniqueCrashObj and attaches diagnostic data
54      *
55      * @param objType Type of diagnostic data (see CrashObjType enum)
56      * @param objAddr Pointer to the data buffer. Must remain valid until destruction.
57      */
UniqueCrashObj(CrashObjType objType,uintptr_t objAddr)58     explicit UniqueCrashObj(CrashObjType objType, uintptr_t objAddr)
59         : lastObjAddr_(DFX_SetCrashObj(objType, objAddr)) {}
60 
61     /**
62      * @brief Destructor automatically detaches diagnostic data
63      */
~UniqueCrashObj()64     ~UniqueCrashObj()
65     {
66         DFX_ResetCrashObj(lastObjAddr_);
67     }
68 
69     // Disable copy operations to prevent double detachment
70     UniqueCrashObj(const UniqueCrashObj&) = delete;
71     UniqueCrashObj& operator=(const UniqueCrashObj&) = delete;
72 
73 private:
74     uintptr_t lastObjAddr_; // handle to the previously set crash object
75 };
76 
77 } // namespace HiviewDFX
78 } // namespace OHOS
79 
80 #endif // DFX_UNIQUE_CRASH_OBJ