!19149 merge arg into master

delete argmapping

Created-by: wendel
Commit-by: wendel
Merged-by: openharmony_ci
Description: **IssueNo**:

**Description**:

**稳定性自检:**
| 自检项                                                       | 自检结果  |
| ------------------------------------------------------------ | -------- |
| 涉及跨进程调用的相关操作需要抛至主线程或加锁防止并发              |   pass       |
| 成员变量进行赋值或创建需要排查并发                               |     pass     |
| 谨慎在lambda表达式中使用引用捕获                                |    pass      |
| 谨慎在未经拷贝的情况下使用外部传入的string、C字符串               |      pass    |
| map\vector\list\set等stl模板类使用时需要排查并发                |   pass       |
| 谨慎考虑加锁范围                                               |   pass       |
| 在IPC通信中谨慎使用同步通信方式                                 |       pass   |
| 禁止传递this指针至其他模块或线程(特别是eventhandler任务)        |    pass      |
| 禁止将外部传入的裸指针在内部直接构造智能指针                      |      pass    |
| 禁止多个独立创建的智能指针管理同一地址                           |    pass      |
| 禁止在析构函数中抛异步任务                                      |   pass       |
| 禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁             |  pass        |
| 禁止在对外接口中未经判空直接使用外部传入的指针                    |  pass        |
| 禁止接口返回局部变量引用                                        |  pass        |
| 禁止在信号函数中加锁                                            |  pass        |
| 禁止在关键流程(SA启动、应用启动等主流程)执行耗时的操作           |pass          |
| 禁止将同一个cpp编译在不同的so中                                 |     pass    |

**安全编码自检:**
| 自检项                                                          | 自检结果 |
| -------------------------------------------------------------- | -------- |
| 裸指针避免通过隐式转换构造为sptr                                 | pass         |
| json对象在取值之前必须先判断类型,避免类型不匹配                   |     pass     |
| 序列化时必须对传入的数组大小进行校验,避免出现超大数组              |      pass    |
| 避免使用未明确位宽的整型,选择使用int8_t、uint8_t等类型            |     pass     |
| 外部传入的路径要做规范化校验,对路径中的.、..、../等特殊字符严格校验 |    pass      |
| 指针变量、表示资源描述符的变量、bool变量必须赋初值                  |   pass       |
| readParcelable获取的对象使用前需要判空                            |     pass     |
| 分配和释放内存的函数需要成对出现                                   |      pass    |
| 申请内存后异常退出前需要及时进行内存释放                            |     pass     |
| 内存申请前必须对内存大小进行合法性校验                              |      pass    |
| 内存分配后必须判断是否成功                                         |       pass   |
| 禁止使用realloc、alloca函数                                       |     pass     |
| 禁止打印文件路径、口令等敏感信息,如有需要,使用private修饰          |    pass      |
| 禁止打印内存地址                                                  |      pass    |
| 整数之间运算时必须严格检查,确保不会出现溢出、反转、除0               |     pass     |
| 禁止对有符号整数进行位操作符运算                                    |      pass    |
| 禁止对指针进行逻辑或位运算                                         | pass         |
| 循环次数如果收外部数据控制,需要检验其合法性                         |       pass   |
| 禁止使用内存操作类危险函数,需要使用安全函数                         |     pass     |
| 谨慎使用不可重入函数                                               |  pass        |
| 必须检查安全函数的返回值,并进行正确处理                             |     pass     |
| 禁止仅通过TokenType类型判断绕过权限校验                             |   pass       |

**TDD Result**:不涉及

**XTS Result**:不涉及

### 是否已执行L0用例
- [x] 已验证
- [ ] 不涉及。如不涉及,请写明理由

