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 #ifndef UPDATER_EMMC_PTABLE_H
17 #define UPDATER_EMMC_PTABLE_H
18 #include <iostream>
19 #include "ptable.h"
20 
21 namespace Updater {
22 class EmmcPtable : public Ptable {
23 public:
24     EmmcPtable() = default;
25     DISALLOW_COPY_MOVE(EmmcPtable);
~EmmcPtable()26     ~EmmcPtable() override {}
27 
28     uint32_t GetDeviceLunNum();
29     bool ParsePartitionFromBuffer(uint8_t *ptbImgBuffer, const uint32_t imgBufSize) override;
30     bool LoadPtableFromDevice() override;
31     bool WritePartitionTable() override;
32     bool EditPartitionBuf(uint8_t *imageBuf, uint64_t imgBufSize, std::vector<PtnInfo> &modifyList) override;
33     bool GetPtableImageBuffer(uint8_t *imageBuf, const uint32_t imgBufSize) override;
34 
35 private:
36     static constexpr uint32_t  GPT_PARTITION_START_LBA_OFFSET = 32;
37     static constexpr uint32_t  GPT_PARTITION_END_LBA_OFFSET = 8;
38     static constexpr uint32_t  GPT_PARTITION_NAME_OFFSET = 56;
39     static constexpr uint32_t  GPT_PARTITION_TYPE_GUID_OFFSET = 0;
40     static constexpr uint32_t  GPT_DISP_NAME_LEN = 32;
41     static constexpr uint32_t GPT_PARTITION_SIZE = 128 * 1024;
42     static constexpr uint32_t LBA_LENGTH = 512;
43     static constexpr uint32_t GPT_PARTITION_INFO_LENGTH = 128;
44     static constexpr uint32_t PROTECTIVE_MBR_SIZE = 512;
45     static constexpr uint32_t MIN_EMMC_WRITE_SIZE = 512;
46     static constexpr uint32_t EMMC_BLOCK_SIZE = 512;
47 
48     struct EmmcPartitionDataInfo {
49         bool isGptVaild = false;
50         uint32_t writeDataLen = 0; // data len write to emmc
51         uint8_t data[GPT_PARTITION_SIZE] = {0}; // ptable image data
52     };
53 
54     struct EmmcPartitionDataInfo emmcPtnDataInfo_;
55 
56     bool EmmcReadGpt(uint8_t *ptableData, uint32_t len);
57     bool UpdateCommInitializeGptPartition(uint8_t *gptImage, const uint32_t len);
58     bool ReadEmmcGptImageToRam();
59     uint64_t GetDeviceCapacity();
60     void EmmcPatchGptHeader(EmmcPartitionDataInfo &ptnDataInfo, const uint32_t blockSize);
61     bool ParseGptHeaderByEmmc(uint8_t *gptImage, const uint32_t len);
62 };
63 } // namespace Updater
64 #endif // UPDATER_EMMC_PTABLE_H