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,const void * context)23 bool RawWriter::Write(const uint8_t *addr, size_t len, [[maybe_unused]] const void *context)
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_ = OpenPath(path_);
37 if (fd_ < 0) {
38 return false;
39 }
40 }
41
42 if (WriteInternal(fd_, addr, len) < 0) {
43 return false;
44 }
45 return true;
46 }
47
WriteInternal(int fd,const uint8_t * data,size_t len)48 int RawWriter::WriteInternal(int fd, const uint8_t *data, size_t len)
49 {
50 ssize_t written = 0;
51 size_t rest = len;
52
53 int ret = lseek64(fd, offset_, SEEK_SET);
54 if (ret == -1) {
55 LOG(ERROR) << "RawWriter: failed to seek file to " << offset_ << " : " << strerror(errno);
56 return -1;
57 }
58
59 while (rest > 0) {
60 written = write(fd, data, rest);
61 if (written < 0) {
62 LOG(ERROR) << "RawWriter: failed to write data of len " << len << " : " << strerror(errno);
63 return -1;
64 }
65 data += written;
66 rest -= static_cast<size_t>(written);
67 }
68 offset_ += static_cast<off64_t>(len);
69 return 0;
70 }
71 } // namespace Updater
72