See merge request: openharmony/ability_ability_runtime!19149
This commit is contained in:
openharmony_ci
2026-04-29 19:16:21 +08:00
4 changed files with 17 additions and 905 deletions
@@ -52,9 +52,6 @@ public:
static void TransferToCmdParam(const ToolInfo &toolInfo, const AAFwk::WantParams &args, std::string &cmdLine);
// Path utilities (public for testing)
static std::vector<std::string> SplitPathBySeparator(const std::string &path, const std::string &separator);
private:
static bool GetBundleInfoByTokenId(AccessToken::AccessTokenID tokenId,
AppExecFwk::BundleInfo &bundleInfo);
@@ -63,12 +60,8 @@ private:
// Helper methods for type validation
static bool ValidateParamType(const sptr<AAFwk::IInterface> &value, const std::string &expectedType,
const nlohmann::json &propertySchema, const std::string &key = "");
static bool ValidateNestedObject(const AAFwk::WantParams &nestedParams,
const nlohmann::json &objectSchema, const std::string &parentKey);
static bool ValidateArrayType(const sptr<AAFwk::IInterface> &value,
const nlohmann::json &propertySchema, const std::string &key);
static bool ValidateObjectType(const sptr<AAFwk::IInterface> &value,
const nlohmann::json &propertySchema, const std::string &key);
static bool ValidateArrayItems(sptr<AAFwk::IArray> arrayObj,
const nlohmann::json &itemsSchema, const std::string &key);
static bool ValidateBasicType(const sptr<AAFwk::IInterface> &value, const std::string &expectedType);
@@ -77,77 +70,16 @@ private:
static bool IsIntegerType(const sptr<AAFwk::IInterface> &value);
static bool IsNumberType(const sptr<AAFwk::IInterface> &value);
static bool IsArrayType(const sptr<AAFwk::IInterface> &value);
static bool IsObjectType(const sptr<AAFwk::IInterface> &value);
// Helper methods for argument mapping
static void ApplyFlagMapping(const std::string &templates, const AAFwk::WantParams &args, std::string &cmdLine);
static void ApplyPositionalMapping(const std::string &order, const AAFwk::WantParams &args, std::string &cmdLine);
static void ApplyFlattenedMapping(const std::string &separator, const std::string &templates,
const AAFwk::WantParams &args, std::string &cmdLine);
static void ApplyJsonStringMapping(const std::string &templates, const AAFwk::WantParams &args,
std::string &cmdLine);
static std::string FormatTemplate(const std::string &tmpl, const std::string &value);
// Helper methods for mode processing (extracted to reduce nesting depth)
static void ProcessArrayExpansion(const sptr<AAFwk::IInterface> &value, const std::string &tmpl,
static void ProcessArrayExpansion(const std::string &key, const sptr<AAFwk::IInterface> &value,
std::string &cmdLine);
static void ProcessJsonStringTemplate(const std::string &key, const sptr<AAFwk::IInterface> &value,
const nlohmann::json &templateValue, std::string &cmdLine);
static void ProcessBooleanTemplate(const std::string &key, const sptr<AAFwk::IInterface> &value,
const nlohmann::json &templateValue, std::string &cmdLine);
static void ProcessFlattenedTemplate(const std::string &flattenedKey, const nlohmann::json &templateValue,
const std::string &separator, const AAFwk::WantParams &args, std::string &cmdLine);
// JSON conversion helper
static std::string ConvertValueToJson(const std::string &key, const sptr<AAFwk::IInterface> &value);
// Nested path query helper for flattened mapping
static sptr<AAFwk::IInterface> QueryNestedValue(const AAFwk::WantParams &args,
const std::string &path, const std::string &separator);
// Helper method for nested path traversal
static sptr<AAFwk::IInterface> QueryNestedPath(const AAFwk::WantParams &args,
const std::vector<std::string> &pathSegments, const std::string &separator);
static sptr<AAFwk::IInterface> QueryNextLevel(const sptr<AAFwk::IInterface> &currentValue,
const std::string &nextSegment, const std::string &separator);
// Helper methods for path query (extracted to reduce QueryNestedValue length)
static sptr<AAFwk::IInterface> TryDirectLookup(const AAFwk::WantParams &args,
const std::string &path);
static sptr<AAFwk::IInterface> TryNestedPathTraversal(const AAFwk::WantParams &args,
const std::string &path, const std::string &separator);
// WantParams to JSON conversion helper for nested objects
static std::string WantParamsToJson(const AAFwk::WantParams &wantParams);
// Core parameter processing logic (extracted for reuse)
static void ApplyFlagModeLogic(const sptr<AAFwk::IInterface> &value,
const nlohmann::json &templateValue, std::string &cmdLine);
// Type conversion helpers
// GetParamStringValue: only supports basic types (bool, int, long, float, double, string)
// GetParamArrayValue: supports single-level arrays with basic type elements
// GetParamJsonValue: converts to JSON format (supports single-level arrays)
// Note: Nested arrays and byte/char/short types are not supported
static std::string GetParamStringValue(const sptr<AAFwk::IInterface> &value);
static std::string GetParamJsonValue(const sptr<AAFwk::IInterface> &value);
static bool GetParamBoolValue(const sptr<AAFwk::IInterface> &value, bool &result);
static bool GetParamArrayValue(const sptr<AAFwk::IInterface> &value, std::vector<std::string> &result);
// Low-level helper methods for code reuse
static bool ExtractWantParams(const sptr<AAFwk::IInterface> &value, AAFwk::WantParams &wantParams);
static std::string EscapeJsonString(const std::string &str);
static void IterateIArray(sptr<AAFwk::IArray> arrayObj,
std::function<void(const sptr<AAFwk::IInterface>&)> elementHandler);
static std::string BuildJsonArrayFromIArray(sptr<AAFwk::IArray> arrayObj,
std::function<std::string(const sptr<AAFwk::IInterface>&)> elementConverter);
// Type-specific JSON conversion helpers (extracted to reduce GetParamJsonValue length)
static std::string ConvertWantParamsToJson(const sptr<AAFwk::IInterface> &value);
static std::string ConvertArrayToJson(const sptr<AAFwk::IInterface> &value);
static std::string ConvertStringToJson(const sptr<AAFwk::IInterface> &value);
static std::string ConvertBooleanToJson(const sptr<AAFwk::IInterface> &value);
static std::string ConvertNumericToJson(const sptr<AAFwk::IInterface> &value);
};
} // namespace CliTool
@@ -162,6 +162,7 @@ bool ToolUtil::GenerateSandboxConfig(const std::string &challenge, AccessToken::
config["callerPid"] = IPCSkeleton::GetCallingPid();
config["gid"] = bundleInfo.gid;
config["appId"] = bundleInfo.appId;
config["bundleName"] = bundleInfo.name;
sandboxConfig = config.dump();
bundleName = bundleInfo.name;
TAG_LOGE(AAFwkTag::CLI_TOOL, "sandboxConfig: %{public}s", sandboxConfig.c_str());
@@ -209,208 +210,31 @@ void ToolUtil::TransferToCmdParam(const ToolInfo &toolInfo, const AAFwk::WantPar
TAG_LOGI(AAFwkTag::CLI_TOOL, "Not has arg");
return;
}
if (toolInfo.argMapping == nullptr) {
TAG_LOGW(AAFwkTag::CLI_TOOL, "argMapping is nullptr");
return;
}
// Apply mapping based on type
switch (toolInfo.argMapping->type) {
case ArgMappingType::FLAG:
ApplyFlagMapping(toolInfo.argMapping->templates, args, cmdLine);
break;
case ArgMappingType::POSITIONAL:
ApplyPositionalMapping(toolInfo.argMapping->order, args, cmdLine);
break;
case ArgMappingType::FLATTENED:
ApplyFlattenedMapping(toolInfo.argMapping->separator, toolInfo.argMapping->templates, args, cmdLine);
break;
case ArgMappingType::JSONSTRING:
ApplyJsonStringMapping(toolInfo.argMapping->templates, args, cmdLine);
break;
default:
TAG_LOGW(AAFwkTag::CLI_TOOL, "Unknown argMapping type");
break;
}
}
void ToolUtil::ApplyFlagMapping(const std::string &templates, const AAFwk::WantParams &args, std::string &cmdLine)
{
if (templates.empty()) {
TAG_LOGW(AAFwkTag::CLI_TOOL, "Flag templates is empty");
return;
}
nlohmann::json templatesJson = nlohmann::json::parse(templates, nullptr, false);
if (templatesJson.is_discarded() || !templatesJson.is_object()) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Failed to parse templates JSON");
return;
}
for (const auto &[key, value] : args.GetParams()) {
if (!templatesJson.contains(key)) {
if (value == nullptr) {
continue;
}
auto &templateValue = templatesJson[key];
// Apply FLAG mode logic for this parameter
ApplyFlagModeLogic(value, templateValue, cmdLine);
}
}
void ToolUtil::ApplyPositionalMapping(const std::string &order, const AAFwk::WantParams &args, std::string &cmdLine)
{
if (order.empty()) {
TAG_LOGW(AAFwkTag::CLI_TOOL, "Positional order is empty");
return;
}
nlohmann::json orderJson = nlohmann::json::parse(order, nullptr, false);
if (orderJson.is_discarded() || !orderJson.is_array()) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Failed to parse order JSON");
return;
}
for (const auto &key : orderJson) {
if (!key.is_string()) {
continue;
}
std::string keyStr = key.get<std::string>();
auto it = args.GetParams().find(keyStr);
if (it != args.GetParams().end()) {
std::string strValue = GetParamStringValue(it->second);
if (!strValue.empty()) {
cmdLine += " " + strValue;
if (IsBooleanType(value)) {
bool boolValue = false;
if (GetParamBoolValue(value, boolValue) && boolValue) {
cmdLine += " --" + key;
}
}
}
}
void ToolUtil::ApplyFlattenedMapping(const std::string &separator, const std::string &templates,
const AAFwk::WantParams &args, std::string &cmdLine)
{
std::string sep = separator.empty() ? "." : separator;
nlohmann::json templatesJson = nlohmann::json::parse(templates, nullptr, false);
if (templatesJson.is_discarded() || !templatesJson.is_object()) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Failed to parse templates JSON");
return;
}
// Process each template key (which contains the flattened path)
for (const auto &templateIt : templatesJson.items()) {
const std::string &flattenedKey = templateIt.key();
const auto &templateValue = templateIt.value();
// Query nested value and process in one step to reduce depth
ProcessFlattenedTemplate(flattenedKey, templateValue, sep, args, cmdLine);
}
}
void ToolUtil::ApplyJsonStringMapping(const std::string &templates, const AAFwk::WantParams &args, std::string &cmdLine)
{
nlohmann::json templatesJson = nlohmann::json::parse(templates, nullptr, false);
if (templatesJson.is_discarded() || !templatesJson.is_object()) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Failed to parse templates JSON");
return;
}
for (const auto &[key, value] : args.GetParams()) {
if (!templatesJson.contains(key)) {
continue;
}
auto &templateValue = templatesJson[key];
if (IsArrayType(value)) {
ProcessArrayExpansion(key, value, cmdLine);
continue;
}
if (templateValue.is_string()) {
ProcessJsonStringTemplate(key, value, templateValue, cmdLine);
} else if (templateValue.is_object()) {
ProcessBooleanTemplate(key, value, templateValue, cmdLine);
std::string strValue = GetParamStringValue(value);
if (!strValue.empty()) {
cmdLine += " --" + key + " " + strValue;
}
}
}
std::string ToolUtil::FormatTemplate(const std::string &tmpl, const std::string &value)
{
std::string result = tmpl;
size_t pos = result.find("{value}");
constexpr int32_t valueSize = 7;
if (pos != std::string::npos) {
result.replace(pos, valueSize, value);
}
pos = result.find("{json}");
constexpr int32_t jsonSize = 6;
if (pos != std::string::npos) {
result.replace(pos, jsonSize, value);
}
return result;
}
sptr<AAFwk::IInterface> ToolUtil::QueryNestedValue(const AAFwk::WantParams &args,
const std::string &path, const std::string &separator)
{
if (path.empty()) {
return nullptr;
}
// Try direct lookup first
sptr<AAFwk::IInterface> result = TryDirectLookup(args, path);
if (result != nullptr) {
return result;
}
// Try nested path traversal
std::string sep = separator.empty() ? "." : separator;
return TryNestedPathTraversal(args, path, sep);
}
sptr<AAFwk::IInterface> ToolUtil::TryDirectLookup(const AAFwk::WantParams &args,
const std::string &path)
{
auto &params = args.GetParams();
auto it = params.find(path);
if (it != params.end()) {
TAG_LOGI(AAFwkTag::CLI_TOOL, "Found param with direct lookup: %{public}s", path.c_str());
return it->second;
}
return nullptr;
}
sptr<AAFwk::IInterface> ToolUtil::TryNestedPathTraversal(const AAFwk::WantParams &args,
const std::string &path, const std::string &separator)
{
std::vector<std::string> pathSegments = SplitPathBySeparator(path, separator);
constexpr int32_t segmentSize = 2;
if (pathSegments.size() < segmentSize) {
return nullptr;
}
return QueryNestedPath(args, pathSegments, separator);
}
std::string ToolUtil::WantParamsToJson(const AAFwk::WantParams &wantParams)
{
nlohmann::json result = nlohmann::json::object();
for (const auto &[key, value] : wantParams.GetParams()) {
// Check if value is another WantParams (nested object)
AAFwk::WantParams nestedWantParams;
if (ExtractWantParams(value, nestedWantParams)) {
// Recursively convert nested WantParams to JSON
result[key] = nlohmann::json::parse(WantParamsToJson(nestedWantParams), nullptr, false);
} else if (value != nullptr) {
// Convert IInterface to JSON value using GetParamJsonValue
std::string valueJsonStr = GetParamJsonValue(value);
nlohmann::json valueJson = nlohmann::json::parse(valueJsonStr, nullptr, false);
if (!valueJson.is_discarded()) {
result[key] = valueJson;
}
}
}
return result.dump();
}
std::string ToolUtil::GetParamStringValue(const sptr<AAFwk::IInterface> &value)
{
if (value == nullptr) {
@@ -475,130 +299,6 @@ std::string ToolUtil::GetParamStringValue(const sptr<AAFwk::IInterface> &value)
return "";
}
std::string ToolUtil::GetParamJsonValue(const sptr<AAFwk::IInterface> &value)
{
if (value == nullptr) {
return "null";
}
// Try WantParams (nested object) - should check before other types
std::string jsonStr = ConvertWantParamsToJson(value);
if (!jsonStr.empty()) {
return jsonStr;
}
// Try Array - only single-level array support (no nested arrays)
jsonStr = ConvertArrayToJson(value);
if (!jsonStr.empty()) {
return jsonStr;
}
// Try String - JSON strings are quoted
jsonStr = ConvertStringToJson(value);
if (!jsonStr.empty()) {
return jsonStr;
}
// Try Boolean - JSON booleans are unquoted
jsonStr = ConvertBooleanToJson(value);
if (!jsonStr.empty()) {
return jsonStr;
}
// Try Numeric types (int, long, float, double)
jsonStr = ConvertNumericToJson(value);
if (!jsonStr.empty()) {
return jsonStr;
}
// If no type matches, return null
return "null";
}
std::string ToolUtil::ConvertWantParamsToJson(const sptr<AAFwk::IInterface> &value)
{
AAFwk::WantParams wantParams;
if (ExtractWantParams(value, wantParams)) {
return WantParamsToJson(wantParams);
}
return "";
}
std::string ToolUtil::ConvertArrayToJson(const sptr<AAFwk::IInterface> &value)
{
if (auto arrayObj = AAFwk::IArray::Query(value)) {
return BuildJsonArrayFromIArray(arrayObj, [](const sptr<AAFwk::IInterface>& element) {
return GetParamJsonValue(element);
});
}
return "";
}
std::string ToolUtil::ConvertStringToJson(const sptr<AAFwk::IInterface> &value)
{
if (auto strObj = AAFwk::IString::Query(value)) {
std::string strValue;
if (strObj->GetString(strValue) != ERR_OK) {
return "\"\"";
}
return "\"" + EscapeJsonString(strValue) + "\"";
}
return "";
}
std::string ToolUtil::ConvertBooleanToJson(const sptr<AAFwk::IInterface> &value)
{
if (auto boolObj = AAFwk::IBoolean::Query(value)) {
bool boolValue = false;
if (boolObj->GetValue(boolValue) == ERR_OK) {
return boolValue ? "true" : "false";
}
return "false";
}
return "";
}
std::string ToolUtil::ConvertNumericToJson(const sptr<AAFwk::IInterface> &value)
{
// Try Integer/Int
if (auto intObj = AAFwk::IInteger::Query(value)) {
int intValue = 0;
if (intObj->GetValue(intValue) == ERR_OK) {
return std::to_string(intValue);
}
return "0";
}
// Try Long
if (auto longObj = AAFwk::ILong::Query(value)) {
long longValue = 0;
if (longObj->GetValue(longValue) == ERR_OK) {
return std::to_string(longValue);
}
return "0";
}
// Try Float
if (auto floatObj = AAFwk::IFloat::Query(value)) {
float floatValue = 0.0f;
if (floatObj->GetValue(floatValue) == ERR_OK) {
return std::to_string(floatValue);
}
return "0.0";
}
// Try Double
if (auto doubleObj = AAFwk::IDouble::Query(value)) {
double doubleValue = 0.0;
if (doubleObj->GetValue(doubleValue) == ERR_OK) {
return std::to_string(doubleValue);
}
return "0.0";
}
return "";
}
bool ToolUtil::GetParamBoolValue(const sptr<AAFwk::IInterface> &value, bool &result)
{
if (value == nullptr) {
@@ -616,249 +316,7 @@ bool ToolUtil::GetParamBoolValue(const sptr<AAFwk::IInterface> &value, bool &res
return false;
}
bool ToolUtil::GetParamArrayValue(const sptr<AAFwk::IInterface> &value, std::vector<std::string> &result)
{
if (value == nullptr) {
return false;
}
// Try to query as IArray
auto arrayValue = AAFwk::IArray::Query(value);
if (arrayValue == nullptr) {
return false;
}
bool foundAny = false;
IterateIArray(arrayValue, [&result, &foundAny](const sptr<AAFwk::IInterface>& element) {
std::string elementStr = GetParamStringValue(element);
if (!elementStr.empty()) {
result.push_back(elementStr);
foundAny = true;
}
});
return foundAny;
}
// ============================================================================
// Helper methods for code reuse
// ============================================================================
bool ToolUtil::ExtractWantParams(const sptr<AAFwk::IInterface> &value, AAFwk::WantParams &wantParams)
{
if (value == nullptr) {
return false;
}
auto wantParamsWrapper = AAFwk::IWantParams::Query(value);
if (wantParamsWrapper == nullptr) {
return false;
}
return wantParamsWrapper->GetValue(wantParams) == ERR_OK;
}
std::string ToolUtil::EscapeJsonString(const std::string &str)
{
std::string escaped = "";
for (char c : str) {
if (c == '"') {
escaped += "\\\"";
} else if (c == '\\') {
escaped += "\\\\";
} else if (c == '\n') {
escaped += "\\n";
} else if (c == '\r') {
escaped += "\\r";
} else if (c == '\t') {
escaped += "\\t";
} else {
escaped += c;
}
}
return escaped;
}
void ToolUtil::IterateIArray(sptr<AAFwk::IArray> arrayObj,
std::function<void(const sptr<AAFwk::IInterface>&)> elementHandler)
{
if (arrayObj == nullptr) {
return;
}
long arrayLength = 0;
if (arrayObj->GetLength(arrayLength) != ERR_OK || arrayLength <= 0) {
return;
}
for (long i = 0; i < arrayLength; ++i) {
sptr<AAFwk::IInterface> elementValue;
if (arrayObj->Get(i, elementValue) != ERR_OK || elementValue == nullptr) {
continue;
}
// Skip nested arrays
if (AAFwk::IArray::Query(elementValue) != nullptr) {
continue;
}
elementHandler(elementValue);
}
}
std::string ToolUtil::BuildJsonArrayFromIArray(sptr<AAFwk::IArray> arrayObj,
std::function<std::string(const sptr<AAFwk::IInterface>&)> elementConverter)
{
if (arrayObj == nullptr) {
return "[]";
}
long arrayLength = 0;
if (arrayObj->GetLength(arrayLength) != ERR_OK || arrayLength <= 0) {
return "[]";
}
std::string result = "[";
bool firstElement = true;
IterateIArray(arrayObj, [&result, &firstElement, &elementConverter](const sptr<AAFwk::IInterface>& element) {
if (!firstElement) {
result += ",";
}
result += elementConverter(element);
firstElement = false;
});
result += "]";
return result;
}
// ============================================================================
// Core FLAG mode logic (extracted for reuse)
// ============================================================================
void ToolUtil::ApplyFlagModeLogic(const sptr<AAFwk::IInterface> &value,
const nlohmann::json &templateValue, std::string &cmdLine)
{
if (value == nullptr) {
return;
}
// Handle string template
if (templateValue.is_string()) {
std::string strValue = GetParamStringValue(value);
if (!strValue.empty()) {
std::string tmpl = templateValue.get<std::string>();
std::string formatted = FormatTemplate(tmpl, strValue);
cmdLine += " " + formatted;
}
return;
}
// Handle boolean template with if_true/if_false
if (templateValue.is_object()) {
bool boolValue = false;
if (GetParamBoolValue(value, boolValue)) {
std::string flag = "";
if (boolValue && templateValue.contains("if_true")) {
flag = templateValue["if_true"].get<std::string>();
} else if (!boolValue && templateValue.contains("if_false")) {
flag = templateValue["if_false"].get<std::string>();
}
if (!flag.empty()) {
cmdLine += " " + flag;
}
}
return;
}
// Handle array type - expand to multiple arguments
if (!templateValue.is_string()) {
return;
}
std::string tmpl = templateValue.get<std::string>();
ProcessArrayExpansion(value, tmpl, cmdLine);
}
void ToolUtil::ProcessJsonStringTemplate(const std::string &key, const sptr<AAFwk::IInterface> &value,
const nlohmann::json &templateValue, std::string &cmdLine)
{
if (value == nullptr) {
TAG_LOGW(AAFwkTag::CLI_TOOL, "Param '%{public}s' value is null", key.c_str());
return;
}
std::string tmpl = templateValue.get<std::string>();
std::string jsonStr = ConvertValueToJson(key, value);
// Apply template with JSON string
std::string formatted = FormatTemplate(tmpl, jsonStr);
cmdLine += " " + formatted;
}
void ToolUtil::ProcessBooleanTemplate(const std::string &key, const sptr<AAFwk::IInterface> &value,
const nlohmann::json &templateValue, std::string &cmdLine)
{
bool boolValue = false;
if (!GetParamBoolValue(value, boolValue)) {
return;
}
std::string flag = "";
if (boolValue && templateValue.contains("if_true")) {
flag = templateValue["if_true"].get<std::string>();
} else if (!boolValue && templateValue.contains("if_false")) {
flag = templateValue["if_false"].get<std::string>();
}
if (!flag.empty()) {
cmdLine += " " + flag;
}
}
std::string ToolUtil::ConvertValueToJson(const std::string &key, const sptr<AAFwk::IInterface> &value)
{
// Check if value is a WantParams (nested object)
AAFwk::WantParams nestedWantParams;
if (ExtractWantParams(value, nestedWantParams)) {
// Recursively convert nested WantParams to JSON
std::string jsonStr = WantParamsToJson(nestedWantParams);
TAG_LOGI(AAFwkTag::CLI_TOOL, "Param '%{public}s' is nested WantParams, converted to: %{public}s",
key.c_str(), jsonStr.c_str());
return jsonStr;
}
// Convert IInterface to JSON string
std::string jsonStr = GetParamJsonValue(value);
TAG_LOGI(AAFwkTag::CLI_TOOL, "Param '%{public}s' converted to JSON: %{public}s",
key.c_str(), jsonStr.c_str());
return jsonStr;
}
void ToolUtil::ProcessFlattenedTemplate(const std::string &flattenedKey, const nlohmann::json &templateValue,
const std::string &separator, const AAFwk::WantParams &args, std::string &cmdLine)
{
// Query nested value - simplifed version
sptr<AAFwk::IInterface> value = QueryNestedValue(args, flattenedKey, separator);
if (value == nullptr) {
return;
}
// Process template based on type
if (templateValue.is_string()) {
std::string strValue = GetParamStringValue(value);
if (!strValue.empty()) {
std::string formatted = FormatTemplate(templateValue.get<std::string>(), strValue);
cmdLine += " " + formatted;
}
} else if (templateValue.is_object()) {
ProcessBooleanTemplate(flattenedKey, value, templateValue, cmdLine);
}
}
void ToolUtil::ProcessArrayExpansion(const sptr<AAFwk::IInterface> &value, const std::string &tmpl,
void ToolUtil::ProcessArrayExpansion(const std::string &key, const sptr<AAFwk::IInterface> &value,
std::string &cmdLine)
{
auto arrayValue = AAFwk::IArray::Query(value);
@@ -885,88 +343,11 @@ void ToolUtil::ProcessArrayExpansion(const sptr<AAFwk::IInterface> &value, const
std::string elementStr = GetParamStringValue(elementValue);
if (!elementStr.empty()) {
std::string formatted = FormatTemplate(tmpl, elementStr);
cmdLine += " " + formatted;
cmdLine += " --" + key + " " + elementStr;
}
}
}
std::vector<std::string> ToolUtil::SplitPathBySeparator(const std::string &path, const std::string &separator)
{
std::vector<std::string> pathSegments;
if (path.empty()) {
return pathSegments;
}
std::string sep = separator.empty() ? "." : separator;
size_t start = 0;
size_t end = path.find(sep);
while (end != std::string::npos) {
std::string segment = path.substr(start, end - start);
if (!segment.empty()) {
pathSegments.push_back(segment);
}
start = end + sep.length();
end = path.find(sep, start);
}
std::string lastSegment = path.substr(start);
if (!lastSegment.empty()) {
pathSegments.push_back(lastSegment);
}
return pathSegments;
}
sptr<AAFwk::IInterface> ToolUtil::QueryNestedPath(const AAFwk::WantParams &args,
const std::vector<std::string> &pathSegments, const std::string &separator)
{
auto &params = args.GetParams();
// First level: query from args
auto firstIt = params.find(pathSegments[0]);
if (firstIt == params.end()) {
TAG_LOGI(AAFwkTag::CLI_TOOL, "First level key not found: %{public}s", pathSegments[0].c_str());
return nullptr;
}
sptr<AAFwk::IInterface> currentValue = firstIt->second;
// Nested levels: traverse through WantParams
for (size_t i = 1; i < pathSegments.size(); ++i) {
currentValue = QueryNextLevel(currentValue, pathSegments[i], separator);
if (currentValue == nullptr) {
TAG_LOGI(AAFwkTag::CLI_TOOL, "Nested key not found: %{public}s", pathSegments[i].c_str());
return nullptr;
}
}
TAG_LOGI(AAFwkTag::CLI_TOOL, "Found param with nested traversal: %{public}s",
pathSegments.size() > 1 ? pathSegments[0].c_str() : "N/A");
return currentValue;
}
sptr<AAFwk::IInterface> ToolUtil::QueryNextLevel(const sptr<AAFwk::IInterface> &currentValue,
const std::string &nextSegment, const std::string &separator)
{
if (currentValue == nullptr) {
return nullptr;
}
AAFwk::WantParams nestedParams;
if (!ExtractWantParams(currentValue, nestedParams)) {
return nullptr;
}
auto &nestedMap = nestedParams.GetParams();
auto nestedIt = nestedMap.find(nextSegment);
if (nestedIt == nestedMap.end()) {
return nullptr;
}
return nestedIt->second;
}
// ============================================================================
// Type validation helpers for ValidateInputSchemaProperties
// ============================================================================
@@ -981,9 +362,6 @@ bool ToolUtil::ValidateParamType(const sptr<AAFwk::IInterface> &value, const std
if (expectedType == "array") {
return ValidateArrayType(value, propertySchema, key);
}
if (expectedType == "object") {
return ValidateObjectType(value, propertySchema, key);
}
return ValidateBasicType(value, expectedType);
}
@@ -1021,19 +399,6 @@ bool ToolUtil::ValidateArrayType(const sptr<AAFwk::IInterface> &value,
return ValidateArrayItems(arrayObj, propertySchema["items"], key);
}
bool ToolUtil::ValidateObjectType(const sptr<AAFwk::IInterface> &value,
const nlohmann::json &propertySchema, const std::string &key)
{
if (!IsObjectType(value)) {
return false;
}
AAFwk::WantParams nestedParams;
if (!ExtractWantParams(value, nestedParams)) {
return false;
}
return ValidateNestedObject(nestedParams, propertySchema, key);
}
bool ToolUtil::ValidateArrayItems(sptr<AAFwk::IArray> arrayObj,
const nlohmann::json &itemsSchema, const std::string &key)
{
@@ -1060,47 +425,6 @@ bool ToolUtil::ValidateArrayItems(sptr<AAFwk::IArray> arrayObj,
return true;
}
bool ToolUtil::ValidateNestedObject(const AAFwk::WantParams &nestedParams,
const nlohmann::json &objectSchema, const std::string &parentKey)
{
if (!objectSchema.contains("properties") || !objectSchema["properties"].is_object()) {
TAG_LOGI(AAFwkTag::CLI_TOOL, "No nested properties defined for '%{public}s', skipping validation",
parentKey.c_str());
return true;
}
auto nestedProperties = objectSchema["properties"];
if (objectSchema.contains("required") && objectSchema["required"].is_array()) {
for (const auto &requiredProp : objectSchema["required"]) {
if (!requiredProp.is_string()) {
continue;
}
std::string requiredKey = requiredProp.get<std::string>();
std::string fullKey = parentKey + "." + requiredKey;
if (nestedParams.GetParams().find(requiredKey) == nestedParams.GetParams().end()) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Required nested property '%{public}s' not found", fullKey.c_str());
return false;
}
}
}
for (const auto &[nestedKey, nestedValue] : nestedParams.GetParams()) {
std::string fullKey = parentKey + "." + nestedKey;
if (!nestedProperties.contains(nestedKey)) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Nested property '%{public}s' not found in schema", fullKey.c_str());
return false;
}
auto &nestedPropertySchema = nestedProperties[nestedKey];
if (nestedPropertySchema.contains("type")) {
std::string expectedType = nestedPropertySchema["type"].get<std::string>();
if (!ValidateParamType(nestedValue, expectedType, nestedPropertySchema, fullKey)) {
TAG_LOGE(AAFwkTag::CLI_TOOL, "Nested property '%{public}s' type mismatch, expected: %{public}s",
fullKey.c_str(), expectedType.c_str());
return false;
}
}
}
return true;
}
bool ToolUtil::IsStringType(const sptr<AAFwk::IInterface> &value)
{
return AAFwk::IString::Query(value) != nullptr;
@@ -1129,11 +453,5 @@ bool ToolUtil::IsArrayType(const sptr<AAFwk::IInterface> &value)
return AAFwk::IArray::Query(value) != nullptr;
}
bool ToolUtil::IsObjectType(const sptr<AAFwk::IInterface> &value)
{
AAFwk::WantParams wantParams;
return ExtractWantParams(value, wantParams);
}
} // namespace CliTool
} // namespace OHOS
+1 -1
View File
@@ -87,6 +87,7 @@ enum class AAFwkLogTag : uint32_t {
AUTOFILLMGR,
EXTMGR,
SER_ROUTER,
CLI_TOOL = SER_ROUTER,
AUTO_STARTUP,
STARTUP,
RECOVERY,
@@ -102,7 +103,6 @@ enum class AAFwkLogTag : uint32_t {
APP_SERVICE_EXT,
VERTICAL_PANEL,
USER_CONTROLLER,
CLI_TOOL,
END = 256, // N.B. never use it
};
@@ -1080,143 +1080,5 @@ HWTEST_F(ToolUtilTest, ValidateInputSchemaProperties_ArrayItems_0200, TestSize.L
GTEST_LOG_(INFO) << "ToolUtil_ValidateInputSchemaProperties_ArrayItems_0200 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0100
* @tc.desc: Test SplitPathBySeparator with normal path
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0100, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0100 start";
std::string path = "app.config.name";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, ".");
EXPECT_EQ(result.size(), 3UL);
EXPECT_EQ(result[0], "app");
EXPECT_EQ(result[1], "config");
EXPECT_EQ(result[2], "name");
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0100 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0200
* @tc.desc: Test SplitPathBySeparator with trailing separator
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0200, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0200 start";
std::string path = "app.config.name.";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, ".");
// Should filter out empty segment
EXPECT_EQ(result.size(), 3UL);
EXPECT_EQ(result[0], "app");
EXPECT_EQ(result[1], "config");
EXPECT_EQ(result[2], "name");
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0200 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0300
* @tc.desc: Test SplitPathBySeparator with leading separator
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0300, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0300 start";
std::string path = ".app.config.name";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, ".");
// Should filter out empty segment
EXPECT_EQ(result.size(), 3UL);
EXPECT_EQ(result[0], "app");
EXPECT_EQ(result[1], "config");
EXPECT_EQ(result[2], "name");
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0300 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0400
* @tc.desc: Test SplitPathBySeparator with multiple consecutive separators
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0400, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0400 start";
std::string path = "app..config...name";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, ".");
// Should filter out all empty segments
EXPECT_EQ(result.size(), 3UL);
EXPECT_EQ(result[0], "app");
EXPECT_EQ(result[1], "config");
EXPECT_EQ(result[2], "name");
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0400 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0500
* @tc.desc: Test SplitPathBySeparator with empty string
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0500, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0500 start";
std::string path = "";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, ".");
EXPECT_EQ(result.size(), 0UL);
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0500 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0600
* @tc.desc: Test SplitPathBySeparator with single segment
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0600, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0600 start";
std::string path = "app";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, ".");
EXPECT_EQ(result.size(), 1UL);
EXPECT_EQ(result[0], "app");
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0600 end";
}
/**
* @tc.name: ToolUtil_SplitPathBySeparator_0700
* @tc.desc: Test SplitPathBySeparator with custom separator
* @tc.type: FUNC
*/
HWTEST_F(ToolUtilTest, SplitPathBySeparator_0700, TestSize.Level1)
{
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0700 start";
std::string path = "app-config-name";
std::vector<std::string> result = ToolUtil::SplitPathBySeparator(path, "-");
EXPECT_EQ(result.size(), 3UL);
EXPECT_EQ(result[0], "app");
EXPECT_EQ(result[1], "config");
EXPECT_EQ(result[2], "name");
GTEST_LOG_(INFO) << "ToolUtil_SplitPathBySeparator_0700 end";
}
} // namespace CliTool
} // namespace OHOS