1 /*
2 * Copyright (C) 2015 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 <libboot_control/libboot_control.h>
18
19 #include <endian.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <string.h>
23
24 #include <string>
25
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/unique_fd.h>
31 #include <bootloader_message/bootloader_message.h>
32
33 #include "private/boot_control_definition.h"
34
35 namespace android {
36 namespace bootable {
37
38 using ::android::hardware::boot::V1_1::MergeStatus;
39
40 // The number of boot attempts that should be made from a new slot before
41 // rolling back to the previous slot.
42 constexpr unsigned int kDefaultBootAttempts = 7;
43 static_assert(kDefaultBootAttempts < 8, "tries_remaining field only has 3 bits");
44
45 constexpr unsigned int kMaxNumSlots =
46 sizeof(bootloader_control::slot_info) / sizeof(bootloader_control::slot_info[0]);
47 constexpr const char* kSlotSuffixes[kMaxNumSlots] = { "_a", "_b", "_c", "_d" };
48 constexpr off_t kBootloaderControlOffset = offsetof(bootloader_message_ab, slot_suffix);
49
CRC32(const uint8_t * buf,size_t size)50 static uint32_t CRC32(const uint8_t* buf, size_t size) {
51 static uint32_t crc_table[256];
52
53 // Compute the CRC-32 table only once.
54 if (!crc_table[1]) {
55 for (uint32_t i = 0; i < 256; ++i) {
56 uint32_t crc = i;
57 for (uint32_t j = 0; j < 8; ++j) {
58 uint32_t mask = -(crc & 1);
59 crc = (crc >> 1) ^ (0xEDB88320 & mask);
60 }
61 crc_table[i] = crc;
62 }
63 }
64
65 uint32_t ret = -1;
66 for (size_t i = 0; i < size; ++i) {
67 ret = (ret >> 8) ^ crc_table[(ret ^ buf[i]) & 0xFF];
68 }
69
70 return ~ret;
71 }
72
73 // Return the little-endian representation of the CRC-32 of the first fields
74 // in |boot_ctrl| up to the crc32_le field.
BootloaderControlLECRC(const bootloader_control * boot_ctrl)75 uint32_t BootloaderControlLECRC(const bootloader_control* boot_ctrl) {
76 return htole32(
77 CRC32(reinterpret_cast<const uint8_t*>(boot_ctrl), offsetof(bootloader_control, crc32_le)));
78 }
79
LoadBootloaderControl(const std::string & misc_device,bootloader_control * buffer)80 bool LoadBootloaderControl(const std::string& misc_device, bootloader_control* buffer) {
81 android::base::unique_fd fd(open(misc_device.c_str(), O_RDONLY));
82 if (fd.get() == -1) {
83 PLOG(ERROR) << "failed to open " << misc_device;
84 return false;
85 }
86 if (lseek(fd, kBootloaderControlOffset, SEEK_SET) != kBootloaderControlOffset) {
87 PLOG(ERROR) << "failed to lseek " << misc_device;
88 return false;
89 }
90 if (!android::base::ReadFully(fd.get(), buffer, sizeof(bootloader_control))) {
91 PLOG(ERROR) << "failed to read " << misc_device;
92 return false;
93 }
94 return true;
95 }
96
UpdateAndSaveBootloaderControl(const std::string & misc_device,bootloader_control * buffer)97 bool UpdateAndSaveBootloaderControl(const std::string& misc_device, bootloader_control* buffer) {
98 buffer->crc32_le = BootloaderControlLECRC(buffer);
99 android::base::unique_fd fd(open(misc_device.c_str(), O_WRONLY | O_SYNC));
100 if (fd.get() == -1) {
101 PLOG(ERROR) << "failed to open " << misc_device;
102 return false;
103 }
104 if (lseek(fd.get(), kBootloaderControlOffset, SEEK_SET) != kBootloaderControlOffset) {
105 PLOG(ERROR) << "failed to lseek " << misc_device;
106 return false;
107 }
108 if (!android::base::WriteFully(fd.get(), buffer, sizeof(bootloader_control))) {
109 PLOG(ERROR) << "failed to write " << misc_device;
110 return false;
111 }
112 return true;
113 }
114
InitDefaultBootloaderControl(BootControl * control,bootloader_control * boot_ctrl)115 void InitDefaultBootloaderControl(BootControl* control, bootloader_control* boot_ctrl) {
116 memset(boot_ctrl, 0, sizeof(*boot_ctrl));
117
118 unsigned int current_slot = control->GetCurrentSlot();
119 if (current_slot < kMaxNumSlots) {
120 strlcpy(boot_ctrl->slot_suffix, kSlotSuffixes[current_slot], sizeof(boot_ctrl->slot_suffix));
121 }
122 boot_ctrl->magic = BOOT_CTRL_MAGIC;
123 boot_ctrl->version = BOOT_CTRL_VERSION;
124
125 // Figure out the number of slots by checking if the partitions exist,
126 // otherwise assume the maximum supported by the header.
127 boot_ctrl->nb_slot = kMaxNumSlots;
128 std::string base_path = control->misc_device();
129 size_t last_path_sep = base_path.rfind('/');
130 if (last_path_sep != std::string::npos) {
131 // We test the existence of the "boot" partition on each possible slot,
132 // which is a partition required by Android Bootloader Requirements.
133 base_path = base_path.substr(0, last_path_sep + 1) + "boot";
134 int last_existing_slot = -1;
135 int first_missing_slot = -1;
136 for (unsigned int slot = 0; slot < kMaxNumSlots; ++slot) {
137 std::string partition_path = base_path + kSlotSuffixes[slot];
138 struct stat part_stat;
139 int err = stat(partition_path.c_str(), &part_stat);
140 if (!err) {
141 last_existing_slot = slot;
142 LOG(INFO) << "Found slot: " << kSlotSuffixes[slot];
143 } else if (err < 0 && errno == ENOENT && first_missing_slot == -1) {
144 first_missing_slot = slot;
145 }
146 }
147 // We only declare that we found the actual number of slots if we found all
148 // the boot partitions up to the number of slots, and no boot partition
149 // after that. Not finding any of the boot partitions implies a problem so
150 // we just leave the number of slots in the maximum value.
151 if ((last_existing_slot != -1 && last_existing_slot + 1 == first_missing_slot) ||
152 (first_missing_slot == -1 && last_existing_slot + 1 == kMaxNumSlots)) {
153 boot_ctrl->nb_slot = last_existing_slot + 1;
154 LOG(INFO) << "Found a system with " << last_existing_slot + 1 << " slots.";
155 }
156 }
157
158 for (unsigned int slot = 0; slot < kMaxNumSlots; ++slot) {
159 slot_metadata entry = {};
160
161 if (slot < boot_ctrl->nb_slot) {
162 entry.priority = 7;
163 entry.tries_remaining = kDefaultBootAttempts;
164 entry.successful_boot = 0;
165 } else {
166 entry.priority = 0; // Unbootable
167 }
168
169 // When the boot_control stored on disk is invalid, we assume that the
170 // current slot is successful. The bootloader should repair this situation
171 // before booting and write a valid boot_control slot, so if we reach this
172 // stage it means that the misc partition was corrupted since boot.
173 if (current_slot == slot) {
174 entry.successful_boot = 1;
175 }
176
177 boot_ctrl->slot_info[slot] = entry;
178 }
179 boot_ctrl->recovery_tries_remaining = 0;
180
181 boot_ctrl->crc32_le = BootloaderControlLECRC(boot_ctrl);
182 }
183
184 // Return the index of the slot suffix passed or -1 if not a valid slot suffix.
SlotSuffixToIndex(const char * suffix)185 int SlotSuffixToIndex(const char* suffix) {
186 for (unsigned int slot = 0; slot < kMaxNumSlots; ++slot) {
187 if (!strcmp(kSlotSuffixes[slot], suffix)) return slot;
188 }
189 return -1;
190 }
191
192 // Initialize the boot_control_private struct with the information from
193 // the bootloader_message buffer stored in |boot_ctrl|. Returns whether the
194 // initialization succeeded.
Init()195 bool BootControl::Init() {
196 if (initialized_) return true;
197
198 // Initialize the current_slot from the read-only property. If the property
199 // was not set (from either the command line or the device tree), we can later
200 // initialize it from the bootloader_control struct.
201 std::string suffix_prop = android::base::GetProperty("ro.boot.slot_suffix", "");
202 if (suffix_prop.empty()) {
203 LOG(ERROR) << "Slot suffix property is not set";
204 return false;
205 }
206 current_slot_ = SlotSuffixToIndex(suffix_prop.c_str());
207
208 std::string err;
209 std::string device = get_bootloader_message_blk_device(&err);
210 if (device.empty()) {
211 LOG(ERROR) << "Could not find bootloader message block device: " << err;
212 return false;
213 }
214
215 bootloader_control boot_ctrl;
216 if (!LoadBootloaderControl(device.c_str(), &boot_ctrl)) {
217 LOG(ERROR) << "Failed to load bootloader control block";
218 return false;
219 }
220
221 // Note that since there isn't a module unload function this memory is leaked.
222 // We use `device` below sometimes, so it's not moved out of here.
223 misc_device_ = device;
224 initialized_ = true;
225
226 // Validate the loaded data, otherwise we will destroy it and re-initialize it
227 // with the current information.
228 uint32_t computed_crc32 = BootloaderControlLECRC(&boot_ctrl);
229 if (boot_ctrl.crc32_le != computed_crc32) {
230 LOG(WARNING) << "Invalid boot control found, expected CRC-32 0x" << std::hex << computed_crc32
231 << " but found 0x" << std::hex << boot_ctrl.crc32_le << ". Re-initializing.";
232 InitDefaultBootloaderControl(this, &boot_ctrl);
233 UpdateAndSaveBootloaderControl(device.c_str(), &boot_ctrl);
234 }
235
236 if (!InitMiscVirtualAbMessageIfNeeded()) {
237 return false;
238 }
239
240 num_slots_ = boot_ctrl.nb_slot;
241 return true;
242 }
243
GetNumberSlots()244 unsigned int BootControl::GetNumberSlots() {
245 return num_slots_;
246 }
247
GetCurrentSlot()248 unsigned int BootControl::GetCurrentSlot() {
249 return current_slot_;
250 }
251
MarkBootSuccessful()252 bool BootControl::MarkBootSuccessful() {
253 bootloader_control bootctrl;
254 if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
255
256 bootctrl.slot_info[current_slot_].successful_boot = 1;
257 // tries_remaining == 0 means that the slot is not bootable anymore, make
258 // sure we mark the current slot as bootable if it succeeds in the last
259 // attempt.
260 bootctrl.slot_info[current_slot_].tries_remaining = 1;
261 return UpdateAndSaveBootloaderControl(misc_device_, &bootctrl);
262 }
263
SetActiveBootSlot(unsigned int slot)264 bool BootControl::SetActiveBootSlot(unsigned int slot) {
265 if (slot >= kMaxNumSlots || slot >= num_slots_) {
266 // Invalid slot number.
267 return false;
268 }
269
270 bootloader_control bootctrl;
271 if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
272
273 // Set every other slot with a lower priority than the new "active" slot.
274 const unsigned int kActivePriority = 15;
275 const unsigned int kActiveTries = 6;
276 for (unsigned int i = 0; i < num_slots_; ++i) {
277 if (i != slot) {
278 if (bootctrl.slot_info[i].priority >= kActivePriority)
279 bootctrl.slot_info[i].priority = kActivePriority - 1;
280 }
281 }
282
283 // Note that setting a slot as active doesn't change the successful bit.
284 // The successful bit will only be changed by setSlotAsUnbootable().
285 bootctrl.slot_info[slot].priority = kActivePriority;
286 bootctrl.slot_info[slot].tries_remaining = kActiveTries;
287
288 // Setting the current slot as active is a way to revert the operation that
289 // set *another* slot as active at the end of an updater. This is commonly
290 // used to cancel the pending update. We should only reset the verity_corrpted
291 // bit when attempting a new slot, otherwise the verity bit on the current
292 // slot would be flip.
293 if (slot != current_slot_) bootctrl.slot_info[slot].verity_corrupted = 0;
294
295 return UpdateAndSaveBootloaderControl(misc_device_, &bootctrl);
296 }
297
SetSlotAsUnbootable(unsigned int slot)298 bool BootControl::SetSlotAsUnbootable(unsigned int slot) {
299 if (slot >= kMaxNumSlots || slot >= num_slots_) {
300 // Invalid slot number.
301 return false;
302 }
303
304 bootloader_control bootctrl;
305 if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
306
307 // The only way to mark a slot as unbootable, regardless of the priority is to
308 // set the tries_remaining to 0.
309 bootctrl.slot_info[slot].successful_boot = 0;
310 bootctrl.slot_info[slot].tries_remaining = 0;
311 return UpdateAndSaveBootloaderControl(misc_device_, &bootctrl);
312 }
313
IsSlotBootable(unsigned int slot)314 bool BootControl::IsSlotBootable(unsigned int slot) {
315 if (slot >= kMaxNumSlots || slot >= num_slots_) {
316 // Invalid slot number.
317 return false;
318 }
319
320 bootloader_control bootctrl;
321 if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
322
323 return bootctrl.slot_info[slot].tries_remaining != 0;
324 }
325
IsSlotMarkedSuccessful(unsigned int slot)326 bool BootControl::IsSlotMarkedSuccessful(unsigned int slot) {
327 if (slot >= kMaxNumSlots || slot >= num_slots_) {
328 // Invalid slot number.
329 return false;
330 }
331
332 bootloader_control bootctrl;
333 if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
334
335 return bootctrl.slot_info[slot].successful_boot && bootctrl.slot_info[slot].tries_remaining;
336 }
337
IsValidSlot(unsigned int slot)338 bool BootControl::IsValidSlot(unsigned int slot) {
339 return slot < kMaxNumSlots && slot < num_slots_;
340 }
341
SetSnapshotMergeStatus(MergeStatus status)342 bool BootControl::SetSnapshotMergeStatus(MergeStatus status) {
343 return SetMiscVirtualAbMergeStatus(current_slot_, status);
344 }
345
GetSnapshotMergeStatus()346 MergeStatus BootControl::GetSnapshotMergeStatus() {
347 MergeStatus status;
348 if (!GetMiscVirtualAbMergeStatus(current_slot_, &status)) {
349 return MergeStatus::UNKNOWN;
350 }
351 return status;
352 }
353
GetSuffix(unsigned int slot)354 const char* BootControl::GetSuffix(unsigned int slot) {
355 if (slot >= kMaxNumSlots || slot >= num_slots_) {
356 return nullptr;
357 }
358 return kSlotSuffixes[slot];
359 }
360
InitMiscVirtualAbMessageIfNeeded()361 bool InitMiscVirtualAbMessageIfNeeded() {
362 std::string err;
363 misc_virtual_ab_message message;
364 if (!ReadMiscVirtualAbMessage(&message, &err)) {
365 LOG(ERROR) << "Could not read merge status: " << err;
366 return false;
367 }
368
369 if (message.version == MISC_VIRTUAL_AB_MESSAGE_VERSION &&
370 message.magic == MISC_VIRTUAL_AB_MAGIC_HEADER) {
371 // Already initialized.
372 return true;
373 }
374
375 message = {};
376 message.version = MISC_VIRTUAL_AB_MESSAGE_VERSION;
377 message.magic = MISC_VIRTUAL_AB_MAGIC_HEADER;
378 if (!WriteMiscVirtualAbMessage(message, &err)) {
379 LOG(ERROR) << "Could not write merge status: " << err;
380 return false;
381 }
382 return true;
383 }
384
SetMiscVirtualAbMergeStatus(unsigned int current_slot,android::hardware::boot::V1_1::MergeStatus status)385 bool SetMiscVirtualAbMergeStatus(unsigned int current_slot,
386 android::hardware::boot::V1_1::MergeStatus status) {
387 std::string err;
388 misc_virtual_ab_message message;
389
390 if (!ReadMiscVirtualAbMessage(&message, &err)) {
391 LOG(ERROR) << "Could not read merge status: " << err;
392 return false;
393 }
394
395 message.merge_status = static_cast<uint8_t>(status);
396 message.source_slot = current_slot;
397 if (!WriteMiscVirtualAbMessage(message, &err)) {
398 LOG(ERROR) << "Could not write merge status: " << err;
399 return false;
400 }
401 return true;
402 }
403
GetMiscVirtualAbMergeStatus(unsigned int current_slot,android::hardware::boot::V1_1::MergeStatus * status)404 bool GetMiscVirtualAbMergeStatus(unsigned int current_slot,
405 android::hardware::boot::V1_1::MergeStatus* status) {
406 std::string err;
407 misc_virtual_ab_message message;
408
409 if (!ReadMiscVirtualAbMessage(&message, &err)) {
410 LOG(ERROR) << "Could not read merge status: " << err;
411 return false;
412 }
413
414 // If the slot reverted after having created a snapshot, then the snapshot will
415 // be thrown away at boot. Thus we don't count this as being in a snapshotted
416 // state.
417 *status = static_cast<MergeStatus>(message.merge_status);
418 if (*status == MergeStatus::SNAPSHOTTED && current_slot == message.source_slot) {
419 *status = MergeStatus::NONE;
420 }
421 return true;
422 }
423
424 } // namespace bootable
425 } // namespace android
426