1 /*
2  * Copyright (c) 2021 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_DATA_WRITER_H
17 #define UPDATER_DATA_WRITER_H
18 
19 #include <cstdio>
20 #include <memory>
21 #include <string>
22 #include <unistd.h>
23 #include "updater_env.h"
24 
25 namespace Updater {
26 enum WriteMode : int {
27     WRITE_RAW = 1,
28     WRITE_DECRYPT = 2,
29     WRITE_BLOCK = 3,
30 };
31 
32 class DataWriter {
33 public:
34     using DataWriterPtr = DataWriter *;
35     using WriterConstructor = std::unique_ptr<DataWriter> (*)(const std::string &, const std::string &,
36         uint64_t, uint64_t);
37     virtual bool Write(const uint8_t *addr, size_t len, const void *context) = 0;
~DataWriter()38     virtual ~DataWriter() {}
39     static std::unique_ptr<DataWriter> CreateDataWriter(WriteMode mode, const std::string &path, UpdaterEnv *env,
40         uint64_t offset = 0);
41     static std::unique_ptr<DataWriter> CreateDataWriter(WriteMode mode, const std::string &path, uint64_t offset = 0);
42     static std::unique_ptr<DataWriter> CreateDataWriter(const std::string &mode, const std::string &path,
43         const std::string &partName = {}, uint64_t startAddr = 0, uint64_t offset = 0);
44     static UpdaterEnv *GetUpdaterEnv();
45     void SetUpdaterEnv(UpdaterEnv *env);
46     static void ReleaseDataWriter(std::unique_ptr<DataWriter> &writer);
47     static void RegisterDataWriter(const std::string &mode, WriterConstructor constructor);
48 
49 protected:
50     virtual int OpenPath(const std::string &path);
51 
52 private:
53     static UpdaterEnv *env_;
54     static inline std::unordered_map<std::string, WriterConstructor> constructorMap_;
55 };
56 
57 // Maybe we should read sector size from flash.
58 #define DEFAULT_SECTOR_SIZE (512)
59 } // Updater
60 #endif // UPDATER_DATA_WRITER_H
61