1 /*
2  * Copyright (C) 2022 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 "service_dump_manager.h"
17 #include <unistd.h>
18 #include <locale>
19 #include <codecvt>
20 #include "media_errors.h"
21 
22 namespace OHOS {
23 namespace Media {
GetInstance()24 ServiceDumpManager &ServiceDumpManager::GetInstance()
25 {
26     static ServiceDumpManager ServiceDumpManager;
27     return ServiceDumpManager;
28 }
29 
RegisterDfxDumper(std::u16string key,DfxDumper dump)30 void ServiceDumpManager::RegisterDfxDumper(std::u16string key, DfxDumper dump)
31 {
32     std::lock_guard<std::mutex> lock(mutex_);
33     dfxDumper_[key] = dump;
34 }
35 
UnregisterDfxDumper()36 void ServiceDumpManager::UnregisterDfxDumper()
37 {
38     std::lock_guard<std::mutex> lock(mutex_);
39     dfxDumper_.clear();
40 }
41 
Dump(int32_t fd,std::unordered_set<std::u16string> args)42 int32_t ServiceDumpManager::Dump(int32_t fd, std::unordered_set<std::u16string> args)
43 {
44     std::lock_guard<std::mutex> lock(mutex_);
45     std::string dumpString = "------------------MediaDfx------------------\n";
46     for (auto iter : dfxDumper_) {
47         if (args.find(static_cast<std::u16string>(iter.first)) != args.end()) {
48             dumpString += "-----";
49             dumpString += std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> {}.to_bytes(iter.first);
50             dumpString += "-----\n";
51             if (fd != -1) {
52                 write(fd, dumpString.c_str(), dumpString.size());
53                 dumpString.clear();
54             }
55             if (iter.second(fd) != MSERR_OK) {
56                 return MSERR_INVALID_OPERATION;
57             }
58         }
59     }
60     return MSERR_OK;
61 }
62 } // namespace Media
63 } // namespace OHOS