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 "process_group_util.h"
17 #include <sstream>
18 #include <string>
19 #include <fstream>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 #include <linux/limits.h>
24 #include "nlohmann/json.hpp"
25 #include "securec.h"
26 #include "res_common_util.h"
27 #include "res_exe_type.h"
28 #include "res_sched_exe_client.h"
29
30 namespace OHOS {
31 namespace ResourceSchedule {
32 namespace CgroupSetting {
33 namespace {
34 static constexpr int FMT_STR_BUFF_LEN = 256;
35 }
36
37 constexpr uint64_t SCHEDULE_CGROUP_FDSAN_TAG = 0xd001702;
38 constexpr uint64_t COMMON_CGROUP_FDSAN_TAG = 0;
39
FormatString(const char * fmt,va_list vararg)40 std::string FormatString(const char* fmt, va_list vararg)
41 {
42 std::string strResult;
43 if (fmt) {
44 char buffer[FMT_STR_BUFF_LEN] = { 0 };
45 int nWritten = vsnprintf_s(buffer, FMT_STR_BUFF_LEN, FMT_STR_BUFF_LEN - 1, fmt, vararg);
46 if (nWritten > 0) {
47 strResult.append(buffer, 0, nWritten);
48 }
49 }
50 return strResult;
51 }
52
StringPrintf(const char * fmt,...)53 std::string StringPrintf(const char* fmt, ...)
54 {
55 va_list vararg;
56 va_start(vararg, fmt);
57 std::string result = FormatString(fmt, vararg);
58 va_end(vararg);
59 return result;
60 }
61
ReadFileToStringForVFSFromExecutor(int tid,std::string & content)62 bool ReadFileToStringForVFSFromExecutor(int tid, std::string& content)
63 {
64 nlohmann::json payload;
65 payload["pid"] = tid;
66 nlohmann::json reply;
67 ResourceSchedule::ResSchedExeClient::GetInstance().SendRequestSync(
68 ResExeType::RES_TYPE_CGROUP_SYNC_EVENT, 0, payload, reply);
69 std::string resStr{"res"};
70 if (!reply.contains(resStr) || !reply[resStr].is_string()) {
71 return false;
72 }
73 content = reply[resStr].get<std::string>();
74 return true;
75 }
76
ReadFileToStringForVFS(const std::string & filePath,std::string & content)77 bool ReadFileToStringForVFS(const std::string& filePath, std::string& content)
78 {
79 std::string realPath;
80 if (!ResCommonUtil::GetRealPath(filePath, realPath)) {
81 return false;
82 }
83 std::ifstream fin(realPath.c_str(), std::ios::in);
84 if (!fin) {
85 return false;
86 }
87 std::stringstream ss;
88 ss << fin.rdbuf();
89 content = ss.str();
90 fin.close();
91 return true;
92 }
93 } // namespace CgroupSetting
94 } // namespace ResourceSchedule
95 } // namespace OHOS
96