1 /*
2 * Copyright (c) 2022 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 <climits>
17 #include <cstdint>
18
19 #include "metadata/metadata_reader.h"
20 #include "metadata/metadata_serializer.h"
21 #include "util/file.h"
22 #include "util/logger.h"
23
24 namespace OHOS {
25 namespace Idl {
26 const char* MetadataReader::tag = "MetadataReader";
27
ReadMetadataFromFile(const String & filePath)28 std::shared_ptr<MetaComponent> MetadataReader::ReadMetadataFromFile(const String& filePath)
29 {
30 File file(filePath, File::READ);
31 if (!file.IsValid()) {
32 Logger::E(tag, "Open \"%s\" file failed.", filePath.string());
33 return nullptr;
34 }
35
36 if (!file.Reset()) {
37 Logger::E(tag, "Reset \"%s\" file failed.", filePath.string());
38 return nullptr;
39 }
40
41 MetaComponent header;
42
43 if (!file.ReadData((void*)&header, sizeof(MetaComponent))) {
44 Logger::E(tag, "Read \"%s\" file failed.", filePath.string());
45 return nullptr;
46 }
47
48 if (header.magic_ != METADATA_MAGIC_NUMBER || header.size_ < 0 || header.size_ > UINT16_MAX) {
49 Logger::E(tag, "The metadata in \"%s\" file is bad.", filePath.string());
50 return nullptr;
51 }
52
53 if (!file.Reset()) {
54 Logger::E(tag, "Reset \"%s\" file failed.", filePath.string());
55 return nullptr;
56 }
57
58 void* data = malloc(header.size_);
59 if (data == nullptr) {
60 Logger::E(tag, "Malloc metadata failed.");
61 return nullptr;
62 }
63
64 if (!file.ReadData(data, header.size_)) {
65 Logger::E(tag, "Read \"%s\" file failed.", filePath.string());
66 free(data);
67 return nullptr;
68 }
69
70 std::shared_ptr<MetaComponent> metadata(
71 (MetaComponent*)data, [](MetaComponent* p) { free(p); });
72
73 MetadataSerializer serializer((uintptr_t)data);
74 serializer.Deserialize();
75
76 return metadata;
77 }
78 } // namespace Idl
79 } // namespace OHOS
80