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#include "lock_parser.h"
16
17#include <vector>
18
19#include <pthread.h>
20
21#include "dfx_log.h"
22namespace OHOS {
23namespace HiviewDFX {
24namespace {
25// defined in alltypes.h
26#define DFX_MUTEX_TYPE u.i[0]
27#define DFX_MUTEX_OWNER u.vi[1]
28typedef struct {
29    union {
30        int i[sizeof(long) == 8 ? 10 : 6];
31        volatile int vi[sizeof(long) == 8 ? 10 : 6];
32        volatile void *volatile p[sizeof(long) == 8 ? 5 : 6];
33    } u;
34} DfxMutex;
35}
36bool LockParser::ParseLockInfo(std::shared_ptr<Unwinder> unwinder, int32_t vmPid, int32_t tid)
37{
38#ifdef __aarch64__
39    std::vector<char> buffer(sizeof(pthread_mutex_t), 0);
40    if (unwinder->GetLockInfo(vmPid, buffer.data(), sizeof(pthread_mutex_t))) {
41        auto mutexInfo = reinterpret_cast<DfxMutex*>(buffer.data());
42        // only PTHREAD_MUTEX_ERRORCHECK(2) type lock contains lock holder thread-id
43        // the normal type only store EBUSY in owner section
44        int type = mutexInfo->DFX_MUTEX_TYPE;
45        int owner = mutexInfo->DFX_MUTEX_OWNER & 0x3fffffff;
46        DFXLOGI("Thread(%{public}d) is waiting a lock with type %d held by %d", tid, type, owner);
47        return true;
48    }
49    return false;
50#else
51    // not impl yet
52    return false;
53#endif
54}
55} // namespace HiviewDFX
56} // namespace OHOS
57