1 /* 2 * Copyright (c) 2020 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 #ifndef OHOS_UTILS_H 17 #define OHOS_UTILS_H 18 19 #include "adapter.h" 20 #include "securec.h" 21 #include "stdint.h" 22 23 namespace OHOS { 24 const uint32_t MAX_STR_SIZE = 4096; 25 26 struct Utils { StrdupUtils27 static char *Strdup(const char *src) 28 { 29 if (src == nullptr) { 30 return nullptr; 31 } 32 33 size_t len = strlen(src); 34 if (len > MAX_STR_SIZE) { 35 return nullptr; 36 } 37 char *dst = reinterpret_cast<char *>(AdapterMalloc(len + 1)); 38 if (dst == nullptr) { 39 return nullptr; 40 } 41 errno_t err = strncpy_s(dst, len + 1, src, len); 42 if (err != EOK) { 43 AdapterFree(dst); 44 return nullptr; 45 } 46 return dst; 47 } 48 MemdupUtils49 static void *Memdup(const void *src, uint32_t len) 50 { 51 if ((src == nullptr) || (len == 0) || (len > MAX_STR_SIZE)) { 52 return nullptr; 53 } 54 55 void *dst = AdapterMalloc(len); 56 if (dst == nullptr) { 57 return nullptr; 58 } 59 60 int ret = memcpy_s(dst, len, src, len); 61 if (ret != 0) { 62 AdapterFree(dst); 63 return nullptr; 64 } 65 66 return dst; 67 } 68 }; // Utils 69 } // OHOS 70 71 #endif // OHOS_UTILS_H 72