blob: bc89c2eea1141e774d4093f07984ef0fc0792057 [file] [log] [blame]
Alex Deymo68c0e7f2017-10-02 20:38:12 +02001// Copyright 2017 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "bsdiff/diff_encoder.h"
6
7#include <vector>
8
9#include "bsdiff/logging.h"
10
11using std::endl;
12
13namespace {
14
15// The maximum positive number that we should encode. A number larger than this
16// for unsigned fields will be interpreted as a negative value and thus a
17// corrupt patch.
18const uint64_t kMaxEncodedUint64Value = (1ULL << 63) - 1;
19
20} // namespace
21
22namespace bsdiff {
23
24bool DiffEncoder::AddControlEntry(const ControlEntry& entry) {
25 if (entry.diff_size > kMaxEncodedUint64Value) {
26 LOG(ERROR) << "Encoding value out of range " << entry.diff_size << endl;
27 return false;
28 }
29
30 if (entry.extra_size > kMaxEncodedUint64Value) {
31 LOG(ERROR) << "Encoding value out of range " << entry.extra_size << endl;
32 return false;
33 }
34
Alex Deymoaefc2532017-10-11 17:50:12 +020035 // entry.diff_size + entry.extra_size don't overflow in uint64_t since we
36 // checked the kMaxEncodedUint64Value limit before.
37 if (entry.diff_size + entry.extra_size > new_size_ - written_output_) {
Alex Deymo68c0e7f2017-10-02 20:38:12 +020038 LOG(ERROR) << "Wrote more output than the declared new_size" << endl;
39 return false;
40 }
41
42 if (entry.diff_size > 0 &&
Alex Deymoaefc2532017-10-11 17:50:12 +020043 (old_pos_ < 0 ||
44 static_cast<uint64_t>(old_pos_) + entry.diff_size > old_size_)) {
45 LOG(ERROR) << "The pointer in the old stream [" << old_pos_ << ", "
46 << (static_cast<uint64_t>(old_pos_) + entry.diff_size)
Alex Deymo68c0e7f2017-10-02 20:38:12 +020047 << ") is out of bounds [0, " << old_size_ << ")" << endl;
48 return false;
49 }
50
51 // Pass down the control entry.
52 if (!patch_->AddControlEntry(entry))
53 return false;
54
55 // Generate the diff stream.
56 std::vector<uint8_t> diff(entry.diff_size);
57 for (uint64_t i = 0; i < entry.diff_size; ++i) {
58 diff[i] = new_buf_[written_output_ + i] - old_buf_[old_pos_ + i];
59 }
60 if (!patch_->WriteDiffStream(diff.data(), diff.size())) {
61 LOG(ERROR) << "Writing " << diff.size() << " bytes to the diff stream"
62 << endl;
63 return false;
64 }
65
66 if (!patch_->WriteExtraStream(new_buf_ + written_output_ + entry.diff_size,
67 entry.extra_size)) {
68 LOG(ERROR) << "Writing " << entry.extra_size << " bytes to the extra stream"
69 << endl;
70 return false;
71 }
72
73 old_pos_ += entry.diff_size + entry.offset_increment;
74 written_output_ += entry.diff_size + entry.extra_size;
75
76 return true;
77}
78
79bool DiffEncoder::Close() {
80 if (written_output_ != new_size_) {
81 LOG(ERROR) << "Close() called but not all the output was written" << endl;
82 return false;
83 }
84 return patch_->Close();
85}
86
87} // namespace bsdiff