1 /*
2 * Copyright (c) 2022-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 "napi_hisysevent_adapter.h"
17
18 #include <cctype>
19 #include <memory>
20
21 #include "def.h"
22 #include "hilog/log.h"
23 #include "napi_hisysevent_util.h"
24 #include "native_engine/native_engine.h"
25
26 namespace OHOS {
27 namespace HiviewDFX {
28 namespace {
29 constexpr HiLogLabel LABEL = { LOG_CORE, 0xD002D08, "NAPI_HISYSEVENT_ADAPTER" };
30 constexpr size_t ERR_INDEX = 0;
31 constexpr size_t VAL_INDEX = 1;
32 constexpr size_t RET_SIZE = 2;
33 constexpr int64_t DEFAULT_LINE_NUM = -1;
34 constexpr char FUNC_SOURCE_NAME[] = "JSHiSysEventWrite";
35 constexpr int FUNC_NAME_INDEX = 1;
36 constexpr int LINE_INFO_INDEX = 2;
37 constexpr int LINE_INDEX = 1;
38 constexpr char CALL_FUNC_INFO_DELIMITER = ' ';
39 constexpr char CALL_LINE_INFO_DELIMITER = ':';
40 constexpr char PATH_DELIMITER = '/';
41
IsUninitializedJsCallerInfo(const JsCallerInfo & info)42 bool IsUninitializedJsCallerInfo(const JsCallerInfo& info)
43 {
44 return info.first.empty() || info.second == DEFAULT_LINE_NUM;
45 }
46
Split(const std::string & origin,char delimiter,std::vector<std::string> & ret)47 void Split(const std::string& origin, char delimiter, std::vector<std::string>& ret)
48 {
49 std::string::size_type start = 0;
50 std::string::size_type end = origin.find(delimiter);
51 while (end != std::string::npos) {
52 if (end == start) {
53 start++;
54 end = origin.find(delimiter, start);
55 continue;
56 }
57 ret.emplace_back(origin.substr(start, end - start));
58 start = end + 1;
59 end = origin.find(delimiter, start);
60 }
61 if (start != origin.length()) {
62 ret.emplace_back(origin.substr(start));
63 }
64 }
65
ParseCallerInfoFromStackTrace(const std::string & stackTrace,JsCallerInfo & callerInfo)66 void ParseCallerInfoFromStackTrace(const std::string& stackTrace, JsCallerInfo& callerInfo)
67 {
68 if (stackTrace.empty()) {
69 HiLog::Error(LABEL, "js stack trace is invalid.");
70 return;
71 }
72 std::vector<std::string> callInfos;
73 Split(stackTrace, CALL_FUNC_INFO_DELIMITER, callInfos);
74 if (callInfos.size() <= FUNC_NAME_INDEX) {
75 HiLog::Error(LABEL, "js function name parsed failed.");
76 return;
77 }
78 callerInfo.first = callInfos[FUNC_NAME_INDEX];
79 if (callInfos.size() <= LINE_INFO_INDEX) {
80 HiLog::Error(LABEL, "js function line info parsed failed.");
81 return;
82 }
83 std::string callInfo = callInfos[LINE_INFO_INDEX];
84 std::vector<std::string> lineInfos;
85 Split(callInfo, CALL_LINE_INFO_DELIMITER, lineInfos);
86 if (lineInfos.size() <= LINE_INDEX) {
87 HiLog::Error(LABEL, "js function line number parsed failed.");
88 return;
89 }
90 if (callerInfo.first == "anonymous") {
91 auto fileName = lineInfos[LINE_INDEX - 1];
92 auto pos = fileName.find_last_of(PATH_DELIMITER);
93 callerInfo.first = (pos == std::string::npos) ? fileName : fileName.substr(++pos);
94 }
95 auto lineInfo = lineInfos[LINE_INDEX];
96 if (std::any_of(lineInfo.begin(), lineInfo.end(), [] (auto& c) {
97 return !isdigit(c);
98 })) {
99 callerInfo.second = DEFAULT_LINE_NUM;
100 return;
101 }
102 callerInfo.second = static_cast<int64_t>(std::stoll(lineInfos[LINE_INDEX]));
103 }
104 }
105
ParseJsCallerInfo(const napi_env env,JsCallerInfo & callerInfo)106 void NapiHiSysEventAdapter::ParseJsCallerInfo(const napi_env env, JsCallerInfo& callerInfo)
107 {
108 NativeEngine* engine = reinterpret_cast<NativeEngine*>(env);
109 std::string stackTrace;
110 if (!engine->BuildJsStackTrace(stackTrace)) {
111 HiLog::Error(LABEL, "js stack trace build failed.");
112 return;
113 }
114 ParseCallerInfoFromStackTrace(stackTrace, callerInfo);
115 }
116
CheckThenWriteSysEvent(HiSysEventAsyncContext * eventAsyncContext)117 void NapiHiSysEventAdapter::CheckThenWriteSysEvent(HiSysEventAsyncContext* eventAsyncContext)
118 {
119 if (eventAsyncContext == nullptr) {
120 return;
121 }
122 if (eventAsyncContext->eventWroteResult != SUCCESS) {
123 return;
124 }
125 auto eventInfo = eventAsyncContext->eventInfo;
126 auto jsCallerInfo = eventAsyncContext->jsCallerInfo;
127 if (IsUninitializedJsCallerInfo(jsCallerInfo)) {
128 eventAsyncContext->eventWroteResult = Write(eventInfo);
129 return;
130 }
131 ControlParam param {
132 .period = HISYSEVENT_DEFAULT_PERIOD,
133 .threshold = HISYSEVENT_DEFAULT_THRESHOLD,
134 };
135 if (HiSysEvent::controller.CheckLimitWritingEvent(param, eventInfo.domain.c_str(), eventInfo.name.c_str(),
136 jsCallerInfo.first.c_str(), jsCallerInfo.second)) {
137 eventAsyncContext->eventWroteResult = ERR_WRITE_IN_HIGH_FREQ;
138 return;
139 }
140 eventAsyncContext->eventWroteResult = Write(eventInfo);
141 }
142
Write(const napi_env env,HiSysEventAsyncContext * eventAsyncContext)143 void NapiHiSysEventAdapter::Write(const napi_env env, HiSysEventAsyncContext* eventAsyncContext)
144 {
145 napi_value resource = nullptr;
146 NapiHiSysEventUtil::CreateStringValue(env, FUNC_SOURCE_NAME, resource);
147 napi_create_async_work(
148 env, nullptr, resource,
149 [] (napi_env env, void* data) {
150 HiSysEventAsyncContext* eventAsyncContext = reinterpret_cast<HiSysEventAsyncContext*>(data);
151 CheckThenWriteSysEvent(eventAsyncContext);
152 },
153 [] (napi_env env, napi_status status, void* data) {
154 HiSysEventAsyncContext* eventAsyncContext = reinterpret_cast<HiSysEventAsyncContext*>(data);
155 napi_value results[RET_SIZE] = {0};
156 auto isNormalWrote = eventAsyncContext->eventWroteResult == SUCCESS &&
157 !NapiHiSysEventUtil::HasStrParamLenOverLimit(eventAsyncContext->eventInfo);
158 if (isNormalWrote) {
159 NapiHiSysEventUtil::CreateNull(env, results[ERR_INDEX]);
160 NapiHiSysEventUtil::CreateInt32Value(env, eventAsyncContext->eventWroteResult, results[VAL_INDEX]);
161 } else {
162 NapiHiSysEventUtil::CreateNull(env, results[VAL_INDEX]);
163 auto errorCode = eventAsyncContext->eventWroteResult == SUCCESS ? ERR_VALUE_LENGTH_TOO_LONG :
164 eventAsyncContext->eventWroteResult;
165 results[ERR_INDEX] = NapiHiSysEventUtil::CreateErrorByRet(env, errorCode);
166 }
167 if (eventAsyncContext->deferred != nullptr) { // promise
168 isNormalWrote ? napi_resolve_deferred(env, eventAsyncContext->deferred, results[VAL_INDEX]) :
169 napi_reject_deferred(env, eventAsyncContext->deferred, results[ERR_INDEX]);
170 } else {
171 napi_value callback = nullptr;
172 napi_get_reference_value(env, eventAsyncContext->callback, &callback);
173 napi_value retValue = nullptr;
174 napi_call_function(env, nullptr, callback, RET_SIZE, results, &retValue);
175 napi_delete_reference(env, eventAsyncContext->callback);
176 }
177 napi_delete_async_work(env, eventAsyncContext->asyncWork);
178 delete eventAsyncContext;
179 }, reinterpret_cast<void*>(eventAsyncContext), &eventAsyncContext->asyncWork);
180 napi_queue_async_work_with_qos(env, eventAsyncContext->asyncWork, napi_qos_default);
181 }
182
InnerWrite(InnerWriter::EventBase & eventBase,const HiSysEventInfo & eventInfo)183 void NapiHiSysEventAdapter::InnerWrite(InnerWriter::EventBase& eventBase,
184 const HiSysEventInfo& eventInfo)
185 {
186 AppendParams(eventBase, eventInfo.boolParams);
187 AppendParams(eventBase, eventInfo.boolArrayParams);
188 AppendParams(eventBase, eventInfo.doubleParams);
189 AppendParams(eventBase, eventInfo.doubleArrayParams);
190 AppendParams(eventBase, eventInfo.stringParams);
191 AppendParams(eventBase, eventInfo.stringArrayParams);
192 }
193
Write(const HiSysEventInfo & eventInfo)194 int NapiHiSysEventAdapter::Write(const HiSysEventInfo& eventInfo)
195 {
196 InnerWriter::EventBase eventBase(eventInfo.domain, eventInfo.name, eventInfo.eventType);
197 InnerWriter::WritebaseInfo(eventBase);
198 if (InnerWriter::IsError(eventBase)) {
199 InnerWriter::ExplainRetCode(eventBase);
200 return eventBase.GetRetCode();
201 }
202
203 InnerWrite(eventBase, eventInfo);
204 InnerWriter::InnerWrite(eventBase);
205 if (InnerWriter::IsError(eventBase)) {
206 InnerWriter::ExplainRetCode(eventBase);
207 return eventBase.GetRetCode();
208 }
209
210 InnerWriter::SendSysEvent(eventBase);
211 return eventBase.GetRetCode();
212 }
213 } // namespace HiviewDFX
214 } // namespace OHOS
215