1 /*
2 * Copyright (c) 2021 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 "hcs_blob_load.h"
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include "hcs_blob_if.h"
20 #include "hdf_log.h"
21 #include "osal_mem.h"
22
23 #define HDF_LOG_TAG hcs_blob_load
24 #define HBC_FILE_EXT ".hcb"
25
IsHcbFile(const char * fname)26 static bool IsHcbFile(const char *fname)
27 {
28 char *hcbExt = strstr(fname, HBC_FILE_EXT);
29 if (hcbExt == NULL) {
30 return false;
31 }
32 return true;
33 }
34
OpenHcsBlobFile(const char * hcsBlobPath,char ** hcsBlob)35 uint32_t OpenHcsBlobFile(const char *hcsBlobPath, char **hcsBlob)
36 {
37 // the 0 is error.
38 int32_t length = 0;
39 if ((hcsBlobPath == NULL) || (hcsBlob == NULL) || !IsHcbFile(hcsBlobPath)) {
40 HDF_LOGE("%{public}s failed, pls check the param", __func__);
41 return length;
42 }
43
44 char path[PATH_MAX] = { 0 };
45 if (realpath(hcsBlobPath, path) == NULL) {
46 HDF_LOGE("file %{public}s is invalid", hcsBlobPath);
47 return length;
48 }
49 FILE *fp = fopen(path, "rb");
50 do {
51 if (fp == NULL) {
52 HDF_LOGE("%{public}s failed, pls check the path of %{public}s", __func__, hcsBlobPath);
53 break;
54 }
55 (void)fseek(fp, 0, SEEK_END);
56 length = (int32_t)ftell(fp);
57 if ((length <= 0) || (length >= HBC_BLOB_MAX_LENGTH)) {
58 length = 0;
59 HDF_LOGE("%{public}s failed, the HcsBlob file length is %{public}d", __func__, length);
60 break;
61 }
62 *hcsBlob = (char *)OsalMemCalloc(length + 1);
63 if ((*hcsBlob) == NULL) {
64 length = 0;
65 HDF_LOGE("%{public}s failed, OsalMemCalloc hcsBlob memory failed", __func__);
66 break;
67 }
68 (void)fseek(fp, 0, SEEK_SET);
69 (void)fread((void *)(*hcsBlob), (size_t)length, 1, fp);
70 } while (0);
71 if (fp != NULL) {
72 fclose(fp);
73 }
74 return (length > 0) ? length : 0;
75 }
76