1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "idmap2/BinaryStreamVisitor.h"
18
19 #include <algorithm>
20 #include <cstring>
21 #include <string>
22
23 #include "android-base/macros.h"
24
25 namespace android::idmap2 {
26
Write16(uint16_t value)27 void BinaryStreamVisitor::Write16(uint16_t value) {
28 uint16_t x = htodl(value);
29 stream_.write(reinterpret_cast<char*>(&x), sizeof(uint16_t));
30 }
31
Write32(uint32_t value)32 void BinaryStreamVisitor::Write32(uint32_t value) {
33 uint32_t x = htodl(value);
34 stream_.write(reinterpret_cast<char*>(&x), sizeof(uint32_t));
35 }
36
WriteString(const StringPiece & value)37 void BinaryStreamVisitor::WriteString(const StringPiece& value) {
38 char buf[kIdmapStringLength];
39 memset(buf, 0, sizeof(buf));
40 memcpy(buf, value.data(), std::min(value.size(), sizeof(buf)));
41 stream_.write(buf, sizeof(buf));
42 }
43
visit(const Idmap & idmap ATTRIBUTE_UNUSED)44 void BinaryStreamVisitor::visit(const Idmap& idmap ATTRIBUTE_UNUSED) {
45 // nothing to do
46 }
47
visit(const IdmapHeader & header)48 void BinaryStreamVisitor::visit(const IdmapHeader& header) {
49 Write32(header.GetMagic());
50 Write32(header.GetVersion());
51 Write32(header.GetTargetCrc());
52 Write32(header.GetOverlayCrc());
53 WriteString(header.GetTargetPath());
54 WriteString(header.GetOverlayPath());
55 }
56
visit(const IdmapData & data ATTRIBUTE_UNUSED)57 void BinaryStreamVisitor::visit(const IdmapData& data ATTRIBUTE_UNUSED) {
58 // nothing to do
59 }
60
visit(const IdmapData::Header & header)61 void BinaryStreamVisitor::visit(const IdmapData::Header& header) {
62 Write16(header.GetTargetPackageId());
63 Write16(header.GetTypeCount());
64 }
65
visit(const IdmapData::TypeEntry & type_entry)66 void BinaryStreamVisitor::visit(const IdmapData::TypeEntry& type_entry) {
67 const uint16_t entryCount = type_entry.GetEntryCount();
68
69 Write16(type_entry.GetTargetTypeId());
70 Write16(type_entry.GetOverlayTypeId());
71 Write16(entryCount);
72 Write16(type_entry.GetEntryOffset());
73 for (uint16_t i = 0; i < entryCount; i++) {
74 EntryId entry_id = type_entry.GetEntry(i);
75 Write32(entry_id != kNoEntry ? static_cast<uint32_t>(entry_id) : kPadding);
76 }
77 }
78
79 } // namespace android::idmap2
80