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