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