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 #include "raw_writer.h"
16 #include <cerrno>
17 #include <cstdio>
18 #include <string>
19 #include <unistd.h>
20 #include "log/log.h"
21
22 namespace updater {
Write(const uint8_t * addr,size_t len,WriteMode mode,const std::string & partitionName)23 bool RawWriter::Write(const uint8_t *addr, size_t len, WriteMode mode, const std::string &partitionName)
24 {
25 if (addr == nullptr) {
26 LOG(ERROR) << "RawWriter: invalid address.";
27 return false;
28 }
29
30 if (len == 0) {
31 LOG(WARNING) << "RawWriter: write length is 0, skip.";
32 return false;
33 }
34
35 if (fd_ < 0) {
36 fd_ = OpenPartition(partitionName_);
37 if (fd_ < 0) {
38 return false;
39 }
40 }
41
42 UPDATER_CHECK_ONLY_RETURN(WriteInternal(fd_, addr, len) >= 0, return false);
43 return true;
44 }
45
WriteInternal(int fd,const uint8_t * data,size_t len)46 int RawWriter::WriteInternal(int fd, const uint8_t *data, size_t len)
47 {
48 ssize_t written = 0;
49 size_t rest = len;
50
51 int ret = lseek64(fd, offset_, SEEK_SET);
52 UPDATER_FILE_CHECK(ret != -1, "RawWriter: failed to seek file to " << offset_, return -1);
53
54 while (rest > 0) {
55 written = write(fd, data, rest);
56 UPDATER_FILE_CHECK(written >= 0, "RawWriter: failed to write data of len " << len, return -1);
57 data += written;
58 rest -= written;
59 }
60 offset_ += len;
61 return 0;
62 }
63 } // namespace updater
64