blob: 28760c99485bb6a7f394a236f0b0d0b74462f12d [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
35 if (written_output_ + entry.diff_size + entry.extra_size > new_size_) {
36 LOG(ERROR) << "Wrote more output than the declared new_size" << endl;
37 return false;
38 }
39
40 if (entry.diff_size > 0 &&
41 (old_pos_ < 0 || static_cast<uint64_t>(old_pos_) >= old_size_)) {
42 LOG(ERROR) << "The pointer in the old stream (" << old_pos_
43 << ") is out of bounds [0, " << old_size_ << ")" << endl;
44 return false;
45 }
46
47 // Pass down the control entry.
48 if (!patch_->AddControlEntry(entry))
49 return false;
50
51 // Generate the diff stream.
52 std::vector<uint8_t> diff(entry.diff_size);
53 for (uint64_t i = 0; i < entry.diff_size; ++i) {
54 diff[i] = new_buf_[written_output_ + i] - old_buf_[old_pos_ + i];
55 }
56 if (!patch_->WriteDiffStream(diff.data(), diff.size())) {
57 LOG(ERROR) << "Writing " << diff.size() << " bytes to the diff stream"
58 << endl;
59 return false;
60 }
61
62 if (!patch_->WriteExtraStream(new_buf_ + written_output_ + entry.diff_size,
63 entry.extra_size)) {
64 LOG(ERROR) << "Writing " << entry.extra_size << " bytes to the extra stream"
65 << endl;
66 return false;
67 }
68
69 old_pos_ += entry.diff_size + entry.offset_increment;
70 written_output_ += entry.diff_size + entry.extra_size;
71
72 return true;
73}
74
75bool DiffEncoder::Close() {
76 if (written_output_ != new_size_) {
77 LOG(ERROR) << "Close() called but not all the output was written" << endl;
78 return false;
79 }
80 return patch_->Close();
81}
82
83} // namespace bsdiff