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