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 {
RegisterRawWriter(void)23 extern "C" __attribute__((constructor)) void RegisterRawWriter(void)
24 {
25 DataWriter::RegisterDataWriter("WRITE_RAW",
26 [](const std::string &path, const std::string &partName, uint64_t startAddr,
27 uint64_t offset) -> std::unique_ptr<DataWriter> {
28 return std::make_unique<RawWriter>(path, startAddr, offset);
29 });
30 }
31
Write(const uint8_t * addr,size_t len,const void * context)32 bool RawWriter::Write(const uint8_t *addr, size_t len, [[maybe_unused]] const void *context)
33 {
34 if (addr == nullptr) {
35 LOG(ERROR) << "RawWriter: invalid address.";
36 return false;
37 }
38
39 if (len == 0) {
40 LOG(WARNING) << "RawWriter: write length is 0, skip.";
41 return false;
42 }
43
44 if (fd_ < 0) {
45 fd_ = OpenPath(path_);
46 if (fd_ < 0) {
47 return false;
48 }
49 }
50
51 if (WriteInternal(fd_, addr, len) < 0) {
52 return false;
53 }
54 return true;
55 }
56
WriteInternal(int fd,const uint8_t * data,size_t len)57 int RawWriter::WriteInternal(int fd, const uint8_t *data, size_t len)
58 {
59 ssize_t written = 0;
60 size_t rest = len;
61
62 int ret = lseek64(fd, offset_, SEEK_SET);
63 if (ret == -1) {
64 LOG(ERROR) << "RawWriter: failed to seek file to " << offset_ << " : " << strerror(errno);
65 return -1;
66 }
67
68 while (rest > 0) {
69 written = write(fd, data, rest);
70 if (written < 0) {
71 LOG(ERROR) << "RawWriter: failed to write data of len " << len << " : " << strerror(errno);
72 return -1;
73 }
74 data += written;
75 rest -= static_cast<size_t>(written);
76 }
77 offset_ += static_cast<off64_t>(len);
78 return 0;
79 }
80 } // namespace Updater
81