• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 #include "ecmascript/platform/async_detect.h"
17 
18 #include "ecmascript/dfx/stackinfo/async_stack_trace.h"
19 
20 namespace panda::ecmascript {
RegisterAsyncDetectCallBack(EcmaVM * vm)21 void RegisterAsyncDetectCallBack([[maybe_unused]] EcmaVM *vm)
22 {
23 #if !defined(STANDALONE_MODE) && !defined(CROSS_PLATFORM)
24     if (vm->GetJSOptions().EnablePendingCheak()) {
25         uv_loop_t *loop = reinterpret_cast<uv_loop_t *>(vm->GetLoop());
26         if (loop == nullptr) {
27             LOG_ECMA(ERROR) << "Get loop failed";
28             return;
29         }
30         static thread_local uv_timer_t handle;
31         uv_timer_init(loop, &handle);
32         handle.data = vm->GetAsyncStackTrace();
33         uv_timer_start(&handle, AsyncDetectCallBack, 0, AsyncStackTrace::PROMISE_PENDING_TIME_MS);
34         if (vm->GetJSThread()->IsMainThread()) {
35             uv_async_send(&loop->wq_async);
36         } else {
37             uv_work_t *work = new uv_work_t;
38             uv_queue_work(loop, work, [](uv_work_t *) { }, [](uv_work_t *work, int32_t) { delete work; });
39         }
40     }
41 #endif
42 }
43 
44 #if !defined(STANDALONE_MODE) && !defined(CROSS_PLATFORM)
AsyncDetectCallBack(uv_timer_t * handle)45 void AsyncDetectCallBack(uv_timer_t* handle)
46 {
47     AsyncStackTrace *asyncStackTrace = static_cast<AsyncStackTrace *>(handle->data);
48     auto now = std::chrono::system_clock::now();
49     auto currentTime = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
50     CMap<uint32_t, std::pair<std::string, int64_t>> asyncTasks = asyncStackTrace->GetAsyncStackTrace();
51     for (auto asyncTask : asyncTasks) {
52         if (currentTime - asyncTask.second.second >= AsyncStackTrace::PROMISE_PENDING_TIME_MS) {
53             LOG_ECMA(ERROR) << "Pending time: " << currentTime - asyncTask.second.second
54                 << ", stack: \n" <<  asyncTask.second.first;
55         }
56     }
57 }
58 #endif
59 } // namespace panda::ecmascript