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 "libdm/dm_table.h"
18 
19 #include <android-base/logging.h>
20 #include <android-base/macros.h>
21 
22 namespace android {
23 namespace dm {
24 
AddTarget(std::unique_ptr<DmTarget> && target)25 bool DmTable::AddTarget(std::unique_ptr<DmTarget>&& target) {
26     if (!target->Valid()) {
27         return false;
28     }
29     num_sectors_ += target->size();
30     targets_.push_back(std::move(target));
31     return true;
32 }
33 
RemoveTarget(std::unique_ptr<DmTarget> &&)34 bool DmTable::RemoveTarget(std::unique_ptr<DmTarget>&& /* target */) {
35     return true;
36 }
37 
valid() const38 bool DmTable::valid() const {
39     if (targets_.empty()) {
40         LOG(ERROR) << "Device-mapper table must have at least one target.";
41         return "";
42     }
43     if (targets_[0]->start() != 0) {
44         LOG(ERROR) << "Device-mapper table must start at logical sector 0.";
45         return "";
46     }
47     return true;
48 }
49 
num_sectors() const50 uint64_t DmTable::num_sectors() const {
51     return valid() ? num_sectors_ : 0;
52 }
53 
54 // Returns a string representation of the table that is ready to be passed
55 // down to the kernel for loading.
56 //
57 // Implementation must verify there are no gaps in the table, table starts
58 // with sector == 0, and iterate over each target to get its table
59 // serialized.
Serialize() const60 std::string DmTable::Serialize() const {
61     if (!valid()) {
62         return "";
63     }
64 
65     std::string table;
66     for (const auto& target : targets_) {
67         table += target->Serialize();
68     }
69     return table;
70 }
71 
72 }  // namespace dm
73 }  // namespace android
74