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 "parameter.h" 17 #include "param_wrapper.h" 18 #include "sysparam_errno.h" 19 #include "system_parameter_ffi.h" 20 21 namespace OHOS { 22 namespace Parameter { 23 24 const int PARA_FAILURE = -1; 25 const int PARA_SUCCESS = 0; 26 static constexpr int MAX_VALUE_LENGTH = PARAM_CONST_VALUE_LEN_MAX; 27 28 extern "C" { MallocCString(const char * origin)29 char* MallocCString(const char* origin) 30 { 31 if (origin == nullptr) { 32 return nullptr; 33 } 34 auto len = strlen(origin) + 1; 35 char* res = static_cast<char*>(malloc(sizeof(char) * len)); 36 if (res == nullptr) { 37 return nullptr; 38 } 39 return std::char_traits<char>::copy(res, origin, len); 40 } 41 GetErrorInfo(int status)42 static int GetErrorInfo(int status) 43 { 44 switch (status) { 45 case EC_FAILURE: 46 case EC_SYSTEM_ERR: 47 case SYSPARAM_SYSTEM_ERROR: 48 return -SYSPARAM_SYSTEM_ERROR; 49 case EC_INVALID: 50 case SYSPARAM_INVALID_INPUT: 51 return -SYSPARAM_INVALID_INPUT; 52 case SYSPARAM_PERMISSION_DENIED: 53 return -SYSPARAM_PERMISSION_DENIED; 54 case SYSPARAM_NOT_FOUND: 55 return -SYSPARAM_NOT_FOUND; 56 case SYSPARAM_INVALID_VALUE: 57 return -SYSPARAM_INVALID_VALUE; 58 default: 59 return -SYSPARAM_SYSTEM_ERROR; 60 } 61 return 0; 62 } 63 FfiOHOSSysTemParameterGet(const char * key,const char * def)64 RetDataCString FfiOHOSSysTemParameterGet(const char* key, const char* def) 65 { 66 RetDataCString ret = {.code = PARA_FAILURE, .data = nullptr}; 67 std::vector<char> value(MAX_VALUE_LENGTH, 0); 68 int status = GetParameter(key, (strlen(def) == 0) ? nullptr : def, value.data(), MAX_VALUE_LENGTH); 69 if (status < PARA_SUCCESS) { 70 ret.code = GetErrorInfo(status); 71 } else { 72 ret.code = PARA_SUCCESS; 73 ret.data = MallocCString(value.data()); 74 } 75 return ret; 76 } 77 FfiOHOSSysTemParameterSet(const char * key,const char * value)78 int32_t FfiOHOSSysTemParameterSet(const char* key, const char* value) 79 { 80 int32_t ret = SetParameter(key, value); 81 if (ret != 0) { 82 return GetErrorInfo(ret); 83 } 84 return ret; 85 } 86 } 87 } 88 }