blob: 73cf1bff16931151177a448f8ff0c82ba31a9201 [file] [log] [blame]
Hridya Valsaraju31d2c262018-07-20 13:35:50 -07001/*
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 "utility.h"
18
David Anderson12211d12018-07-24 15:21:20 -070019#include <android-base/logging.h>
20
21#include "fastboot_device.h"
22
23using android::base::unique_fd;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070024using android::hardware::boot::V1_0::Slot;
25
David Anderson12211d12018-07-24 15:21:20 -070026static bool OpenPhysicalPartition(const std::string& name, PartitionHandle* handle) {
27 std::optional<std::string> path = FindPhysicalPartition(name);
28 if (!path) {
29 return false;
30 }
31 *handle = PartitionHandle(*path);
32 return true;
33}
34
35bool OpenPartition(FastbootDevice* /* device */, const std::string& name, PartitionHandle* handle) {
36 if (!OpenPhysicalPartition(name, handle)) {
37 LOG(ERROR) << "No such partition: " << name;
38 return false;
39 }
40
41 unique_fd fd(TEMP_FAILURE_RETRY(open(handle->path().c_str(), O_WRONLY | O_EXCL)));
42 if (fd < 0) {
43 PLOG(ERROR) << "Failed to open block device: " << handle->path();
44 return false;
45 }
46 handle->set_fd(std::move(fd));
47 return true;
48}
49
50std::optional<std::string> FindPhysicalPartition(const std::string& name) {
51 std::string path = "/dev/block/by-name/" + name;
52 if (access(path.c_str(), R_OK | W_OK) < 0) {
53 return {};
54 }
55 return path;
56}
57
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070058bool GetSlotNumber(const std::string& slot, Slot* number) {
59 if (slot.size() != 1) {
60 return false;
61 }
62 if (slot[0] < 'a' || slot[0] > 'z') {
63 return false;
64 }
65 *number = slot[0] - 'a';
66 return true;
67}