summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--build/all.gyp2
-rw-r--r--chrome/chrome.sln10
-rw-r--r--courgette/adjustment_method.cc (renamed from third_party/courgette/adjustment_method.cc)1406
-rw-r--r--courgette/adjustment_method.h (renamed from third_party/courgette/adjustment_method.h)85
-rw-r--r--courgette/adjustment_method_unittest.cc (renamed from third_party/courgette/adjustment_method_unittest.cc)217
-rw-r--r--courgette/assembly_program.cc (renamed from third_party/courgette/assembly_program.cc)745
-rw-r--r--courgette/assembly_program.h (renamed from third_party/courgette/assembly_program.h)267
-rw-r--r--courgette/bsdiff_memory_unittest.cc (renamed from third_party/courgette/bsdiff_memory_unittest.cc)223
-rw-r--r--courgette/courgette.gyp (renamed from third_party/courgette/courgette.gyp)49
-rw-r--r--courgette/courgette.h (renamed from third_party/courgette/courgette.h)236
-rw-r--r--courgette/courgette.sln111
-rw-r--r--courgette/courgette_minimal_tool.cc (renamed from third_party/courgette/courgette_minimal_tool.cc)100
-rw-r--r--courgette/courgette_tool.cc (renamed from third_party/courgette/courgette_tool.cc)809
-rw-r--r--courgette/crc.cc (renamed from third_party/courgette/crc.cc)44
-rw-r--r--courgette/crc.h (renamed from third_party/courgette/crc.h)34
-rw-r--r--courgette/difference_estimator.cc (renamed from third_party/courgette/difference_estimator.cc)236
-rw-r--r--courgette/difference_estimator.h (renamed from third_party/courgette/difference_estimator.h)116
-rw-r--r--courgette/difference_estimator_unittest.cc (renamed from third_party/courgette/difference_estimator_unittest.cc)116
-rw-r--r--courgette/disassembler.cc (renamed from third_party/courgette/disassembler.cc)872
-rw-r--r--courgette/disassembler.h (renamed from third_party/courgette/disassembler.h)77
-rw-r--r--courgette/encode_decode_unittest.cc (renamed from third_party/courgette/encode_decode_unittest.cc)5
-rw-r--r--courgette/encoded_program.cc (renamed from third_party/courgette/encoded_program.cc)6
-rw-r--r--courgette/encoded_program.h (renamed from third_party/courgette/encoded_program.h)3
-rw-r--r--courgette/encoded_program_fuzz_unittest.cc (renamed from third_party/courgette/encoded_program_fuzz_unittest.cc)471
-rw-r--r--courgette/encoded_program_unittest.cc (renamed from third_party/courgette/encoded_program_unittest.cc)5
-rw-r--r--courgette/ensemble.cc (renamed from third_party/courgette/ensemble.cc)204
-rw-r--r--courgette/ensemble.h (renamed from third_party/courgette/ensemble.h)514
-rw-r--r--courgette/ensemble_apply.cc (renamed from third_party/courgette/ensemble_apply.cc)824
-rw-r--r--courgette/ensemble_create.cc (renamed from third_party/courgette/ensemble_create.cc)764
-rw-r--r--courgette/image_info.cc (renamed from third_party/courgette/image_info.cc)3
-rw-r--r--courgette/image_info.h (renamed from third_party/courgette/image_info.h)1
-rw-r--r--courgette/image_info_unittest.cc (renamed from third_party/courgette/image_info_unittest.cc)3
-rw-r--r--courgette/memory_monitor.cc (renamed from third_party/courgette/memory_monitor.cc)244
-rw-r--r--courgette/region.h (renamed from third_party/courgette/region.h)124
-rw-r--r--courgette/run_all_unittests.cc (renamed from third_party/courgette/run_all_unittests.cc)19
-rw-r--r--courgette/simple_delta.cc (renamed from third_party/courgette/simple_delta.cc)82
-rw-r--r--courgette/simple_delta.h (renamed from third_party/courgette/simple_delta.h)46
-rw-r--r--courgette/streams.cc (renamed from third_party/courgette/streams.cc)4
-rw-r--r--courgette/streams.h (renamed from third_party/courgette/streams.h)2
-rw-r--r--courgette/streams_unittest.cc (renamed from third_party/courgette/streams_unittest.cc)2
-rw-r--r--courgette/testdata/en-US.dll (renamed from third_party/courgette/testdata/en-US.dll)bin73216 -> 73216 bytes
-rw-r--r--courgette/testdata/setup1.exe (renamed from third_party/courgette/testdata/setup1.exe)bin967168 -> 967168 bytes
-rw-r--r--courgette/testdata/setup2.exe (renamed from third_party/courgette/testdata/setup2.exe)bin965632 -> 965632 bytes
-rw-r--r--courgette/third_party/LICENCE (renamed from third_party/courgette/LICENCE.bsdiff)0
-rw-r--r--courgette/third_party/README.chromium23
-rw-r--r--courgette/third_party/bsdiff.h (renamed from third_party/courgette/bsdiff.h)0
-rw-r--r--courgette/third_party/bsdiff_apply.cc (renamed from third_party/courgette/bsdiff_apply.cc)6
-rw-r--r--courgette/third_party/bsdiff_create.cc (renamed from third_party/courgette/bsdiff_create.cc)6
-rw-r--r--courgette/win32_x86_generator.h (renamed from third_party/courgette/win32_x86_generator.h)252
-rw-r--r--courgette/win32_x86_patcher.h (renamed from third_party/courgette/win32_x86_patcher.h)190
50 files changed, 4834 insertions, 4724 deletions
diff --git a/build/all.gyp b/build/all.gyp
index a2ef584..f2c85a8 100644
--- a/build/all.gyp
+++ b/build/all.gyp
@@ -59,7 +59,7 @@
['OS=="win"', {
'dependencies': [
'../sandbox/sandbox.gyp:*',
- '../third_party/courgette/courgette.gyp:*',
+ '../courgette/courgette.gyp:*',
'../webkit/activex_shim/activex_shim.gyp:*',
'../webkit/activex_shim_dll/activex_shim_dll.gyp:*',
'temp_gyp/breakpad.gyp:*',
diff --git a/chrome/chrome.sln b/chrome/chrome.sln
index 4be747b..ce4d621 100644
--- a/chrome/chrome.sln
+++ b/chrome/chrome.sln
@@ -1487,9 +1487,9 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tcmalloc", "..\third_party\
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "app", "..\app\app.vcproj", "{4631946D-7D5F-44BD-A5A8-504C0A7033BE}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_lib", "..\third_party\courgette\courgette_lib.vcproj", "{9A72A362-E617-4205-B9F2-43C6FB280FA1}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_lib", "..\courgette\courgette_lib.vcproj", "{9A72A362-E617-4205-B9F2-43C6FB280FA1}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_fuzz", "..\third_party\courgette\courgette_fuzz.vcproj", "{57C27529-8CA9-4FC3-9C02-DA05B172F785}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_fuzz", "..\courgette\courgette_fuzz.vcproj", "{57C27529-8CA9-4FC3-9C02-DA05B172F785}"
ProjectSection(ProjectDependencies) = postProject
{1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
{8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
@@ -1498,7 +1498,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_fuzz", "..\third_
{F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
EndProjectSection
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_unittests", "..\third_party\courgette\courgette_unittests.vcproj", "{24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_unittests", "..\courgette\courgette_unittests.vcproj", "{24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}"
ProjectSection(ProjectDependencies) = postProject
{1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
{8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
@@ -1507,7 +1507,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_unittests", "..\t
{F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
EndProjectSection
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_tool", "..\third_party\courgette\courgette_tool.vcproj", "{4EA8CE12-9C6F-45E5-9D08-720383FE3685}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette", "..\courgette\courgette.vcproj", "{4EA8CE12-9C6F-45E5-9D08-720383FE3685}"
ProjectSection(ProjectDependencies) = postProject
{1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
{8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
@@ -1515,7 +1515,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_tool", "..\third_
{F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
EndProjectSection
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_minimal_tool", "..\third_party\courgette\courgette_minimal_tool.vcproj", "{EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_minimal_tool", "..\courgette\courgette_minimal_tool.vcproj", "{EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}"
ProjectSection(ProjectDependencies) = postProject
{1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
{8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
diff --git a/third_party/courgette/adjustment_method.cc b/courgette/adjustment_method.cc
index 8f6caef..48e7cc0 100644
--- a/third_party/courgette/adjustment_method.cc
+++ b/courgette/adjustment_method.cc
@@ -1,703 +1,703 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/courgette/adjustment_method.h"
-
-#include <algorithm>
-#include <list>
-#include <map>
-#include <set>
-#include <string>
-#include <vector>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "base/string_util.h"
-
-#include "third_party/courgette/assembly_program.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/encoded_program.h"
-#include "third_party/courgette/image_info.h"
-
-namespace courgette {
-
-// We have three discretionary information logging levels for algorithm
-// development. For now just configure with #defines.
-// TODO(sra): make dependent of some configurable setting.
-#define NO_LOG DLOG_IF(INFO, false)
-// #define ALOG1 LOG(INFO)
-// #define ALOG2 LOG(INFO)
-// #define ALOG3 LOG(INFO)
-#define ALOG1 NO_LOG
-#define ALOG2 NO_LOG
-#define ALOG3 NO_LOG
-
-////////////////////////////////////////////////////////////////////////////////
-
-class NullAdjustmentMethod : public AdjustmentMethod {
- bool Adjust(const AssemblyProgram& model, AssemblyProgram* program) {
- return true;
- }
-};
-
-////////////////////////////////////////////////////////////////////////////////
-
-// The purpose of adjustment is to assign indexes to Labels of a program 'p' to
-// make the sequence of indexes similar to a 'model' program 'm'. Labels
-// themselves don't have enough information to do this job, so we work with a
-// LabelInfo surrogate for each label.
-//
-class LabelInfo {
- public:
- Label* label_; // The label that this info a surrogate for.
-
- // Information used only in debugging messages.
- uint32 is_model_ : 1; // Is the label in the model?
- uint32 debug_index_ : 31; // An unique small number for naming the label.
-
- uint32 refs_; // Number of times this Label is referenced.
-
- LabelInfo* assignment_; // Label from other program corresponding to this.
-
- // LabelInfos are in a doubly linked list ordered by address (label_->rva_) so
- // we can quickly find Labels adjacent in address order.
- LabelInfo* next_addr_; // Label(Info) at next highest address.
- LabelInfo* prev_addr_; // Label(Info) at next lowest address.
-
- std::vector<uint32> positions_; // Offsets into the trace of references.
-
- // Just a no-argument constructor and copy constructor. Actual LabelInfo
- // objects are allocated in std::pair structs in a std::map.
- LabelInfo()
- : label_(NULL), is_model_(false), debug_index_(0), refs_(0),
- assignment_(NULL),
- next_addr_(NULL),
- prev_addr_(NULL) {}
-
- private:
- void operator=(const LabelInfo*); // Disallow assignment only.
-
- // Public compiler generated copy constructor is needed to constuct
- // std::pair<Label*, LabelInfo> so that fresh LabelInfos can be allocated
- // inside a std::map.
-};
-
-struct OrderLabelInfoByAddressAscending {
- bool operator()(const LabelInfo* a, const LabelInfo* b) const {
- return a->label_->rva_ < b->label_->rva_;
- }
-};
-
-static std::string ToString(LabelInfo* info) {
- std::string s;
- StringAppendF(&s, "%c%d", "pm"[info->is_model_], info->debug_index_);
- if (info->label_->index_ != Label::kNoIndex)
- StringAppendF(&s, " (%d)", info->label_->index_);
-
- StringAppendF(&s, " #%u", info->refs_);
- return s;
-}
-
-// General graph matching is exponential, essentially trying all permutations.
-// The exponential algorithm can be made faster by avoiding consideration of
-// impossible or unlikely matches. We can make the matching practical by eager
-// matching - by looking for likely matches and commiting to them, and using the
-// committed assignment as the basis for further matching.
-//
-// The basic eager graph-matching assignment is based on several ideas:
-//
-// * The strongest match will be for parts of the program that have not
-// changed. If part of a program has not changed, then the number of
-// references to a label will be the same, and corresponding pairs of
-// adjacent labels will have the same RVA difference.
-//
-// * Some assignments are 'obvious' if you look at the distribution. Example:
-// if both the program and the model have a label that is referred to much
-// more often than the next most refered-to label, it is likely the two
-// labels correspond.
-//
-// * If a label from the program corresponds to a label in the model, it is
-// likely that the labels near the corresponding labels also match. A
-// conservative way of extending the match is to assign only those labels
-// which have exactly the same address offset and reference count.
-//
-// * If two labels correspond, then we can try to match up the references
-// before and after the labels in the reference stream. For this to be
-// practical, the number of references has to be small, e.g. each label has
-// exactly one reference.
-//
-
-// Note: we also tried a completely different approach: random assignment
-// followed by simulated annealing. This produced similar results. The results
-// were not as good for very small differences because the simulated annealing
-// never quite hit the groove. And simulated annealing was several orders of
-// magnitude slower.
-
-
-// TRIE node for suffix strings in the label reference sequence.
-//
-// We dynamically build a trie for both the program and model, growing the trie
-// as necessary. The trie node for a (possibly) empty string of label
-// references contains the distribution of labels following the string. The
-// roots node (for the empty string) thus contains the simple distribution of
-// labels within the label reference stream.
-
-struct Node {
- Node(LabelInfo* in_edge, Node* prev)
- : in_edge_(in_edge), prev_(prev), count_(0),
- in_queue_(false) {
- length_ = 1 + (prev_ ? prev_->length_ : 0);
- }
- LabelInfo* in_edge_; //
- Node* prev_; // Node at shorter length.
- int count_; // Frequency of this path in Trie.
- int length_;
- typedef std::map<LabelInfo*, Node*> Edges;
- Edges edges_;
- std::vector<int> places_; // Indexes into sequence of this item.
- std::list<Node*> edges_in_frequency_order;
-
- bool in_queue_;
- bool Extended() const { return edges_.size() > 0; }
-
- uint32 Weight() const {
- return edges_in_frequency_order.front()->count_;
- }
-};
-
-static std::string ToString(Node* node) {
- std::vector<std::string> prefix;
- for (Node* n = node; n->prev_; n = n->prev_)
- prefix.push_back(ToString(n->in_edge_));
-
- std::string s;
- s += "{";
- const char* sep = "";
- while (!prefix.empty()) {
- s += sep;
- sep = ",";
- s += prefix.back();
- prefix.pop_back();
- }
-
- s += StringPrintf("%u", node->count_);
- s += " @";
- s += Uint64ToString(node->edges_in_frequency_order.size());
- s += "}";
- return s;
-}
-
-typedef std::vector<LabelInfo*> Trace;
-
-struct OrderNodeByCountDecreasing {
- bool operator()(Node* a, Node* b) const {
- if (a->count_ != b->count_)
- return (a->count_) > (b->count_);
- return a->places_.at(0) < b->places_.at(0); // Prefer first occuring.
- }
-};
-
-struct OrderNodeByWeightDecreasing {
- bool operator()(Node* a, Node* b) const {
- // (Maybe tie-break on total count, followed by lowest assigned node indexes
- // in path.)
- uint32 a_weight = a->Weight();
- uint32 b_weight = b->Weight();
- if (a_weight != b_weight)
- return a_weight > b_weight;
- if (a->length_ != b->length_)
- return a->length_ > b->length_; // Prefer longer.
- return a->places_.at(0) < b->places_.at(0); // Prefer first occuring.
- }
-};
-
-typedef std::set<Node*, OrderNodeByWeightDecreasing> NodeQueue;
-
-class AssignmentProblem {
- public:
- AssignmentProblem(const Trace& model,
- const Trace& problem)
- : m_trace_(model),
- p_trace_(problem) {
- }
-
- ~AssignmentProblem() {
- for (size_t i = 0; i < all_nodes_.size(); ++i)
- delete all_nodes_[i];
- }
-
- bool Solve() {
- m_root_ = MakeRootNode(m_trace_);
- p_root_ = MakeRootNode(p_trace_);
- AddToQueue(p_root_);
-
- while (!worklist_.empty()) {
- Node* node = *worklist_.begin();
- node->in_queue_ = false;
- worklist_.erase(node);
- TrySolveNode(node);
- }
-
- ALOG1 << unsolved_.size() << " unsolved items";
- return true;
- }
-
- private:
- void AddToQueue(Node* node) {
- if (node->length_ >= 10) {
- ALOG3 << "Length clipped " << ToString(node->prev_);
- return;
- }
- if (node->in_queue_) {
- LOG(ERROR) << "Double add " << ToString(node);
- return;
- }
- // just to be sure data for prioritizing is available
- ExtendNode(node, p_trace_);
- // SkipCommittedLabels(node);
- if (node->edges_in_frequency_order.empty())
- return;
- node->in_queue_ = true;
- worklist_.insert(node);
- }
-
- void SkipCommittedLabels(Node* node) {
- ExtendNode(node, p_trace_);
- uint32 skipped = 0;
- while (!node->edges_in_frequency_order.empty() &&
- node->edges_in_frequency_order.front()->in_edge_->assignment_) {
- ++skipped;
- node->edges_in_frequency_order.pop_front();
- }
- if (skipped > 0)
- ALOG3 << "Skipped " << skipped << " at " << ToString(node);
- }
-
- void TrySolveNode(Node* p_node) {
- Node* front = p_node->edges_in_frequency_order.front();
- if (front->in_edge_->assignment_) {
- p_node->edges_in_frequency_order.pop_front();
- AddToQueue(front);
- AddToQueue(p_node);
- return;
- }
-
- // Compare frequencies of unassigned edges, and either make
- // assignment(s) or move node to unsolved list
-
- Node* m_node = FindModelNode(p_node);
-
- if (m_node == NULL) {
- ALOG1 << "Can't find model node";
- unsolved_.insert(p_node);
- return;
- }
- ExtendNode(m_node, m_trace_);
-
- // Lets just try greedy
-
- SkipCommittedLabels(m_node);
- if (m_node->edges_in_frequency_order.empty()) {
- ALOG3 << "Punting, no elements left in model vs "
- << p_node->edges_in_frequency_order.size();
- unsolved_.insert(p_node);
- return;
- }
- Node* m_match = m_node->edges_in_frequency_order.front();
- Node* p_match = p_node->edges_in_frequency_order.front();
-
- if (p_match->count_ > 1.1 * m_match->count_ ||
- m_match->count_ > 1.1 * p_match->count_) {
- ALOG2 << "Tricky distribution "
- << p_match->count_ << ":" << m_match->count_ << " "
- << ToString(p_match) << " vs " << ToString(m_match);
- return;
- }
-
- m_node->edges_in_frequency_order.pop_front();
- p_node->edges_in_frequency_order.pop_front();
-
- LabelInfo* p_label_info = p_match->in_edge_;
- LabelInfo* m_label_info = m_match->in_edge_;
- int m_index = p_label_info->label_->index_;
- if (m_index != Label::kNoIndex) {
- ALOG1 << "Cant use unassigned label from model " << m_index;
- unsolved_.insert(p_node);
- return;
- }
-
- Assign(p_label_info, m_label_info);
-
- AddToQueue(p_match); // find matches within new match
- AddToQueue(p_node); // and more matches within this node
- }
-
- void Assign(LabelInfo* p_info, LabelInfo* m_info) {
- AssignOne(p_info, m_info);
- ALOG3 << "Assign " << ToString(p_info) << " := " << ToString(m_info);
- // Now consider unassigned adjacent addresses
- TryExtendAssignment(p_info, m_info);
- }
-
- void AssignOne(LabelInfo* p_info, LabelInfo* m_info) {
- p_info->label_->index_ = m_info->label_->index_;
-
- // Mark as assigned
- m_info->assignment_ = p_info;
- p_info->assignment_ = m_info;
- }
-
- void TryExtendAssignment(LabelInfo* p_info, LabelInfo* m_info) {
- RVA m_rva_base = m_info->label_->rva_;
- RVA p_rva_base = p_info->label_->rva_;
-
- LabelInfo* m_info_next = m_info->next_addr_;
- LabelInfo* p_info_next = p_info->next_addr_;
- for ( ; m_info_next && p_info_next; ) {
- if (m_info_next->assignment_)
- break;
-
- RVA m_rva = m_info_next->label_->rva_;
- RVA p_rva = p_info_next->label_->rva_;
-
- if (m_rva - m_rva_base != p_rva - p_rva_base) {
- // previous label was pointing to something that is different size
- break;
- }
- LabelInfo* m_info_next_next = m_info_next->next_addr_;
- LabelInfo* p_info_next_next = p_info_next->next_addr_;
- if (m_info_next_next && p_info_next_next) {
- RVA m_rva_next = m_info_next_next->label_->rva_;
- RVA p_rva_next = p_info_next_next->label_->rva_;
- if (m_rva_next - m_rva != p_rva_next - p_rva) {
- // Since following labels are no longer in address lockstep, assume
- // this address has a difference.
- break;
- }
- }
-
- // The label has inconsistent numbers of references, it is probably not
- // the same thing.
- if (m_info_next->refs_ != p_info_next->refs_) {
- break;
- }
-
- ALOG3 << " Extending assignment -> "
- << ToString(p_info_next) << " := " << ToString(m_info_next);
-
- AssignOne(p_info_next, m_info_next);
-
- if (p_info_next->refs_ == m_info_next->refs_ &&
- p_info_next->refs_ == 1) {
- TryExtendSequence(p_info_next->positions_[0],
- m_info_next->positions_[0]);
- TryExtendSequenceBackwards(p_info_next->positions_[0],
- m_info_next->positions_[0]);
- }
-
- p_info_next = p_info_next_next;
- m_info_next = m_info_next_next;
- }
-
- LabelInfo* m_info_prev = m_info->prev_addr_;
- LabelInfo* p_info_prev = p_info->prev_addr_;
- for ( ; m_info_prev && p_info_prev; ) {
- if (m_info_prev->assignment_)
- break;
-
- RVA m_rva = m_info_prev->label_->rva_;
- RVA p_rva = p_info_prev->label_->rva_;
-
- if (m_rva - m_rva_base != p_rva - p_rva_base) {
- // previous label was pointing to something that is different size
- break;
- }
- LabelInfo* m_info_prev_prev = m_info_prev->prev_addr_;
- LabelInfo* p_info_prev_prev = p_info_prev->prev_addr_;
-
- // The the label has inconsistent numbers of references, it is
- // probably not the same thing
- if (m_info_prev->refs_ != p_info_prev->refs_) {
- break;
- }
-
- AssignOne(p_info_prev, m_info_prev);
- ALOG3 << " Extending assignment <- " << ToString(p_info_prev) << " := "
- << ToString(m_info_prev);
-
- p_info_prev = p_info_prev_prev;
- m_info_prev = m_info_prev_prev;
- }
- }
-
- uint32 TryExtendSequence(uint32 p_pos_start, uint32 m_pos_start) {
- uint32 p_pos = p_pos_start + 1;
- uint32 m_pos = m_pos_start + 1;
-
- while (p_pos < p_trace_.size() && m_pos < m_trace_.size()) {
- LabelInfo* p_info = p_trace_[p_pos];
- LabelInfo* m_info = m_trace_[m_pos];
-
- // To match, either (1) both are assigned or (2) both are unassigned.
- if ((p_info->assignment_ == NULL) != (m_info->assignment_ == NULL))
- break;
-
- // If they are assigned, it needs to be consistent (same index).
- if (p_info->assignment_ && m_info->assignment_) {
- if (p_info->label_->index_ != m_info->label_->index_)
- break;
- ++p_pos;
- ++m_pos;
- continue;
- }
-
- if (p_info->refs_ != m_info->refs_)
- break;
-
- AssignOne(p_info, m_info);
- ALOG3 << " Extending assignment seq"
- << "[+" << p_pos - p_pos_start << "]"
- << " -> "
- << ToString(p_info) << " := " << ToString(m_info);
-
- ++p_pos;
- ++m_pos;
- }
-
- return p_pos - p_pos_start;
- }
-
- uint32 TryExtendSequenceBackwards(uint32 p_pos_start, uint32 m_pos_start) {
- if (p_pos_start == 0 || m_pos_start == 0)
- return 0;
-
- uint32 p_pos = p_pos_start - 1;
- uint32 m_pos = m_pos_start - 1;
-
- while (p_pos > 0 && m_pos > 0) {
- LabelInfo* p_info = p_trace_[p_pos];
- LabelInfo* m_info = m_trace_[m_pos];
-
- if ((p_info->assignment_ == NULL) != (m_info->assignment_ == NULL))
- break;
-
- if (p_info->assignment_ && m_info->assignment_) {
- if (p_info->label_->index_ != m_info->label_->index_)
- break;
- --p_pos;
- --m_pos;
- continue;
- }
-
- if (p_info->refs_ != m_info->refs_)
- break;
-
- AssignOne(p_info, m_info);
- ALOG3 << " Extending assignment seq"
- << "[-" << p_pos_start - p_pos << "]"
- << " <- "
- << ToString(p_info) << " := " << ToString(m_info);
-
- --p_pos;
- --m_pos;
- }
-
- return p_pos - p_pos_start;
- }
-
- Node* FindModelNode(Node* node) {
- if (node->prev_ == NULL)
- return m_root_;
-
- Node* m_parent = FindModelNode(node->prev_);
- if (m_parent == NULL) {
- return NULL;
- }
-
- ExtendNode(m_parent, m_trace_);
-
- LabelInfo* p_label = node->in_edge_;
- LabelInfo* m_label = p_label->assignment_;
- if (m_label == NULL) {
- ALOG1 << "Expected assigned prefix";
- return NULL;
- }
-
- Node::Edges::iterator e = m_parent->edges_.find(m_label);
- if (e == m_parent->edges_.end()) {
- ALOG2 << "Expected defined edge in parent";
- return NULL;
- }
-
- return e->second;
- }
-
- Node* MakeRootNode(const Trace& trace) {
- Node* node = new Node(NULL, NULL);
- all_nodes_.push_back(node);
- for (size_t i = 0; i < trace.size(); ++i) {
- ++node->count_;
- node->places_.push_back(i);
- }
- return node;
- }
-
- void ExtendNode(Node* node, const Trace& trace) {
- // Make sure trie is filled in at this node.
- if (node->Extended())
- return;
- for (size_t i = 0; i < node->places_.size(); ++i) {
- uint32 index = node->places_.at(i);
- if (index < trace.size()) {
- LabelInfo* item = trace.at(index);
- Node*& slot = node->edges_[item];
- if (slot == NULL) {
- slot = new Node(item, node);
- all_nodes_.push_back(slot);
- node->edges_in_frequency_order.push_back(slot);
- }
- slot->places_.push_back(index + 1);
- ++slot->count_;
- }
- }
- node->edges_in_frequency_order.sort(OrderNodeByCountDecreasing());
- }
-
- const Trace& m_trace_;
- const Trace& p_trace_;
- Node* m_root_;
- Node* p_root_;
-
- NodeQueue worklist_;
- NodeQueue unsolved_;
-
- std::vector<Node*> all_nodes_;
-
- DISALLOW_COPY_AND_ASSIGN(AssignmentProblem);
-};
-
-class GraphAdjuster : public AdjustmentMethod {
- public:
- GraphAdjuster() {}
- ~GraphAdjuster() {}
-
- bool Adjust(const AssemblyProgram& model, AssemblyProgram* program) {
- LOG(INFO) << "GraphAdjuster::Adjust";
- prog_ = program;
- model_ = &model;
- debug_label_index_gen_ = 0;
- return Finish();
- }
-
- bool Finish() {
- prog_->UnassignIndexes();
- CollectTraces(model_, &model_abs32_, &model_rel32_, true);
- CollectTraces(prog_, &prog_abs32_, &prog_rel32_, false);
- Solve(model_abs32_, prog_abs32_);
- Solve(model_rel32_, prog_rel32_);
- prog_->AssignRemainingIndexes();
- return true;
- }
-
- private:
-
- void CollectTraces(const AssemblyProgram* program, Trace* abs32, Trace* rel32,
- bool is_model) {
- const std::vector<Instruction*>& instructions = program->instructions();
- for (size_t i = 0; i < instructions.size(); ++i) {
- Instruction* instruction = instructions.at(i);
- if (Label* label = program->InstructionAbs32Label(instruction))
- ReferenceLabel(abs32, label, is_model);
- if (Label* label = program->InstructionRel32Label(instruction))
- ReferenceLabel(rel32, label, is_model);
- }
- // TODO(sra): we could simply append all the labels in index order to
- // incorporate some costing for entropy (bigger deltas) that will be
- // introduced into the label address table by non-monotonic ordering. This
- // would have some knock-on effects to parts of the algorithm that work on
- // single-occurence labels.
- }
-
- void Solve(const Trace& model, const Trace& problem) {
- LinkLabelInfos(model);
- LinkLabelInfos(problem);
- AssignmentProblem a(model, problem);
- a.Solve();
- }
-
- void LinkLabelInfos(const Trace& trace) {
- typedef std::set<LabelInfo*, OrderLabelInfoByAddressAscending> Ordered;
- Ordered ordered;
- for (Trace::const_iterator p = trace.begin(); p != trace.end(); ++p)
- ordered.insert(*p);
- LabelInfo* prev = NULL;
- for (Ordered::iterator p = ordered.begin(); p != ordered.end(); ++p) {
- LabelInfo* curr = *p;
- if (prev) prev->next_addr_ = curr;
- curr->prev_addr_ = prev;
- prev = curr;
-
- if (curr->positions_.size() != curr->refs_)
- NOTREACHED();
- }
- }
-
- void ReferenceLabel(Trace* trace, Label* label, bool is_model) {
- trace->push_back(MakeLabelInfo(label, is_model, trace->size()));
- }
-
- LabelInfo* MakeLabelInfo(Label* label, bool is_model, uint32 position) {
- LabelInfo& slot = label_infos_[label];
- if (slot.label_ == NULL) {
- slot.label_ = label;
- slot.is_model_ = is_model;
- slot.debug_index_ = ++debug_label_index_gen_;
- }
- slot.positions_.push_back(position);
- ++slot.refs_;
- return &slot;
- }
-
- AssemblyProgram* prog_; // Program to be adjusted, owned by caller.
- const AssemblyProgram* model_; // Program to be mimicked, owned by caller.
-
- Trace model_abs32_;
- Trace model_rel32_;
- Trace prog_abs32_;
- Trace prog_rel32_;
-
- int debug_label_index_gen_;
-
- // Note LabelInfo is allocated inside map, so the LabelInfo lifetimes are
- // managed by the map.
- std::map<Label*, LabelInfo> label_infos_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(GraphAdjuster);
-};
-
-
-////////////////////////////////////////////////////////////////////////////////
-
-void AdjustmentMethod::Destroy() { delete this; }
-
-AdjustmentMethod* AdjustmentMethod::MakeNullAdjustmentMethod() {
- return new NullAdjustmentMethod();
-}
-
-AdjustmentMethod* AdjustmentMethod::MakeProductionAdjustmentMethod() {
- return new GraphAdjuster();
-}
-
-Status Adjust(const AssemblyProgram& model, AssemblyProgram* program) {
- AdjustmentMethod* method = AdjustmentMethod::MakeProductionAdjustmentMethod();
- bool ok = method->Adjust(model, program);
- method->Destroy();
- if (ok)
- return C_OK;
- else
- return C_ADJUSTMENT_FAILED;
-}
-
-} // namespace courgette
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "courgette/adjustment_method.h"
+
+#include <algorithm>
+#include <list>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "base/string_util.h"
+
+#include "courgette/assembly_program.h"
+#include "courgette/courgette.h"
+#include "courgette/encoded_program.h"
+#include "courgette/image_info.h"
+
+namespace courgette {
+
+// We have three discretionary information logging levels for algorithm
+// development. For now just configure with #defines.
+// TODO(sra): make dependent of some configurable setting.
+#define NO_LOG DLOG_IF(INFO, false)
+// #define ALOG1 LOG(INFO)
+// #define ALOG2 LOG(INFO)
+// #define ALOG3 LOG(INFO)
+#define ALOG1 NO_LOG
+#define ALOG2 NO_LOG
+#define ALOG3 NO_LOG
+
+////////////////////////////////////////////////////////////////////////////////
+
+class NullAdjustmentMethod : public AdjustmentMethod {
+ bool Adjust(const AssemblyProgram& model, AssemblyProgram* program) {
+ return true;
+ }
+};
+
+////////////////////////////////////////////////////////////////////////////////
+
+// The purpose of adjustment is to assign indexes to Labels of a program 'p' to
+// make the sequence of indexes similar to a 'model' program 'm'. Labels
+// themselves don't have enough information to do this job, so we work with a
+// LabelInfo surrogate for each label.
+//
+class LabelInfo {
+ public:
+ Label* label_; // The label that this info a surrogate for.
+
+ // Information used only in debugging messages.
+ uint32 is_model_ : 1; // Is the label in the model?
+ uint32 debug_index_ : 31; // An unique small number for naming the label.
+
+ uint32 refs_; // Number of times this Label is referenced.
+
+ LabelInfo* assignment_; // Label from other program corresponding to this.
+
+ // LabelInfos are in a doubly linked list ordered by address (label_->rva_) so
+ // we can quickly find Labels adjacent in address order.
+ LabelInfo* next_addr_; // Label(Info) at next highest address.
+ LabelInfo* prev_addr_; // Label(Info) at next lowest address.
+
+ std::vector<uint32> positions_; // Offsets into the trace of references.
+
+ // Just a no-argument constructor and copy constructor. Actual LabelInfo
+ // objects are allocated in std::pair structs in a std::map.
+ LabelInfo()
+ : label_(NULL), is_model_(false), debug_index_(0), refs_(0),
+ assignment_(NULL),
+ next_addr_(NULL),
+ prev_addr_(NULL) {}
+
+ private:
+ void operator=(const LabelInfo*); // Disallow assignment only.
+
+ // Public compiler generated copy constructor is needed to constuct
+ // std::pair<Label*, LabelInfo> so that fresh LabelInfos can be allocated
+ // inside a std::map.
+};
+
+struct OrderLabelInfoByAddressAscending {
+ bool operator()(const LabelInfo* a, const LabelInfo* b) const {
+ return a->label_->rva_ < b->label_->rva_;
+ }
+};
+
+static std::string ToString(LabelInfo* info) {
+ std::string s;
+ StringAppendF(&s, "%c%d", "pm"[info->is_model_], info->debug_index_);
+ if (info->label_->index_ != Label::kNoIndex)
+ StringAppendF(&s, " (%d)", info->label_->index_);
+
+ StringAppendF(&s, " #%u", info->refs_);
+ return s;
+}
+
+// General graph matching is exponential, essentially trying all permutations.
+// The exponential algorithm can be made faster by avoiding consideration of
+// impossible or unlikely matches. We can make the matching practical by eager
+// matching - by looking for likely matches and commiting to them, and using the
+// committed assignment as the basis for further matching.
+//
+// The basic eager graph-matching assignment is based on several ideas:
+//
+// * The strongest match will be for parts of the program that have not
+// changed. If part of a program has not changed, then the number of
+// references to a label will be the same, and corresponding pairs of
+// adjacent labels will have the same RVA difference.
+//
+// * Some assignments are 'obvious' if you look at the distribution. Example:
+// if both the program and the model have a label that is referred to much
+// more often than the next most refered-to label, it is likely the two
+// labels correspond.
+//
+// * If a label from the program corresponds to a label in the model, it is
+// likely that the labels near the corresponding labels also match. A
+// conservative way of extending the match is to assign only those labels
+// which have exactly the same address offset and reference count.
+//
+// * If two labels correspond, then we can try to match up the references
+// before and after the labels in the reference stream. For this to be
+// practical, the number of references has to be small, e.g. each label has
+// exactly one reference.
+//
+
+// Note: we also tried a completely different approach: random assignment
+// followed by simulated annealing. This produced similar results. The results
+// were not as good for very small differences because the simulated annealing
+// never quite hit the groove. And simulated annealing was several orders of
+// magnitude slower.
+
+
+// TRIE node for suffix strings in the label reference sequence.
+//
+// We dynamically build a trie for both the program and model, growing the trie
+// as necessary. The trie node for a (possibly) empty string of label
+// references contains the distribution of labels following the string. The
+// roots node (for the empty string) thus contains the simple distribution of
+// labels within the label reference stream.
+
+struct Node {
+ Node(LabelInfo* in_edge, Node* prev)
+ : in_edge_(in_edge), prev_(prev), count_(0),
+ in_queue_(false) {
+ length_ = 1 + (prev_ ? prev_->length_ : 0);
+ }
+ LabelInfo* in_edge_; //
+ Node* prev_; // Node at shorter length.
+ int count_; // Frequency of this path in Trie.
+ int length_;
+ typedef std::map<LabelInfo*, Node*> Edges;
+ Edges edges_;
+ std::vector<int> places_; // Indexes into sequence of this item.
+ std::list<Node*> edges_in_frequency_order;
+
+ bool in_queue_;
+ bool Extended() const { return edges_.size() > 0; }
+
+ uint32 Weight() const {
+ return edges_in_frequency_order.front()->count_;
+ }
+};
+
+static std::string ToString(Node* node) {
+ std::vector<std::string> prefix;
+ for (Node* n = node; n->prev_; n = n->prev_)
+ prefix.push_back(ToString(n->in_edge_));
+
+ std::string s;
+ s += "{";
+ const char* sep = "";
+ while (!prefix.empty()) {
+ s += sep;
+ sep = ",";
+ s += prefix.back();
+ prefix.pop_back();
+ }
+
+ s += StringPrintf("%u", node->count_);
+ s += " @";
+ s += Uint64ToString(node->edges_in_frequency_order.size());
+ s += "}";
+ return s;
+}
+
+typedef std::vector<LabelInfo*> Trace;
+
+struct OrderNodeByCountDecreasing {
+ bool operator()(Node* a, Node* b) const {
+ if (a->count_ != b->count_)
+ return (a->count_) > (b->count_);
+ return a->places_.at(0) < b->places_.at(0); // Prefer first occuring.
+ }
+};
+
+struct OrderNodeByWeightDecreasing {
+ bool operator()(Node* a, Node* b) const {
+ // (Maybe tie-break on total count, followed by lowest assigned node indexes
+ // in path.)
+ uint32 a_weight = a->Weight();
+ uint32 b_weight = b->Weight();
+ if (a_weight != b_weight)
+ return a_weight > b_weight;
+ if (a->length_ != b->length_)
+ return a->length_ > b->length_; // Prefer longer.
+ return a->places_.at(0) < b->places_.at(0); // Prefer first occuring.
+ }
+};
+
+typedef std::set<Node*, OrderNodeByWeightDecreasing> NodeQueue;
+
+class AssignmentProblem {
+ public:
+ AssignmentProblem(const Trace& model,
+ const Trace& problem)
+ : m_trace_(model),
+ p_trace_(problem) {
+ }
+
+ ~AssignmentProblem() {
+ for (size_t i = 0; i < all_nodes_.size(); ++i)
+ delete all_nodes_[i];
+ }
+
+ bool Solve() {
+ m_root_ = MakeRootNode(m_trace_);
+ p_root_ = MakeRootNode(p_trace_);
+ AddToQueue(p_root_);
+
+ while (!worklist_.empty()) {
+ Node* node = *worklist_.begin();
+ node->in_queue_ = false;
+ worklist_.erase(node);
+ TrySolveNode(node);
+ }
+
+ ALOG1 << unsolved_.size() << " unsolved items";
+ return true;
+ }
+
+ private:
+ void AddToQueue(Node* node) {
+ if (node->length_ >= 10) {
+ ALOG3 << "Length clipped " << ToString(node->prev_);
+ return;
+ }
+ if (node->in_queue_) {
+ LOG(ERROR) << "Double add " << ToString(node);
+ return;
+ }
+ // just to be sure data for prioritizing is available
+ ExtendNode(node, p_trace_);
+ // SkipCommittedLabels(node);
+ if (node->edges_in_frequency_order.empty())
+ return;
+ node->in_queue_ = true;
+ worklist_.insert(node);
+ }
+
+ void SkipCommittedLabels(Node* node) {
+ ExtendNode(node, p_trace_);
+ uint32 skipped = 0;
+ while (!node->edges_in_frequency_order.empty() &&
+ node->edges_in_frequency_order.front()->in_edge_->assignment_) {
+ ++skipped;
+ node->edges_in_frequency_order.pop_front();
+ }
+ if (skipped > 0)
+ ALOG3 << "Skipped " << skipped << " at " << ToString(node);
+ }
+
+ void TrySolveNode(Node* p_node) {
+ Node* front = p_node->edges_in_frequency_order.front();
+ if (front->in_edge_->assignment_) {
+ p_node->edges_in_frequency_order.pop_front();
+ AddToQueue(front);
+ AddToQueue(p_node);
+ return;
+ }
+
+ // Compare frequencies of unassigned edges, and either make
+ // assignment(s) or move node to unsolved list
+
+ Node* m_node = FindModelNode(p_node);
+
+ if (m_node == NULL) {
+ ALOG1 << "Can't find model node";
+ unsolved_.insert(p_node);
+ return;
+ }
+ ExtendNode(m_node, m_trace_);
+
+ // Lets just try greedy
+
+ SkipCommittedLabels(m_node);
+ if (m_node->edges_in_frequency_order.empty()) {
+ ALOG3 << "Punting, no elements left in model vs "
+ << p_node->edges_in_frequency_order.size();
+ unsolved_.insert(p_node);
+ return;
+ }
+ Node* m_match = m_node->edges_in_frequency_order.front();
+ Node* p_match = p_node->edges_in_frequency_order.front();
+
+ if (p_match->count_ > 1.1 * m_match->count_ ||
+ m_match->count_ > 1.1 * p_match->count_) {
+ ALOG2 << "Tricky distribution "
+ << p_match->count_ << ":" << m_match->count_ << " "
+ << ToString(p_match) << " vs " << ToString(m_match);
+ return;
+ }
+
+ m_node->edges_in_frequency_order.pop_front();
+ p_node->edges_in_frequency_order.pop_front();
+
+ LabelInfo* p_label_info = p_match->in_edge_;
+ LabelInfo* m_label_info = m_match->in_edge_;
+ int m_index = p_label_info->label_->index_;
+ if (m_index != Label::kNoIndex) {
+ ALOG1 << "Cant use unassigned label from model " << m_index;
+ unsolved_.insert(p_node);
+ return;
+ }
+
+ Assign(p_label_info, m_label_info);
+
+ AddToQueue(p_match); // find matches within new match
+ AddToQueue(p_node); // and more matches within this node
+ }
+
+ void Assign(LabelInfo* p_info, LabelInfo* m_info) {
+ AssignOne(p_info, m_info);
+ ALOG3 << "Assign " << ToString(p_info) << " := " << ToString(m_info);
+ // Now consider unassigned adjacent addresses
+ TryExtendAssignment(p_info, m_info);
+ }
+
+ void AssignOne(LabelInfo* p_info, LabelInfo* m_info) {
+ p_info->label_->index_ = m_info->label_->index_;
+
+ // Mark as assigned
+ m_info->assignment_ = p_info;
+ p_info->assignment_ = m_info;
+ }
+
+ void TryExtendAssignment(LabelInfo* p_info, LabelInfo* m_info) {
+ RVA m_rva_base = m_info->label_->rva_;
+ RVA p_rva_base = p_info->label_->rva_;
+
+ LabelInfo* m_info_next = m_info->next_addr_;
+ LabelInfo* p_info_next = p_info->next_addr_;
+ for ( ; m_info_next && p_info_next; ) {
+ if (m_info_next->assignment_)
+ break;
+
+ RVA m_rva = m_info_next->label_->rva_;
+ RVA p_rva = p_info_next->label_->rva_;
+
+ if (m_rva - m_rva_base != p_rva - p_rva_base) {
+ // previous label was pointing to something that is different size
+ break;
+ }
+ LabelInfo* m_info_next_next = m_info_next->next_addr_;
+ LabelInfo* p_info_next_next = p_info_next->next_addr_;
+ if (m_info_next_next && p_info_next_next) {
+ RVA m_rva_next = m_info_next_next->label_->rva_;
+ RVA p_rva_next = p_info_next_next->label_->rva_;
+ if (m_rva_next - m_rva != p_rva_next - p_rva) {
+ // Since following labels are no longer in address lockstep, assume
+ // this address has a difference.
+ break;
+ }
+ }
+
+ // The label has inconsistent numbers of references, it is probably not
+ // the same thing.
+ if (m_info_next->refs_ != p_info_next->refs_) {
+ break;
+ }
+
+ ALOG3 << " Extending assignment -> "
+ << ToString(p_info_next) << " := " << ToString(m_info_next);
+
+ AssignOne(p_info_next, m_info_next);
+
+ if (p_info_next->refs_ == m_info_next->refs_ &&
+ p_info_next->refs_ == 1) {
+ TryExtendSequence(p_info_next->positions_[0],
+ m_info_next->positions_[0]);
+ TryExtendSequenceBackwards(p_info_next->positions_[0],
+ m_info_next->positions_[0]);
+ }
+
+ p_info_next = p_info_next_next;
+ m_info_next = m_info_next_next;
+ }
+
+ LabelInfo* m_info_prev = m_info->prev_addr_;
+ LabelInfo* p_info_prev = p_info->prev_addr_;
+ for ( ; m_info_prev && p_info_prev; ) {
+ if (m_info_prev->assignment_)
+ break;
+
+ RVA m_rva = m_info_prev->label_->rva_;
+ RVA p_rva = p_info_prev->label_->rva_;
+
+ if (m_rva - m_rva_base != p_rva - p_rva_base) {
+ // previous label was pointing to something that is different size
+ break;
+ }
+ LabelInfo* m_info_prev_prev = m_info_prev->prev_addr_;
+ LabelInfo* p_info_prev_prev = p_info_prev->prev_addr_;
+
+ // The the label has inconsistent numbers of references, it is
+ // probably not the same thing
+ if (m_info_prev->refs_ != p_info_prev->refs_) {
+ break;
+ }
+
+ AssignOne(p_info_prev, m_info_prev);
+ ALOG3 << " Extending assignment <- " << ToString(p_info_prev) << " := "
+ << ToString(m_info_prev);
+
+ p_info_prev = p_info_prev_prev;
+ m_info_prev = m_info_prev_prev;
+ }
+ }
+
+ uint32 TryExtendSequence(uint32 p_pos_start, uint32 m_pos_start) {
+ uint32 p_pos = p_pos_start + 1;
+ uint32 m_pos = m_pos_start + 1;
+
+ while (p_pos < p_trace_.size() && m_pos < m_trace_.size()) {
+ LabelInfo* p_info = p_trace_[p_pos];
+ LabelInfo* m_info = m_trace_[m_pos];
+
+ // To match, either (1) both are assigned or (2) both are unassigned.
+ if ((p_info->assignment_ == NULL) != (m_info->assignment_ == NULL))
+ break;
+
+ // If they are assigned, it needs to be consistent (same index).
+ if (p_info->assignment_ && m_info->assignment_) {
+ if (p_info->label_->index_ != m_info->label_->index_)
+ break;
+ ++p_pos;
+ ++m_pos;
+ continue;
+ }
+
+ if (p_info->refs_ != m_info->refs_)
+ break;
+
+ AssignOne(p_info, m_info);
+ ALOG3 << " Extending assignment seq"
+ << "[+" << p_pos - p_pos_start << "]"
+ << " -> "
+ << ToString(p_info) << " := " << ToString(m_info);
+
+ ++p_pos;
+ ++m_pos;
+ }
+
+ return p_pos - p_pos_start;
+ }
+
+ uint32 TryExtendSequenceBackwards(uint32 p_pos_start, uint32 m_pos_start) {
+ if (p_pos_start == 0 || m_pos_start == 0)
+ return 0;
+
+ uint32 p_pos = p_pos_start - 1;
+ uint32 m_pos = m_pos_start - 1;
+
+ while (p_pos > 0 && m_pos > 0) {
+ LabelInfo* p_info = p_trace_[p_pos];
+ LabelInfo* m_info = m_trace_[m_pos];
+
+ if ((p_info->assignment_ == NULL) != (m_info->assignment_ == NULL))
+ break;
+
+ if (p_info->assignment_ && m_info->assignment_) {
+ if (p_info->label_->index_ != m_info->label_->index_)
+ break;
+ --p_pos;
+ --m_pos;
+ continue;
+ }
+
+ if (p_info->refs_ != m_info->refs_)
+ break;
+
+ AssignOne(p_info, m_info);
+ ALOG3 << " Extending assignment seq"
+ << "[-" << p_pos_start - p_pos << "]"
+ << " <- "
+ << ToString(p_info) << " := " << ToString(m_info);
+
+ --p_pos;
+ --m_pos;
+ }
+
+ return p_pos - p_pos_start;
+ }
+
+ Node* FindModelNode(Node* node) {
+ if (node->prev_ == NULL)
+ return m_root_;
+
+ Node* m_parent = FindModelNode(node->prev_);
+ if (m_parent == NULL) {
+ return NULL;
+ }
+
+ ExtendNode(m_parent, m_trace_);
+
+ LabelInfo* p_label = node->in_edge_;
+ LabelInfo* m_label = p_label->assignment_;
+ if (m_label == NULL) {
+ ALOG1 << "Expected assigned prefix";
+ return NULL;
+ }
+
+ Node::Edges::iterator e = m_parent->edges_.find(m_label);
+ if (e == m_parent->edges_.end()) {
+ ALOG2 << "Expected defined edge in parent";
+ return NULL;
+ }
+
+ return e->second;
+ }
+
+ Node* MakeRootNode(const Trace& trace) {
+ Node* node = new Node(NULL, NULL);
+ all_nodes_.push_back(node);
+ for (size_t i = 0; i < trace.size(); ++i) {
+ ++node->count_;
+ node->places_.push_back(i);
+ }
+ return node;
+ }
+
+ void ExtendNode(Node* node, const Trace& trace) {
+ // Make sure trie is filled in at this node.
+ if (node->Extended())
+ return;
+ for (size_t i = 0; i < node->places_.size(); ++i) {
+ uint32 index = node->places_.at(i);
+ if (index < trace.size()) {
+ LabelInfo* item = trace.at(index);
+ Node*& slot = node->edges_[item];
+ if (slot == NULL) {
+ slot = new Node(item, node);
+ all_nodes_.push_back(slot);
+ node->edges_in_frequency_order.push_back(slot);
+ }
+ slot->places_.push_back(index + 1);
+ ++slot->count_;
+ }
+ }
+ node->edges_in_frequency_order.sort(OrderNodeByCountDecreasing());
+ }
+
+ const Trace& m_trace_;
+ const Trace& p_trace_;
+ Node* m_root_;
+ Node* p_root_;
+
+ NodeQueue worklist_;
+ NodeQueue unsolved_;
+
+ std::vector<Node*> all_nodes_;
+
+ DISALLOW_COPY_AND_ASSIGN(AssignmentProblem);
+};
+
+class GraphAdjuster : public AdjustmentMethod {
+ public:
+ GraphAdjuster() {}
+ ~GraphAdjuster() {}
+
+ bool Adjust(const AssemblyProgram& model, AssemblyProgram* program) {
+ LOG(INFO) << "GraphAdjuster::Adjust";
+ prog_ = program;
+ model_ = &model;
+ debug_label_index_gen_ = 0;
+ return Finish();
+ }
+
+ bool Finish() {
+ prog_->UnassignIndexes();
+ CollectTraces(model_, &model_abs32_, &model_rel32_, true);
+ CollectTraces(prog_, &prog_abs32_, &prog_rel32_, false);
+ Solve(model_abs32_, prog_abs32_);
+ Solve(model_rel32_, prog_rel32_);
+ prog_->AssignRemainingIndexes();
+ return true;
+ }
+
+ private:
+
+ void CollectTraces(const AssemblyProgram* program, Trace* abs32, Trace* rel32,
+ bool is_model) {
+ const std::vector<Instruction*>& instructions = program->instructions();
+ for (size_t i = 0; i < instructions.size(); ++i) {
+ Instruction* instruction = instructions.at(i);
+ if (Label* label = program->InstructionAbs32Label(instruction))
+ ReferenceLabel(abs32, label, is_model);
+ if (Label* label = program->InstructionRel32Label(instruction))
+ ReferenceLabel(rel32, label, is_model);
+ }
+ // TODO(sra): we could simply append all the labels in index order to
+ // incorporate some costing for entropy (bigger deltas) that will be
+ // introduced into the label address table by non-monotonic ordering. This
+ // would have some knock-on effects to parts of the algorithm that work on
+ // single-occurence labels.
+ }
+
+ void Solve(const Trace& model, const Trace& problem) {
+ LinkLabelInfos(model);
+ LinkLabelInfos(problem);
+ AssignmentProblem a(model, problem);
+ a.Solve();
+ }
+
+ void LinkLabelInfos(const Trace& trace) {
+ typedef std::set<LabelInfo*, OrderLabelInfoByAddressAscending> Ordered;
+ Ordered ordered;
+ for (Trace::const_iterator p = trace.begin(); p != trace.end(); ++p)
+ ordered.insert(*p);
+ LabelInfo* prev = NULL;
+ for (Ordered::iterator p = ordered.begin(); p != ordered.end(); ++p) {
+ LabelInfo* curr = *p;
+ if (prev) prev->next_addr_ = curr;
+ curr->prev_addr_ = prev;
+ prev = curr;
+
+ if (curr->positions_.size() != curr->refs_)
+ NOTREACHED();
+ }
+ }
+
+ void ReferenceLabel(Trace* trace, Label* label, bool is_model) {
+ trace->push_back(MakeLabelInfo(label, is_model, trace->size()));
+ }
+
+ LabelInfo* MakeLabelInfo(Label* label, bool is_model, uint32 position) {
+ LabelInfo& slot = label_infos_[label];
+ if (slot.label_ == NULL) {
+ slot.label_ = label;
+ slot.is_model_ = is_model;
+ slot.debug_index_ = ++debug_label_index_gen_;
+ }
+ slot.positions_.push_back(position);
+ ++slot.refs_;
+ return &slot;
+ }
+
+ AssemblyProgram* prog_; // Program to be adjusted, owned by caller.
+ const AssemblyProgram* model_; // Program to be mimicked, owned by caller.
+
+ Trace model_abs32_;
+ Trace model_rel32_;
+ Trace prog_abs32_;
+ Trace prog_rel32_;
+
+ int debug_label_index_gen_;
+
+ // Note LabelInfo is allocated inside map, so the LabelInfo lifetimes are
+ // managed by the map.
+ std::map<Label*, LabelInfo> label_infos_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GraphAdjuster);
+};
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+void AdjustmentMethod::Destroy() { delete this; }
+
+AdjustmentMethod* AdjustmentMethod::MakeNullAdjustmentMethod() {
+ return new NullAdjustmentMethod();
+}
+
+AdjustmentMethod* AdjustmentMethod::MakeProductionAdjustmentMethod() {
+ return new GraphAdjuster();
+}
+
+Status Adjust(const AssemblyProgram& model, AssemblyProgram* program) {
+ AdjustmentMethod* method = AdjustmentMethod::MakeProductionAdjustmentMethod();
+ bool ok = method->Adjust(model, program);
+ method->Destroy();
+ if (ok)
+ return C_OK;
+ else
+ return C_ADJUSTMENT_FAILED;
+}
+
+} // namespace courgette
diff --git a/third_party/courgette/adjustment_method.h b/courgette/adjustment_method.h
index 2a5b0c7..8ca71e8 100644
--- a/third_party/courgette/adjustment_method.h
+++ b/courgette/adjustment_method.h
@@ -1,43 +1,42 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef COURGETTE_ADJUSTMENT_METHOD_H_
-#define COURGETTE_ADJUSTMENT_METHOD_H_
-
-#include "base/basictypes.h"
-
-namespace courgette {
-
-class AssemblyProgram;
-
-class AdjustmentMethod {
- public:
- // Factory methods for making adjusters.
-
- // Returns the adjustment method used in production.
- static AdjustmentMethod* MakeProductionAdjustmentMethod();
-
- // Returns and adjustement method that makes no adjustments.
- static AdjustmentMethod* MakeNullAdjustmentMethod();
-
-
- // Adjusts |program| to increase similarity to |model|. |program| can be
- // changed in any way provided that it still produces the same output when
- // assembled.
- virtual bool Adjust(const AssemblyProgram& model,
- AssemblyProgram* program) = 0;
-
- // Deletes 'this' adjustment method.
- virtual void Destroy();
-
- protected:
- AdjustmentMethod() {}
- virtual ~AdjustmentMethod() {}
-
- DISALLOW_COPY_AND_ASSIGN(AdjustmentMethod);
-};
-
-} // namespace courgette
-#endif // COURGETTE_ADJUSTMENT_METHOD_H_
-
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COURGETTE_ADJUSTMENT_METHOD_H_
+#define COURGETTE_ADJUSTMENT_METHOD_H_
+
+#include "base/basictypes.h"
+
+namespace courgette {
+
+class AssemblyProgram;
+
+class AdjustmentMethod {
+ public:
+ // Factory methods for making adjusters.
+
+ // Returns the adjustment method used in production.
+ static AdjustmentMethod* MakeProductionAdjustmentMethod();
+
+ // Returns and adjustement method that makes no adjustments.
+ static AdjustmentMethod* MakeNullAdjustmentMethod();
+
+
+ // Adjusts |program| to increase similarity to |model|. |program| can be
+ // changed in any way provided that it still produces the same output when
+ // assembled.
+ virtual bool Adjust(const AssemblyProgram& model,
+ AssemblyProgram* program) = 0;
+
+ // Deletes 'this' adjustment method.
+ virtual void Destroy();
+
+ protected:
+ AdjustmentMethod() {}
+ virtual ~AdjustmentMethod() {}
+
+ DISALLOW_COPY_AND_ASSIGN(AdjustmentMethod);
+};
+
+} // namespace courgette
+#endif // COURGETTE_ADJUSTMENT_METHOD_H_
diff --git a/third_party/courgette/adjustment_method_unittest.cc b/courgette/adjustment_method_unittest.cc
index 2048126..661b23d 100644
--- a/third_party/courgette/adjustment_method_unittest.cc
+++ b/courgette/adjustment_method_unittest.cc
@@ -1,109 +1,108 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <string>
-
-#include "base/path_service.h"
-#include "base/file_util.h"
-#include "base/string_util.h"
-
-#include "third_party/courgette/assembly_program.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
-
-#include "testing/gtest/include/gtest/gtest.h"
-
-class AdjustmentMethodTest : public testing::Test {
- public:
- void Test1() const;
-
- private:
- void SetUp() {
- }
-
- void TearDown() {
- }
-
- // Returns one of two similar a simple programs. They differ only in the
- // label assignment, so that it is possible to make them look identical.
- courgette::AssemblyProgram* MakeProgram(int kind) const {
- courgette::AssemblyProgram* prog = new courgette::AssemblyProgram();
- prog->set_image_base(0x00400000);
-
- courgette::Label* labelA = prog->FindOrMakeAbs32Label(0x00410000);
- courgette::Label* labelB = prog->FindOrMakeAbs32Label(0x00410004);
-
- prog->EmitAbs32(labelA);
- prog->EmitAbs32(labelA);
- prog->EmitAbs32(labelB);
- prog->EmitAbs32(labelA);
- prog->EmitAbs32(labelA);
- prog->EmitAbs32(labelB);
-
- if (kind == 0) {
- labelA->index_ = 0;
- labelB->index_ = 1;
- } else {
- labelA->index_ = 1;
- labelB->index_ = 0;
- }
- prog->AssignRemainingIndexes();
-
- return prog;
- }
-
- courgette::AssemblyProgram* MakeProgramA() const { return MakeProgram(0); }
- courgette::AssemblyProgram* MakeProgramB() const { return MakeProgram(1); }
-
- // Returns a string that is the serialized version of |program|.
- // Deletes |program|.
- std::string Serialize(courgette::AssemblyProgram *program) const {
- courgette::EncodedProgram* encoded = NULL;
-
- const courgette::Status encode_status = Encode(program, &encoded);
- EXPECT_EQ(courgette::C_OK, encode_status);
-
- DeleteAssemblyProgram(program);
-
- courgette::SinkStreamSet sinks;
- const courgette::Status write_status = WriteEncodedProgram(encoded, &sinks);
- EXPECT_EQ(courgette::C_OK, write_status);
-
- DeleteEncodedProgram(encoded);
-
- courgette::SinkStream sink;
- bool can_collect = sinks.CopyTo(&sink);
- EXPECT_TRUE(can_collect);
-
- return std::string(reinterpret_cast<const char *>(sink.Buffer()),
- sink.Length());
- }
-};
-
-
-void AdjustmentMethodTest::Test1() const {
- courgette::AssemblyProgram* prog1 = MakeProgramA();
- courgette::AssemblyProgram* prog2 = MakeProgramB();
- std::string s1 = Serialize(prog1);
- std::string s2 = Serialize(prog2);
-
- // Don't use EXPECT_EQ because strings are unprintable.
- EXPECT_FALSE(s1 == s2); // Unadjusted A and B differ.
-
- courgette::AssemblyProgram* prog5 = MakeProgramA();
- courgette::AssemblyProgram* prog6 = MakeProgramB();
- courgette::Status can_adjust = Adjust(*prog5, prog6);
- EXPECT_EQ(courgette::C_OK, can_adjust);
- std::string s5 = Serialize(prog5);
- std::string s6 = Serialize(prog6);
-
- EXPECT_TRUE(s1 == s5); // Adjustment did not change A (prog5)
- EXPECT_TRUE(s5 == s6); // Adjustment did change B into A
-}
-
-
-TEST_F(AdjustmentMethodTest, All) {
- Test1();
-}
-
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <string>
+
+#include "base/path_service.h"
+#include "base/file_util.h"
+#include "base/string_util.h"
+
+#include "courgette/assembly_program.h"
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+class AdjustmentMethodTest : public testing::Test {
+ public:
+ void Test1() const;
+
+ private:
+ void SetUp() {
+ }
+
+ void TearDown() {
+ }
+
+ // Returns one of two similar a simple programs. They differ only in the
+ // label assignment, so that it is possible to make them look identical.
+ courgette::AssemblyProgram* MakeProgram(int kind) const {
+ courgette::AssemblyProgram* prog = new courgette::AssemblyProgram();
+ prog->set_image_base(0x00400000);
+
+ courgette::Label* labelA = prog->FindOrMakeAbs32Label(0x00410000);
+ courgette::Label* labelB = prog->FindOrMakeAbs32Label(0x00410004);
+
+ prog->EmitAbs32(labelA);
+ prog->EmitAbs32(labelA);
+ prog->EmitAbs32(labelB);
+ prog->EmitAbs32(labelA);
+ prog->EmitAbs32(labelA);
+ prog->EmitAbs32(labelB);
+
+ if (kind == 0) {
+ labelA->index_ = 0;
+ labelB->index_ = 1;
+ } else {
+ labelA->index_ = 1;
+ labelB->index_ = 0;
+ }
+ prog->AssignRemainingIndexes();
+
+ return prog;
+ }
+
+ courgette::AssemblyProgram* MakeProgramA() const { return MakeProgram(0); }
+ courgette::AssemblyProgram* MakeProgramB() const { return MakeProgram(1); }
+
+ // Returns a string that is the serialized version of |program|.
+ // Deletes |program|.
+ std::string Serialize(courgette::AssemblyProgram *program) const {
+ courgette::EncodedProgram* encoded = NULL;
+
+ const courgette::Status encode_status = Encode(program, &encoded);
+ EXPECT_EQ(courgette::C_OK, encode_status);
+
+ DeleteAssemblyProgram(program);
+
+ courgette::SinkStreamSet sinks;
+ const courgette::Status write_status = WriteEncodedProgram(encoded, &sinks);
+ EXPECT_EQ(courgette::C_OK, write_status);
+
+ DeleteEncodedProgram(encoded);
+
+ courgette::SinkStream sink;
+ bool can_collect = sinks.CopyTo(&sink);
+ EXPECT_TRUE(can_collect);
+
+ return std::string(reinterpret_cast<const char *>(sink.Buffer()),
+ sink.Length());
+ }
+};
+
+
+void AdjustmentMethodTest::Test1() const {
+ courgette::AssemblyProgram* prog1 = MakeProgramA();
+ courgette::AssemblyProgram* prog2 = MakeProgramB();
+ std::string s1 = Serialize(prog1);
+ std::string s2 = Serialize(prog2);
+
+ // Don't use EXPECT_EQ because strings are unprintable.
+ EXPECT_FALSE(s1 == s2); // Unadjusted A and B differ.
+
+ courgette::AssemblyProgram* prog5 = MakeProgramA();
+ courgette::AssemblyProgram* prog6 = MakeProgramB();
+ courgette::Status can_adjust = Adjust(*prog5, prog6);
+ EXPECT_EQ(courgette::C_OK, can_adjust);
+ std::string s5 = Serialize(prog5);
+ std::string s6 = Serialize(prog6);
+
+ EXPECT_TRUE(s1 == s5); // Adjustment did not change A (prog5)
+ EXPECT_TRUE(s5 == s6); // Adjustment did change B into A
+}
+
+
+TEST_F(AdjustmentMethodTest, All) {
+ Test1();
+}
diff --git a/third_party/courgette/assembly_program.cc b/courgette/assembly_program.cc
index 178dfdf..e40f38f 100644
--- a/third_party/courgette/assembly_program.cc
+++ b/courgette/assembly_program.cc
@@ -1,373 +1,372 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/courgette/assembly_program.h"
-
-#include <memory.h>
-#include <algorithm>
-#include <map>
-#include <set>
-#include <sstream>
-#include <vector>
-
-#include "base/logging.h"
-
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/encoded_program.h"
-
-namespace courgette {
-
-// Opcodes of simple assembly language
-enum OP {
- ORIGIN, // ORIGIN <rva> - set current address for assembly.
- MAKERELOCS, // Generates a base relocation table.
- DEFBYTE, // DEFBYTE <value> - emit a byte literal.
- REL32, // REL32 <label> - emit a rel32 encoded reference to 'label'.
- ABS32, // REL32 <label> - emit am abs32 encoded reference to 'label'.
- LAST_OP
-};
-
-// Base class for instructions. Because we have so many instructions we want to
-// keep them as small as possible. For this reason we avoid virtual functions.
-//
-class Instruction {
- public:
- OP op() const { return static_cast<OP>(op_); }
-
- protected:
- explicit Instruction(OP op) : op_(op), info_(0) {}
- Instruction(OP op, unsigned int info) : op_(op), info_(info) {}
-
- uint32 op_ : 4; // A few bits to store the OP code.
- uint32 info_ : 28; // Remaining bits in first word available to subclass.
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Instruction);
-};
-
-namespace {
-
-// Sets the current address for the emitting instructions.
-class OriginInstruction : public Instruction {
- public:
- explicit OriginInstruction(RVA rva) : Instruction(ORIGIN, 0), rva_(rva) {}
- RVA origin_rva() const { return rva_; }
- private:
- RVA rva_;
-};
-
-// Emits an entire base relocation table.
-class MakeRelocsInstruction : public Instruction {
- public:
- MakeRelocsInstruction() : Instruction(MAKERELOCS) {}
-};
-
-// Emits a single byte.
-class ByteInstruction : public Instruction {
- public:
- explicit ByteInstruction(uint8 value) : Instruction(DEFBYTE, value) {}
- uint8 byte_value() const { return info_; }
-};
-
-// A ABS32 to REL32 instruction emits a reference to a label's address.
-class InstructionWithLabel : public Instruction {
- public:
- InstructionWithLabel(OP op, Label* label)
- : Instruction(op, 0), label_(label) {
- if (label == NULL) NOTREACHED();
- }
- Label* label() const { return label_; }
- private:
- Label* label_;
-};
-
-} // namespace
-
-AssemblyProgram::AssemblyProgram()
- : image_base_(0),
- byte_instruction_cache_(NULL) {
-}
-
-static void DeleteContainedLabels(const RVAToLabel& labels) {
- for (RVAToLabel::const_iterator p = labels.begin(); p != labels.end(); ++p)
- delete p->second;
-}
-
-AssemblyProgram::~AssemblyProgram() {
- for (size_t i = 0; i < instructions_.size(); ++i) {
- Instruction* instruction = instructions_[i];
- if (instruction->op() != DEFBYTE) // Will be in byte_instruction_cache_.
- delete instruction;
- }
- if (byte_instruction_cache_) {
- for (size_t i = 0; i < 256; ++i)
- delete byte_instruction_cache_[i];
- delete[] byte_instruction_cache_;
- }
- DeleteContainedLabels(rel32_labels_);
- DeleteContainedLabels(abs32_labels_);
-}
-
-void AssemblyProgram::EmitMakeRelocsInstruction() {
- Emit(new MakeRelocsInstruction());
-}
-
-void AssemblyProgram::EmitOriginInstruction(RVA rva) {
- Emit(new OriginInstruction(rva));
-}
-
-void AssemblyProgram::EmitByteInstruction(uint8 byte) {
- Emit(GetByteInstruction(byte));
-}
-
-void AssemblyProgram::EmitRel32(Label* label) {
- Emit(new InstructionWithLabel(REL32, label));
-}
-
-void AssemblyProgram::EmitAbs32(Label* label) {
- Emit(new InstructionWithLabel(ABS32, label));
-}
-
-Label* AssemblyProgram::FindOrMakeAbs32Label(RVA rva) {
- return FindLabel(rva, &abs32_labels_);
-}
-
-Label* AssemblyProgram::FindOrMakeRel32Label(RVA rva) {
- return FindLabel(rva, &rel32_labels_);
-}
-
-void AssemblyProgram::DefaultAssignIndexes() {
- DefaultAssignIndexes(&abs32_labels_);
- DefaultAssignIndexes(&rel32_labels_);
-}
-
-void AssemblyProgram::UnassignIndexes() {
- UnassignIndexes(&abs32_labels_);
- UnassignIndexes(&rel32_labels_);
-}
-
-void AssemblyProgram::AssignRemainingIndexes() {
- AssignRemainingIndexes(&abs32_labels_);
- AssignRemainingIndexes(&rel32_labels_);
-}
-
-Label* AssemblyProgram::InstructionAbs32Label(
- const Instruction* instruction) const {
- if (instruction->op() == ABS32)
- return static_cast<const InstructionWithLabel*>(instruction)->label();
- return NULL;
-}
-
-Label* AssemblyProgram::InstructionRel32Label(
- const Instruction* instruction) const {
- if (instruction->op() == REL32)
- return static_cast<const InstructionWithLabel*>(instruction)->label();
- return NULL;
-}
-
-Label* AssemblyProgram::FindLabel(RVA rva, RVAToLabel* labels) {
- Label*& slot = (*labels)[rva];
- if (slot == 0) {
- slot = new Label(rva);
- }
- return slot;
-}
-
-void AssemblyProgram::UnassignIndexes(RVAToLabel* labels) {
- for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
- Label* current = p->second;
- current->index_ = Label::kNoIndex;
- }
-}
-
-// DefaultAssignIndexes takes a set of labels and assigns indexes in increasing
-// address order.
-//
-void AssemblyProgram::DefaultAssignIndexes(RVAToLabel* labels) {
- int index = 0;
- for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
- Label* current = p->second;
- if (current->index_ != Label::kNoIndex)
- NOTREACHED();
- current->index_ = index;
- ++index;
- }
-}
-
-// AssignRemainingIndexes assigns indexes to any addresses (labels) that are not
-// yet assigned an index.
-//
-void AssemblyProgram::AssignRemainingIndexes(RVAToLabel* labels) {
- // An address table compresses best when each index is associated with an
- // address that is slight larger than the previous index.
-
- // First see which indexes have not been used. The 'available' vector could
- // grow even bigger, but the number of addresses is a better starting size
- // than empty.
- std::vector<bool> available(labels->size(), true);
- int used = 0;
-
- for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
- size_t index = p->second->index_;
- if (index != Label::kNoIndex) {
- while (index >= available.size())
- available.push_back(true);
- available.at(index) = false;
- ++used;
- }
- }
-
- LOG(INFO) << used << " of " << labels->size() << " labels pre-assigned";
-
- // Are there any unused labels that happen to be adjacent following a used
- // label?
- //
- int fill_forward_count = 0;
- Label* prev = 0;
- for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
- Label* current = p->second;
- if (current->index_ == Label::kNoIndex) {
- size_t index = 0;
- if (prev && prev->index_ != Label::kNoIndex)
- index = prev->index_ + 1;
- if (index < available.size() && available.at(index)) {
- current->index_ = index;
- available.at(index) = false;
- ++fill_forward_count;
- }
- }
- prev = current;
- }
-
- // Are there any unused labels that happen to be adjacent preceeding a used
- // label?
- //
- int fill_backward_count = 0;
- int backward_refs = 0;
- prev = 0;
- for (RVAToLabel::reverse_iterator p = labels->rbegin();
- p != labels->rend();
- ++p) {
- Label* current = p->second;
- if (current->index_ == Label::kNoIndex) {
- int prev_index;
- if (prev)
- prev_index = prev->index_;
- else
- prev_index = available.size();
- if (prev_index != 0 &&
- prev_index != Label::kNoIndex &&
- available.at(prev_index - 1)) {
- current->index_ = prev_index - 1;
- available.at(current->index_) = false;
- ++fill_backward_count;
- }
- }
- prev = current;
- }
-
- // Fill in any remaining indexes
- int fill_infill_count = 0;
- int index = 0;
- for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
- Label* current = p->second;
- if (current->index_ == Label::kNoIndex) {
- while (!available.at(index)) {
- ++index;
- }
- current->index_ = index;
- available.at(index) = false;
- ++index;
- ++fill_infill_count;
- }
- }
-
- LOG(INFO) << " fill"
- << " forward " << fill_forward_count << " "
- << " backward " << fill_backward_count << " "
- << " infill " << fill_infill_count;
-}
-
-typedef void (EncodedProgram::*DefineLabelMethod)(int index, RVA value);
-
-static void DefineLabels(const RVAToLabel& labels,
- EncodedProgram* encoded_format,
- DefineLabelMethod define_label) {
- for (RVAToLabel::const_iterator p = labels.begin(); p != labels.end(); ++p) {
- Label* label = p->second;
- (encoded_format->*define_label)(label->index_, label->rva_);
- }
-}
-
-EncodedProgram* AssemblyProgram::Encode() const {
- EncodedProgram* encoded = new EncodedProgram();
-
- encoded->set_image_base(image_base_);
- DefineLabels(abs32_labels_, encoded, &EncodedProgram::DefineAbs32Label);
- DefineLabels(rel32_labels_, encoded, &EncodedProgram::DefineRel32Label);
- encoded->EndLabels();
-
- for (size_t i = 0; i < instructions_.size(); ++i) {
- Instruction* instruction = instructions_[i];
-
- switch (instruction->op()) {
- case ORIGIN: {
- OriginInstruction* org = static_cast<OriginInstruction*>(instruction);
- encoded->AddOrigin(org->origin_rva());
- break;
- }
- case DEFBYTE: {
- uint8 b = static_cast<ByteInstruction*>(instruction)->byte_value();
- encoded->AddCopy(1, &b);
- break;
- }
- case REL32: {
- Label* label = static_cast<InstructionWithLabel*>(instruction)->label();
- encoded->AddRel32(label->index_);
- break;
- }
- case ABS32: {
- Label* label = static_cast<InstructionWithLabel*>(instruction)->label();
- encoded->AddAbs32(label->index_);
- break;
- }
- case MAKERELOCS: {
- encoded->AddMakeRelocs();
- break;
- }
- default: {
- NOTREACHED() << "Unknown Insn OP kind";
- }
- }
- }
-
- return encoded;
-}
-
-Instruction* AssemblyProgram::GetByteInstruction(uint8 byte) {
- if (!byte_instruction_cache_) {
- byte_instruction_cache_ = new Instruction*[256];
- for (int i = 0; i < 256; ++i) {
- byte_instruction_cache_[i] = new ByteInstruction(static_cast<uint8>(i));
- }
- }
-
- return byte_instruction_cache_[byte];
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-Status Encode(AssemblyProgram* program, EncodedProgram** output) {
- *output = NULL;
- EncodedProgram *encoded = program->Encode();
- if (encoded) {
- *output = encoded;
- return C_OK;
- } else {
- return C_GENERAL_ERROR;
- }
-}
-
-} // namespace courgette
-
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "courgette/assembly_program.h"
+
+#include <memory.h>
+#include <algorithm>
+#include <map>
+#include <set>
+#include <sstream>
+#include <vector>
+
+#include "base/logging.h"
+
+#include "courgette/courgette.h"
+#include "courgette/encoded_program.h"
+
+namespace courgette {
+
+// Opcodes of simple assembly language
+enum OP {
+ ORIGIN, // ORIGIN <rva> - set current address for assembly.
+ MAKERELOCS, // Generates a base relocation table.
+ DEFBYTE, // DEFBYTE <value> - emit a byte literal.
+ REL32, // REL32 <label> - emit a rel32 encoded reference to 'label'.
+ ABS32, // REL32 <label> - emit am abs32 encoded reference to 'label'.
+ LAST_OP
+};
+
+// Base class for instructions. Because we have so many instructions we want to
+// keep them as small as possible. For this reason we avoid virtual functions.
+//
+class Instruction {
+ public:
+ OP op() const { return static_cast<OP>(op_); }
+
+ protected:
+ explicit Instruction(OP op) : op_(op), info_(0) {}
+ Instruction(OP op, unsigned int info) : op_(op), info_(info) {}
+
+ uint32 op_ : 4; // A few bits to store the OP code.
+ uint32 info_ : 28; // Remaining bits in first word available to subclass.
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(Instruction);
+};
+
+namespace {
+
+// Sets the current address for the emitting instructions.
+class OriginInstruction : public Instruction {
+ public:
+ explicit OriginInstruction(RVA rva) : Instruction(ORIGIN, 0), rva_(rva) {}
+ RVA origin_rva() const { return rva_; }
+ private:
+ RVA rva_;
+};
+
+// Emits an entire base relocation table.
+class MakeRelocsInstruction : public Instruction {
+ public:
+ MakeRelocsInstruction() : Instruction(MAKERELOCS) {}
+};
+
+// Emits a single byte.
+class ByteInstruction : public Instruction {
+ public:
+ explicit ByteInstruction(uint8 value) : Instruction(DEFBYTE, value) {}
+ uint8 byte_value() const { return info_; }
+};
+
+// A ABS32 to REL32 instruction emits a reference to a label's address.
+class InstructionWithLabel : public Instruction {
+ public:
+ InstructionWithLabel(OP op, Label* label)
+ : Instruction(op, 0), label_(label) {
+ if (label == NULL) NOTREACHED();
+ }
+ Label* label() const { return label_; }
+ private:
+ Label* label_;
+};
+
+} // namespace
+
+AssemblyProgram::AssemblyProgram()
+ : image_base_(0),
+ byte_instruction_cache_(NULL) {
+}
+
+static void DeleteContainedLabels(const RVAToLabel& labels) {
+ for (RVAToLabel::const_iterator p = labels.begin(); p != labels.end(); ++p)
+ delete p->second;
+}
+
+AssemblyProgram::~AssemblyProgram() {
+ for (size_t i = 0; i < instructions_.size(); ++i) {
+ Instruction* instruction = instructions_[i];
+ if (instruction->op() != DEFBYTE) // Will be in byte_instruction_cache_.
+ delete instruction;
+ }
+ if (byte_instruction_cache_) {
+ for (size_t i = 0; i < 256; ++i)
+ delete byte_instruction_cache_[i];
+ delete[] byte_instruction_cache_;
+ }
+ DeleteContainedLabels(rel32_labels_);
+ DeleteContainedLabels(abs32_labels_);
+}
+
+void AssemblyProgram::EmitMakeRelocsInstruction() {
+ Emit(new MakeRelocsInstruction());
+}
+
+void AssemblyProgram::EmitOriginInstruction(RVA rva) {
+ Emit(new OriginInstruction(rva));
+}
+
+void AssemblyProgram::EmitByteInstruction(uint8 byte) {
+ Emit(GetByteInstruction(byte));
+}
+
+void AssemblyProgram::EmitRel32(Label* label) {
+ Emit(new InstructionWithLabel(REL32, label));
+}
+
+void AssemblyProgram::EmitAbs32(Label* label) {
+ Emit(new InstructionWithLabel(ABS32, label));
+}
+
+Label* AssemblyProgram::FindOrMakeAbs32Label(RVA rva) {
+ return FindLabel(rva, &abs32_labels_);
+}
+
+Label* AssemblyProgram::FindOrMakeRel32Label(RVA rva) {
+ return FindLabel(rva, &rel32_labels_);
+}
+
+void AssemblyProgram::DefaultAssignIndexes() {
+ DefaultAssignIndexes(&abs32_labels_);
+ DefaultAssignIndexes(&rel32_labels_);
+}
+
+void AssemblyProgram::UnassignIndexes() {
+ UnassignIndexes(&abs32_labels_);
+ UnassignIndexes(&rel32_labels_);
+}
+
+void AssemblyProgram::AssignRemainingIndexes() {
+ AssignRemainingIndexes(&abs32_labels_);
+ AssignRemainingIndexes(&rel32_labels_);
+}
+
+Label* AssemblyProgram::InstructionAbs32Label(
+ const Instruction* instruction) const {
+ if (instruction->op() == ABS32)
+ return static_cast<const InstructionWithLabel*>(instruction)->label();
+ return NULL;
+}
+
+Label* AssemblyProgram::InstructionRel32Label(
+ const Instruction* instruction) const {
+ if (instruction->op() == REL32)
+ return static_cast<const InstructionWithLabel*>(instruction)->label();
+ return NULL;
+}
+
+Label* AssemblyProgram::FindLabel(RVA rva, RVAToLabel* labels) {
+ Label*& slot = (*labels)[rva];
+ if (slot == 0) {
+ slot = new Label(rva);
+ }
+ return slot;
+}
+
+void AssemblyProgram::UnassignIndexes(RVAToLabel* labels) {
+ for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
+ Label* current = p->second;
+ current->index_ = Label::kNoIndex;
+ }
+}
+
+// DefaultAssignIndexes takes a set of labels and assigns indexes in increasing
+// address order.
+//
+void AssemblyProgram::DefaultAssignIndexes(RVAToLabel* labels) {
+ int index = 0;
+ for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
+ Label* current = p->second;
+ if (current->index_ != Label::kNoIndex)
+ NOTREACHED();
+ current->index_ = index;
+ ++index;
+ }
+}
+
+// AssignRemainingIndexes assigns indexes to any addresses (labels) that are not
+// yet assigned an index.
+//
+void AssemblyProgram::AssignRemainingIndexes(RVAToLabel* labels) {
+ // An address table compresses best when each index is associated with an
+ // address that is slight larger than the previous index.
+
+ // First see which indexes have not been used. The 'available' vector could
+ // grow even bigger, but the number of addresses is a better starting size
+ // than empty.
+ std::vector<bool> available(labels->size(), true);
+ int used = 0;
+
+ for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
+ size_t index = p->second->index_;
+ if (index != Label::kNoIndex) {
+ while (index >= available.size())
+ available.push_back(true);
+ available.at(index) = false;
+ ++used;
+ }
+ }
+
+ LOG(INFO) << used << " of " << labels->size() << " labels pre-assigned";
+
+ // Are there any unused labels that happen to be adjacent following a used
+ // label?
+ //
+ int fill_forward_count = 0;
+ Label* prev = 0;
+ for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
+ Label* current = p->second;
+ if (current->index_ == Label::kNoIndex) {
+ size_t index = 0;
+ if (prev && prev->index_ != Label::kNoIndex)
+ index = prev->index_ + 1;
+ if (index < available.size() && available.at(index)) {
+ current->index_ = index;
+ available.at(index) = false;
+ ++fill_forward_count;
+ }
+ }
+ prev = current;
+ }
+
+ // Are there any unused labels that happen to be adjacent preceeding a used
+ // label?
+ //
+ int fill_backward_count = 0;
+ int backward_refs = 0;
+ prev = 0;
+ for (RVAToLabel::reverse_iterator p = labels->rbegin();
+ p != labels->rend();
+ ++p) {
+ Label* current = p->second;
+ if (current->index_ == Label::kNoIndex) {
+ int prev_index;
+ if (prev)
+ prev_index = prev->index_;
+ else
+ prev_index = available.size();
+ if (prev_index != 0 &&
+ prev_index != Label::kNoIndex &&
+ available.at(prev_index - 1)) {
+ current->index_ = prev_index - 1;
+ available.at(current->index_) = false;
+ ++fill_backward_count;
+ }
+ }
+ prev = current;
+ }
+
+ // Fill in any remaining indexes
+ int fill_infill_count = 0;
+ int index = 0;
+ for (RVAToLabel::iterator p = labels->begin(); p != labels->end(); ++p) {
+ Label* current = p->second;
+ if (current->index_ == Label::kNoIndex) {
+ while (!available.at(index)) {
+ ++index;
+ }
+ current->index_ = index;
+ available.at(index) = false;
+ ++index;
+ ++fill_infill_count;
+ }
+ }
+
+ LOG(INFO) << " fill"
+ << " forward " << fill_forward_count << " "
+ << " backward " << fill_backward_count << " "
+ << " infill " << fill_infill_count;
+}
+
+typedef void (EncodedProgram::*DefineLabelMethod)(int index, RVA value);
+
+static void DefineLabels(const RVAToLabel& labels,
+ EncodedProgram* encoded_format,
+ DefineLabelMethod define_label) {
+ for (RVAToLabel::const_iterator p = labels.begin(); p != labels.end(); ++p) {
+ Label* label = p->second;
+ (encoded_format->*define_label)(label->index_, label->rva_);
+ }
+}
+
+EncodedProgram* AssemblyProgram::Encode() const {
+ EncodedProgram* encoded = new EncodedProgram();
+
+ encoded->set_image_base(image_base_);
+ DefineLabels(abs32_labels_, encoded, &EncodedProgram::DefineAbs32Label);
+ DefineLabels(rel32_labels_, encoded, &EncodedProgram::DefineRel32Label);
+ encoded->EndLabels();
+
+ for (size_t i = 0; i < instructions_.size(); ++i) {
+ Instruction* instruction = instructions_[i];
+
+ switch (instruction->op()) {
+ case ORIGIN: {
+ OriginInstruction* org = static_cast<OriginInstruction*>(instruction);
+ encoded->AddOrigin(org->origin_rva());
+ break;
+ }
+ case DEFBYTE: {
+ uint8 b = static_cast<ByteInstruction*>(instruction)->byte_value();
+ encoded->AddCopy(1, &b);
+ break;
+ }
+ case REL32: {
+ Label* label = static_cast<InstructionWithLabel*>(instruction)->label();
+ encoded->AddRel32(label->index_);
+ break;
+ }
+ case ABS32: {
+ Label* label = static_cast<InstructionWithLabel*>(instruction)->label();
+ encoded->AddAbs32(label->index_);
+ break;
+ }
+ case MAKERELOCS: {
+ encoded->AddMakeRelocs();
+ break;
+ }
+ default: {
+ NOTREACHED() << "Unknown Insn OP kind";
+ }
+ }
+ }
+
+ return encoded;
+}
+
+Instruction* AssemblyProgram::GetByteInstruction(uint8 byte) {
+ if (!byte_instruction_cache_) {
+ byte_instruction_cache_ = new Instruction*[256];
+ for (int i = 0; i < 256; ++i) {
+ byte_instruction_cache_[i] = new ByteInstruction(static_cast<uint8>(i));
+ }
+ }
+
+ return byte_instruction_cache_[byte];
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+Status Encode(AssemblyProgram* program, EncodedProgram** output) {
+ *output = NULL;
+ EncodedProgram *encoded = program->Encode();
+ if (encoded) {
+ *output = encoded;
+ return C_OK;
+ } else {
+ return C_GENERAL_ERROR;
+ }
+}
+
+} // namespace courgette
diff --git a/third_party/courgette/assembly_program.h b/courgette/assembly_program.h
index 4b48133..e726f81 100644
--- a/third_party/courgette/assembly_program.h
+++ b/courgette/assembly_program.h
@@ -1,134 +1,133 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef COURGETTE_ASSEMBLY_PROGRAM_H_
-#define COURGETTE_ASSEMBLY_PROGRAM_H_
-
-#include <map>
-#include <set>
-#include <vector>
-
-#include "base/basictypes.h"
-
-#include "third_party/courgette/image_info.h"
-
-namespace courgette {
-
-class EncodedProgram;
-class Instruction;
-
-// A Label is a symbolic reference to an address. Unlike a conventional
-// assembly language, we always know the address. The address will later be
-// stored in a table and the Label will be replaced with the index into the
-// table.
-//
-// TODO(sra): Make fields private and add setters and getters.
-class Label {
- public:
- static const int kNoIndex = -1;
- Label() : rva_(0), index_(kNoIndex) {}
- explicit Label(RVA rva) : rva_(rva), index_(kNoIndex) {}
-
- RVA rva_; // Address refered to by the label.
- int index_; // Index of address in address table, kNoIndex until assigned.
-};
-
-typedef std::map<RVA, Label*> RVAToLabel;
-
-// An AssemblyProgram is the result of disassembling an executable file.
-//
-// * The disassembler creates labels in the AssemblyProgram and emits
-// 'Instructions'.
-// * The disassembler then calls DefaultAssignIndexes to assign
-// addresses to positions in the address tables.
-// * [Optional step]
-// * At this point the AssemblyProgram can be converted into an
-// EncodedProgram and serialized to an output stream.
-// * Later, the EncodedProgram can be deserialized and assembled into
-// the original file.
-//
-// The optional step is to modify the AssemblyProgram. One form of modification
-// is to assign indexes in such a way as to make the EncodedProgram for this
-// AssemblyProgram look more like the EncodedProgram for some other
-// AssemblyProgram. The modification process should call UnassignIndexes, do
-// its own assignment, and then call AssignRemainingIndexes to ensure all
-// indexes are assigned.
-//
-class AssemblyProgram {
- public:
- AssemblyProgram();
- ~AssemblyProgram();
-
- void set_image_base(uint64 image_base) { image_base_ = image_base; }
-
- // Instructions will be assembled in the order they are emitted.
-
- // Generates an entire base relocation table.
- void EmitMakeRelocsInstruction();
-
- // Following instruction will be assembled at address 'rva'.
- void EmitOriginInstruction(RVA rva);
-
- // Generates a single byte of data or machine instruction.
- void EmitByteInstruction(uint8 byte);
-
- // Generates 4-byte relative reference to address of 'label'.
- void EmitRel32(Label* label);
-
- // Generates 4-byte absolute reference to address of 'label'.
- void EmitAbs32(Label* label);
-
- Label* FindOrMakeAbs32Label(RVA rva);
- Label* FindOrMakeRel32Label(RVA rva);
-
- void DefaultAssignIndexes();
- void UnassignIndexes();
- void AssignRemainingIndexes();
-
- EncodedProgram* Encode() const;
-
- // Accessor for instruction list.
- const std::vector<Instruction*>& instructions() const {
- return instructions_;
- }
-
- // Returns the label if the instruction contains and absolute address,
- // otherwise returns NULL.
- Label* InstructionAbs32Label(const Instruction* instruction) const;
-
- // Returns the label if the instruction contains and rel32 offset,
- // otherwise returns NULL.
- Label* InstructionRel32Label(const Instruction* instruction) const;
-
-
- private:
- void Emit(Instruction* instruction) { instructions_.push_back(instruction); }
-
- Label* FindLabel(RVA rva, RVAToLabel* labels);
-
- // Helper methods for the public versions.
- static void UnassignIndexes(RVAToLabel* labels);
- static void DefaultAssignIndexes(RVAToLabel* labels);
- static void AssignRemainingIndexes(RVAToLabel* labels);
-
- // Sharing instructions that emit a single byte saves a lot of space.
- Instruction* GetByteInstruction(uint8 byte);
- Instruction** byte_instruction_cache_;
-
- uint64 image_base_; // Desired or mandated base address of image.
-
- std::vector<Instruction*> instructions_; // All the instructions in program.
-
- // These are lookup maps to find the label associated with a given address.
- // We have separate label spaces for addresses referenced by rel32 labels and
- // abs32 labels. This is somewhat arbitrary.
- RVAToLabel rel32_labels_;
- RVAToLabel abs32_labels_;
-
- DISALLOW_COPY_AND_ASSIGN(AssemblyProgram);
-};
-
-} // namespace courgette
-#endif // COURGETTE_ASSEMBLY_PROGRAM_H_
-
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COURGETTE_ASSEMBLY_PROGRAM_H_
+#define COURGETTE_ASSEMBLY_PROGRAM_H_
+
+#include <map>
+#include <set>
+#include <vector>
+
+#include "base/basictypes.h"
+
+#include "courgette/image_info.h"
+
+namespace courgette {
+
+class EncodedProgram;
+class Instruction;
+
+// A Label is a symbolic reference to an address. Unlike a conventional
+// assembly language, we always know the address. The address will later be
+// stored in a table and the Label will be replaced with the index into the
+// table.
+//
+// TODO(sra): Make fields private and add setters and getters.
+class Label {
+ public:
+ static const int kNoIndex = -1;
+ Label() : rva_(0), index_(kNoIndex) {}
+ explicit Label(RVA rva) : rva_(rva), index_(kNoIndex) {}
+
+ RVA rva_; // Address refered to by the label.
+ int index_; // Index of address in address table, kNoIndex until assigned.
+};
+
+typedef std::map<RVA, Label*> RVAToLabel;
+
+// An AssemblyProgram is the result of disassembling an executable file.
+//
+// * The disassembler creates labels in the AssemblyProgram and emits
+// 'Instructions'.
+// * The disassembler then calls DefaultAssignIndexes to assign
+// addresses to positions in the address tables.
+// * [Optional step]
+// * At this point the AssemblyProgram can be converted into an
+// EncodedProgram and serialized to an output stream.
+// * Later, the EncodedProgram can be deserialized and assembled into
+// the original file.
+//
+// The optional step is to modify the AssemblyProgram. One form of modification
+// is to assign indexes in such a way as to make the EncodedProgram for this
+// AssemblyProgram look more like the EncodedProgram for some other
+// AssemblyProgram. The modification process should call UnassignIndexes, do
+// its own assignment, and then call AssignRemainingIndexes to ensure all
+// indexes are assigned.
+//
+class AssemblyProgram {
+ public:
+ AssemblyProgram();
+ ~AssemblyProgram();
+
+ void set_image_base(uint64 image_base) { image_base_ = image_base; }
+
+ // Instructions will be assembled in the order they are emitted.
+
+ // Generates an entire base relocation table.
+ void EmitMakeRelocsInstruction();
+
+ // Following instruction will be assembled at address 'rva'.
+ void EmitOriginInstruction(RVA rva);
+
+ // Generates a single byte of data or machine instruction.
+ void EmitByteInstruction(uint8 byte);
+
+ // Generates 4-byte relative reference to address of 'label'.
+ void EmitRel32(Label* label);
+
+ // Generates 4-byte absolute reference to address of 'label'.
+ void EmitAbs32(Label* label);
+
+ Label* FindOrMakeAbs32Label(RVA rva);
+ Label* FindOrMakeRel32Label(RVA rva);
+
+ void DefaultAssignIndexes();
+ void UnassignIndexes();
+ void AssignRemainingIndexes();
+
+ EncodedProgram* Encode() const;
+
+ // Accessor for instruction list.
+ const std::vector<Instruction*>& instructions() const {
+ return instructions_;
+ }
+
+ // Returns the label if the instruction contains and absolute address,
+ // otherwise returns NULL.
+ Label* InstructionAbs32Label(const Instruction* instruction) const;
+
+ // Returns the label if the instruction contains and rel32 offset,
+ // otherwise returns NULL.
+ Label* InstructionRel32Label(const Instruction* instruction) const;
+
+
+ private:
+ void Emit(Instruction* instruction) { instructions_.push_back(instruction); }
+
+ Label* FindLabel(RVA rva, RVAToLabel* labels);
+
+ // Helper methods for the public versions.
+ static void UnassignIndexes(RVAToLabel* labels);
+ static void DefaultAssignIndexes(RVAToLabel* labels);
+ static void AssignRemainingIndexes(RVAToLabel* labels);
+
+ // Sharing instructions that emit a single byte saves a lot of space.
+ Instruction* GetByteInstruction(uint8 byte);
+ Instruction** byte_instruction_cache_;
+
+ uint64 image_base_; // Desired or mandated base address of image.
+
+ std::vector<Instruction*> instructions_; // All the instructions in program.
+
+ // These are lookup maps to find the label associated with a given address.
+ // We have separate label spaces for addresses referenced by rel32 labels and
+ // abs32 labels. This is somewhat arbitrary.
+ RVAToLabel rel32_labels_;
+ RVAToLabel abs32_labels_;
+
+ DISALLOW_COPY_AND_ASSIGN(AssemblyProgram);
+};
+
+} // namespace courgette
+#endif // COURGETTE_ASSEMBLY_PROGRAM_H_
diff --git a/third_party/courgette/bsdiff_memory_unittest.cc b/courgette/bsdiff_memory_unittest.cc
index e1add46..97da726 100644
--- a/third_party/courgette/bsdiff_memory_unittest.cc
+++ b/courgette/bsdiff_memory_unittest.cc
@@ -1,112 +1,111 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/courgette/bsdiff.h"
-
-#include <string>
-
-#include "base/file_util.h"
-#include "base/path_service.h"
-#include "base/string_util.h"
-
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
-
-#include "testing/gtest/include/gtest/gtest.h"
-
-class BSDiffMemoryTest : public testing::Test {
- public:
- std::string FileContents(const char *file_name) const;
- void GenerateAndTestPatch(const std::string& a, const std::string& b) const;
-
- private:
- void SetUp() {
- PathService::Get(base::DIR_SOURCE_ROOT, &test_dir_);
- // file_util::AppendToPath(&test_dir_, L"third_party");
- file_util::AppendToPath(&test_dir_, L"courgette");
- file_util::AppendToPath(&test_dir_, L"testdata");
- }
-
- std::wstring test_dir_;
-};
-
-// Reads a test file into a string.
-std::string BSDiffMemoryTest::FileContents(const char *file_name) const {
- std::wstring file_path = test_dir_;
- file_util::AppendToPath(&file_path, UTF8ToWide(file_name));
- std::string file_bytes;
- if (!file_util::ReadFileToString(file_path, &file_bytes)) {
- EXPECT_TRUE(!"Could not read test data");
- }
- return file_bytes;
-}
-
-void BSDiffMemoryTest::GenerateAndTestPatch(const std::string& old_text,
- const std::string& new_text) const {
- courgette::SourceStream old1;
- courgette::SourceStream new1;
- old1.Init(old_text.c_str(), old_text.length());
- new1.Init(new_text.c_str(), new_text.length());
-
- courgette::SinkStream patch1;
- courgette::BSDiffStatus status = CreateBinaryPatch(&old1, &new1, &patch1);
- EXPECT_EQ(courgette::OK, status);
-
- courgette::SourceStream old2;
- courgette::SourceStream patch2;
- old2.Init(old_text.c_str(), old_text.length());
- patch2.Init(patch1);
-
- courgette::SinkStream new2;
- status = ApplyBinaryPatch(&old2, &patch2, &new2);
- EXPECT_EQ(courgette::OK, status);
- EXPECT_EQ(new_text.length(), new2.Length());
- EXPECT_EQ(0, memcmp(new_text.c_str(), new2.Buffer(), new_text.length()));
-}
-
-TEST_F(BSDiffMemoryTest, TestEmpty) {
- GenerateAndTestPatch("", "");
-}
-
-TEST_F(BSDiffMemoryTest, TestEmptyVsNonempty) {
- GenerateAndTestPatch("", "xxx");
-}
-
-TEST_F(BSDiffMemoryTest, TestNonemptyVsEmpty) {
- GenerateAndTestPatch("xxx", "");
-}
-
-TEST_F(BSDiffMemoryTest, TestSmallInputsWithSmallChanges) {
- std::string file1 =
- "I would not, could not, in a box.\n"
- "I could not, would not, with a fox.\n"
- "I will not eat them with a mouse.\n"
- "I will not eat them in a house.\n"
- "I will not eat them here or there.\n"
- "I will not eat them anywhere.\n"
- "I do not eat green eggs and ham.\n"
- "I do not like them, Sam-I-am.\n";
- std::string file2 =
- "I would not, could not, in a BOX.\n"
- "I could not, would not, with a FOX.\n"
- "I will not eat them with a MOUSE.\n"
- "I will not eat them in a HOUSE.\n"
- "I will not eat them in a HOUSE.\n" // Extra line.
- "I will not eat them here or THERE.\n"
- "I will not eat them ANYWHERE.\n"
- "I do not eat green eggs and HAM.\n"
- "I do not like them, Sam-I-am.\n";
- GenerateAndTestPatch(file1, file2);
-}
-
-TEST_F(BSDiffMemoryTest, TestIndenticalDlls) {
- std::string file1 = FileContents("en-US.dll");
- GenerateAndTestPatch(file1, file1);
-}
-
-TEST_F(BSDiffMemoryTest, TestDifferentExes) {
- std::string file1 = FileContents("setup1.exe");
- std::string file2 = FileContents("setup2.exe");
- GenerateAndTestPatch(file1, file2);
-}
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "courgette/third_party/bsdiff.h"
+
+#include <string>
+
+#include "base/file_util.h"
+#include "base/path_service.h"
+#include "base/string_util.h"
+
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+class BSDiffMemoryTest : public testing::Test {
+ public:
+ std::string FileContents(const char *file_name) const;
+ void GenerateAndTestPatch(const std::string& a, const std::string& b) const;
+
+ private:
+ void SetUp() {
+ PathService::Get(base::DIR_SOURCE_ROOT, &test_dir_);
+ file_util::AppendToPath(&test_dir_, L"courgette");
+ file_util::AppendToPath(&test_dir_, L"testdata");
+ }
+
+ std::wstring test_dir_;
+};
+
+// Reads a test file into a string.
+std::string BSDiffMemoryTest::FileContents(const char *file_name) const {
+ std::wstring file_path = test_dir_;
+ file_util::AppendToPath(&file_path, UTF8ToWide(file_name));
+ std::string file_bytes;
+ if (!file_util::ReadFileToString(file_path, &file_bytes)) {
+ EXPECT_TRUE(!"Could not read test data");
+ }
+ return file_bytes;
+}
+
+void BSDiffMemoryTest::GenerateAndTestPatch(const std::string& old_text,
+ const std::string& new_text) const {
+ courgette::SourceStream old1;
+ courgette::SourceStream new1;
+ old1.Init(old_text.c_str(), old_text.length());
+ new1.Init(new_text.c_str(), new_text.length());
+
+ courgette::SinkStream patch1;
+ courgette::BSDiffStatus status = CreateBinaryPatch(&old1, &new1, &patch1);
+ EXPECT_EQ(courgette::OK, status);
+
+ courgette::SourceStream old2;
+ courgette::SourceStream patch2;
+ old2.Init(old_text.c_str(), old_text.length());
+ patch2.Init(patch1);
+
+ courgette::SinkStream new2;
+ status = ApplyBinaryPatch(&old2, &patch2, &new2);
+ EXPECT_EQ(courgette::OK, status);
+ EXPECT_EQ(new_text.length(), new2.Length());
+ EXPECT_EQ(0, memcmp(new_text.c_str(), new2.Buffer(), new_text.length()));
+}
+
+TEST_F(BSDiffMemoryTest, TestEmpty) {
+ GenerateAndTestPatch("", "");
+}
+
+TEST_F(BSDiffMemoryTest, TestEmptyVsNonempty) {
+ GenerateAndTestPatch("", "xxx");
+}
+
+TEST_F(BSDiffMemoryTest, TestNonemptyVsEmpty) {
+ GenerateAndTestPatch("xxx", "");
+}
+
+TEST_F(BSDiffMemoryTest, TestSmallInputsWithSmallChanges) {
+ std::string file1 =
+ "I would not, could not, in a box.\n"
+ "I could not, would not, with a fox.\n"
+ "I will not eat them with a mouse.\n"
+ "I will not eat them in a house.\n"
+ "I will not eat them here or there.\n"
+ "I will not eat them anywhere.\n"
+ "I do not eat green eggs and ham.\n"
+ "I do not like them, Sam-I-am.\n";
+ std::string file2 =
+ "I would not, could not, in a BOX.\n"
+ "I could not, would not, with a FOX.\n"
+ "I will not eat them with a MOUSE.\n"
+ "I will not eat them in a HOUSE.\n"
+ "I will not eat them in a HOUSE.\n" // Extra line.
+ "I will not eat them here or THERE.\n"
+ "I will not eat them ANYWHERE.\n"
+ "I do not eat green eggs and HAM.\n"
+ "I do not like them, Sam-I-am.\n";
+ GenerateAndTestPatch(file1, file2);
+}
+
+TEST_F(BSDiffMemoryTest, TestIndenticalDlls) {
+ std::string file1 = FileContents("en-US.dll");
+ GenerateAndTestPatch(file1, file1);
+}
+
+TEST_F(BSDiffMemoryTest, TestDifferentExes) {
+ std::string file1 = FileContents("setup1.exe");
+ std::string file2 = FileContents("setup2.exe");
+ GenerateAndTestPatch(file1, file2);
+}
diff --git a/third_party/courgette/courgette.gyp b/courgette/courgette.gyp
index a55b191..03de462 100644
--- a/third_party/courgette/courgette.gyp
+++ b/courgette/courgette.gyp
@@ -7,15 +7,15 @@
'chromium_code': 1,
},
'includes': [
- '../../build/common.gypi',
+ '../build/common.gypi',
],
'targets': [
{
'target_name': 'courgette_lib',
'type': '<(library)',
'dependencies': [
- '../../base/base.gyp:base',
- #'../../third_party/lzma_sdk/7z_C.vcproj',
+ '../base/base.gyp:base',
+ #'../third_party/lzma_sdk/7z_C.vcproj',
],
'msvs_guid': '9A72A362-E617-4205-B9F2-43C6FB280FA1',
'sources': [
@@ -23,9 +23,9 @@
'adjustment_method.h',
'assembly_program.cc',
'assembly_program.h',
- 'bsdiff.h',
- 'bsdiff_apply.cc',
- 'bsdiff_create.cc',
+ 'third_party/bsdiff.h',
+ 'third_party/bsdiff_apply.cc',
+ 'third_party/bsdiff_create.cc',
'courgette.h',
'crc.cc',
'crc.h',
@@ -49,38 +49,29 @@
'win32_x86_generator.h',
'win32_x86_patcher.h',
],
- 'include_dirs': [
- #'..',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- # '..',
- ],
- },
},
- {
- 'target_name': 'courgette_tool',
+ {
+ 'target_name': 'courgette',
'type': 'executable',
'msvs_guid': '4EA8CE12-9C6F-45E5-9D08-720383FE3685',
'sources': [
'courgette_tool.cc',
- #'memory_monitor.cc',
- ],
+ ],
'dependencies': [
'courgette_lib',
- '../../base/base.gyp:base',
+ '../base/base.gyp:base',
],
},
- {
+ {
'target_name': 'courgette_minimal_tool',
'type': 'executable',
'msvs_guid': 'EB79415F-2F17-4BDC-AADD-4CA4C2D21B73',
'sources': [
'courgette_minimal_tool.cc',
- ],
+ ],
'dependencies': [
'courgette_lib',
- '../../base/base.gyp:base',
+ '../base/base.gyp:base',
],
},
{
@@ -96,24 +87,24 @@
'image_info_unittest.cc',
'run_all_unittests.cc',
'streams_unittest.cc',
- ],
+ ],
'dependencies': [
'courgette_lib',
- '../../base/base.gyp:base',
- '../../testing/gtest.gyp:gtest',
+ '../base/base.gyp:base',
+ '../testing/gtest.gyp:gtest',
],
},
- {
+ {
'target_name': 'courgette_fuzz',
'type': 'executable',
'msvs_guid': '57C27529-8CA9-4FC3-9C02-DA05B172F785',
'sources': [
'encoded_program_fuzz_unittest.cc',
- ],
+ ],
'dependencies': [
'courgette_lib',
- '../../base/base.gyp:base',
- '../../testing/gtest.gyp:gtest',
+ '../base/base.gyp:base',
+ '../testing/gtest.gyp:gtest',
],
},
],
diff --git a/third_party/courgette/courgette.h b/courgette/courgette.h
index 09bb375..0ddded5 100644
--- a/third_party/courgette/courgette.h
+++ b/courgette/courgette.h
@@ -1,118 +1,118 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef COURGETTE_COURGETTE_H_
-#define COURGETTE_COURGETTE_H_
-
-namespace courgette {
-
-// Status codes for Courgette APIs.
-//
-// Client code should only rely on the distintion between C_OK and the other
-// status codes.
-//
-enum Status {
- C_OK = 1, // Successful operation.
-
- C_GENERAL_ERROR = 2, // Error other than listed below.
-
- C_READ_OPEN_ERROR = 3, // Could not open input file for reading.
- C_READ_ERROR = 4, // Could not read from opened input file.
-
- C_WRITE_OPEN_ERROR = 3, // Could not open output file for writing.
- C_WRITE_ERROR = 4, // Could not write to opened output file.
-
- C_BAD_ENSEMBLE_MAGIC = 5, // Ensemble patch has bad magic.
- C_BAD_ENSEMBLE_VERSION = 6, // Ensemble patch has wrong version.
- C_BAD_ENSEMBLE_HEADER = 7, // Ensemble patch has corrupt header.
- C_BAD_ENSEMBLE_CRC = 8, // Ensemble patch has corrupt header.
-
- C_BAD_TRANSFORM = 12, // Transform mis-specified.
- C_BAD_BASE = 13, // Base for transform malformed.
-
- C_BINARY_DIFF_CRC_ERROR = 14, // Internal diff input doesn't have expected
- // CRC.
-
- // Internal errors.
- C_STREAM_ERROR = 20, // Unexpected error from streams.h.
- C_STREAM_NOT_CONSUMED = 21, // Stream has extra data, is expected to be
- // used up.
- C_SERIALIZATION_FAILED = 22, //
- C_DESERIALIZATION_FAILED = 23, //
- C_INPUT_NOT_RECOGNIZED = 24, // Unrecognized input (not an executable).
- C_DISASSEMBLY_FAILED = 25, //
- C_ASSEMBLY_FAILED = 26, //
- C_ADJUSTMENT_FAILED = 27, //
-
-
-};
-
-class SinkStream;
-class SinkStreamSet;
-class SourceStream;
-class SourceStreamSet;
-
-class AssemblyProgram;
-class EncodedProgram;
-
-// Applies the patch to the bytes in |old| and writes the transformed ensemble
-// to |output|.
-// Returns C_OK unless something went wrong.
-Status ApplyEnsemblePatch(SourceStream* old, SourceStream* patch,
- SinkStream* output);
-
-// Applies the patch in |patch_file_name| to the bytes in |old_file_name| and
-// writes the transformed ensemble to |new_file_name|.
-// Returns C_OK unless something went wrong.
-// This function first validates that the patch file has a proper header, so the
-// function can be used to 'try' a patch.
-Status ApplyEnsemblePatch(const wchar_t* old_file_name,
- const wchar_t* patch_file_name,
- const wchar_t* new_file_name);
-
-// Generates a patch that will transform the bytes in |old| into the bytes in
-// |target|.
-// Returns C_OK unless something when wrong (unexpected).
-Status GenerateEnsemblePatch(SourceStream* old, SourceStream* target,
- SinkStream* patch);
-
-// Parses a Windows 32-bit 'Portable Executable' format file from memory,
-// storing the pointer to the AssemblyProgram in |*output|.
-// Returns C_OK if successful, otherwise returns an error status and sets
-// |*output| to NULL.
-Status ParseWin32X86PE(const void* buffer, size_t length,
- AssemblyProgram** output);
-
-// Converts |program| into encoded form, returning it as |*output|.
-// Returns C_OK if succeeded, otherwise returns an error status and
-// sets |*output| to NULL
-Status Encode(AssemblyProgram* program, EncodedProgram** output);
-
-
-// Serializes |encoded| into the stream set.
-// Returns C_OK if succeeded, otherwise returns an error status.
-Status WriteEncodedProgram(EncodedProgram* encoded, SinkStreamSet* sink);
-
-// Assembles |encoded|, emitting the bytes into |buffer|.
-// Returns C_OK if succeeded, otherwise returns an error status and leaves
-// |buffer| in an undefined state.
-Status Assemble(EncodedProgram* encoded, SinkStream* buffer);
-
-// Deserializes program from the stream set.
-// Returns C_OK if succeeded, otherwise returns an error status and
-// sets |*output| to NULL
-Status ReadEncodedProgram(SourceStreamSet* source, EncodedProgram** output);
-
-// Used to free an AssemblyProgram returned by other APIs.
-void DeleteAssemblyProgram(AssemblyProgram* program);
-
-// Used to free an EncodedProgram returned by other APIs.
-void DeleteEncodedProgram(EncodedProgram* encoded);
-
-// Adjusts |program| to look more like |model|.
-//
-Status Adjust(const AssemblyProgram& model, AssemblyProgram *program);
-
-} // namespace courgette
-#endif // COURGETTE_COURGETTE_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COURGETTE_COURGETTE_H_
+#define COURGETTE_COURGETTE_H_
+
+namespace courgette {
+
+// Status codes for Courgette APIs.
+//
+// Client code should only rely on the distintion between C_OK and the other
+// status codes.
+//
+enum Status {
+ C_OK = 1, // Successful operation.
+
+ C_GENERAL_ERROR = 2, // Error other than listed below.
+
+ C_READ_OPEN_ERROR = 3, // Could not open input file for reading.
+ C_READ_ERROR = 4, // Could not read from opened input file.
+
+ C_WRITE_OPEN_ERROR = 3, // Could not open output file for writing.
+ C_WRITE_ERROR = 4, // Could not write to opened output file.
+
+ C_BAD_ENSEMBLE_MAGIC = 5, // Ensemble patch has bad magic.
+ C_BAD_ENSEMBLE_VERSION = 6, // Ensemble patch has wrong version.
+ C_BAD_ENSEMBLE_HEADER = 7, // Ensemble patch has corrupt header.
+ C_BAD_ENSEMBLE_CRC = 8, // Ensemble patch has corrupt header.
+
+ C_BAD_TRANSFORM = 12, // Transform mis-specified.
+ C_BAD_BASE = 13, // Base for transform malformed.
+
+ C_BINARY_DIFF_CRC_ERROR = 14, // Internal diff input doesn't have expected
+ // CRC.
+
+ // Internal errors.
+ C_STREAM_ERROR = 20, // Unexpected error from streams.h.
+ C_STREAM_NOT_CONSUMED = 21, // Stream has extra data, is expected to be
+ // used up.
+ C_SERIALIZATION_FAILED = 22, //
+ C_DESERIALIZATION_FAILED = 23, //
+ C_INPUT_NOT_RECOGNIZED = 24, // Unrecognized input (not an executable).
+ C_DISASSEMBLY_FAILED = 25, //
+ C_ASSEMBLY_FAILED = 26, //
+ C_ADJUSTMENT_FAILED = 27, //
+
+
+};
+
+class SinkStream;
+class SinkStreamSet;
+class SourceStream;
+class SourceStreamSet;
+
+class AssemblyProgram;
+class EncodedProgram;
+
+// Applies the patch to the bytes in |old| and writes the transformed ensemble
+// to |output|.
+// Returns C_OK unless something went wrong.
+Status ApplyEnsemblePatch(SourceStream* old, SourceStream* patch,
+ SinkStream* output);
+
+// Applies the patch in |patch_file_name| to the bytes in |old_file_name| and
+// writes the transformed ensemble to |new_file_name|.
+// Returns C_OK unless something went wrong.
+// This function first validates that the patch file has a proper header, so the
+// function can be used to 'try' a patch.
+Status ApplyEnsemblePatch(const wchar_t* old_file_name,
+ const wchar_t* patch_file_name,
+ const wchar_t* new_file_name);
+
+// Generates a patch that will transform the bytes in |old| into the bytes in
+// |target|.
+// Returns C_OK unless something when wrong (unexpected).
+Status GenerateEnsemblePatch(SourceStream* old, SourceStream* target,
+ SinkStream* patch);
+
+// Parses a Windows 32-bit 'Portable Executable' format file from memory,
+// storing the pointer to the AssemblyProgram in |*output|.
+// Returns C_OK if successful, otherwise returns an error status and sets
+// |*output| to NULL.
+Status ParseWin32X86PE(const void* buffer, size_t length,
+ AssemblyProgram** output);
+
+// Converts |program| into encoded form, returning it as |*output|.
+// Returns C_OK if succeeded, otherwise returns an error status and
+// sets |*output| to NULL
+Status Encode(AssemblyProgram* program, EncodedProgram** output);
+
+
+// Serializes |encoded| into the stream set.
+// Returns C_OK if succeeded, otherwise returns an error status.
+Status WriteEncodedProgram(EncodedProgram* encoded, SinkStreamSet* sink);
+
+// Assembles |encoded|, emitting the bytes into |buffer|.
+// Returns C_OK if succeeded, otherwise returns an error status and leaves
+// |buffer| in an undefined state.
+Status Assemble(EncodedProgram* encoded, SinkStream* buffer);
+
+// Deserializes program from the stream set.
+// Returns C_OK if succeeded, otherwise returns an error status and
+// sets |*output| to NULL
+Status ReadEncodedProgram(SourceStreamSet* source, EncodedProgram** output);
+
+// Used to free an AssemblyProgram returned by other APIs.
+void DeleteAssemblyProgram(AssemblyProgram* program);
+
+// Used to free an EncodedProgram returned by other APIs.
+void DeleteEncodedProgram(EncodedProgram* encoded);
+
+// Adjusts |program| to look more like |model|.
+//
+Status Adjust(const AssemblyProgram& model, AssemblyProgram *program);
+
+} // namespace courgette
+#endif // COURGETTE_COURGETTE_H_
diff --git a/courgette/courgette.sln b/courgette/courgette.sln
new file mode 100644
index 0000000..38e1f59
--- /dev/null
+++ b/courgette/courgette.sln
@@ -0,0 +1,111 @@
+Microsoft Visual Studio Solution File, Format Version 9.00
+# Visual Studio 2005
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_lib", "courgette_lib.vcproj", "{9A72A362-E617-4205-B9F2-43C6FB280FA1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_unittests", "courgette_unittests.vcproj", "{24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}"
+ ProjectSection(ProjectDependencies) = postProject
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1} = {9A72A362-E617-4205-B9F2-43C6FB280FA1}
+ {1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B} = {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
+ {8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_fuzz", "courgette_fuzz.vcproj", "{57C27529-8CA9-4FC3-9C02-DA05B172F785}"
+ ProjectSection(ProjectDependencies) = postProject
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1} = {9A72A362-E617-4205-B9F2-43C6FB280FA1}
+ {1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B} = {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
+ {8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette_minimal_tool", "courgette_minimal_tool.vcproj", "{EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}"
+ ProjectSection(ProjectDependencies) = postProject
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1} = {9A72A362-E617-4205-B9F2-43C6FB280FA1}
+ {1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
+ {8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "courgette", "courgette.vcproj", "{4EA8CE12-9C6F-45E5-9D08-720383FE3685}"
+ ProjectSection(ProjectDependencies) = postProject
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1} = {9A72A362-E617-4205-B9F2-43C6FB280FA1}
+ {1832A374-8A74-4F9E-B536-69A699B3E165} = {1832A374-8A74-4F9E-B536-69A699B3E165}
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {F22022F0-2D3B-5610-4E80-C674A8E01C5A}
+ {8C27D792-2648-4F5E-9ED0-374276327308} = {8C27D792-2648-4F5E-9ED0-374276327308}
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dependencies", "dependencies", "{3C050794-ECB2-85EB-D650-18D00BF2A989}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icuuc", "..\third_party\icu38\icuuc.vcproj", "{8C27D792-2648-4F5E-9ED0-374276327308}"
+ ProjectSection(ProjectDependencies) = postProject
+ {A0D94973-D355-47A5-A1E2-3456F321F010} = {A0D94973-D355-47A5-A1E2-3456F321F010}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icui18n", "..\third_party\icu38\icui18n.vcproj", "{F22022F0-2D3B-5610-4E80-C674A8E01C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icudata", "..\third_party\icu38\icudata.vcproj", "{A0D94973-D355-47A5-A1E2-3456F321F010}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base", "..\base\base.vcproj", "{1832A374-8A74-4F9E-B536-69A699B3E165}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest", "..\testing\gtest.vcproj", "{BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Release|Win32 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {1832A374-8A74-4F9E-B536-69A699B3E165}.Debug|Win32.ActiveCfg = Debug|Win32
+ {1832A374-8A74-4F9E-B536-69A699B3E165}.Debug|Win32.Build.0 = Debug|Win32
+ {1832A374-8A74-4F9E-B536-69A699B3E165}.Release|Win32.ActiveCfg = Release|Win32
+ {1832A374-8A74-4F9E-B536-69A699B3E165}.Release|Win32.Build.0 = Release|Win32
+ {24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}.Debug|Win32.ActiveCfg = Debug|Win32
+ {24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}.Debug|Win32.Build.0 = Debug|Win32
+ {24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}.Release|Win32.ActiveCfg = Release|Win32
+ {24309F1A-4035-46F9-A3D8-F47DC4BCC2B8}.Release|Win32.Build.0 = Release|Win32
+ {4EA8CE12-9C6F-45E5-9D08-720383FE3685}.Debug|Win32.ActiveCfg = Debug|Win32
+ {4EA8CE12-9C6F-45E5-9D08-720383FE3685}.Debug|Win32.Build.0 = Debug|Win32
+ {4EA8CE12-9C6F-45E5-9D08-720383FE3685}.Release|Win32.ActiveCfg = Release|Win32
+ {4EA8CE12-9C6F-45E5-9D08-720383FE3685}.Release|Win32.Build.0 = Release|Win32
+ {57C27529-8CA9-4FC3-9C02-DA05B172F785}.Debug|Win32.ActiveCfg = Debug|Win32
+ {57C27529-8CA9-4FC3-9C02-DA05B172F785}.Debug|Win32.Build.0 = Debug|Win32
+ {57C27529-8CA9-4FC3-9C02-DA05B172F785}.Release|Win32.ActiveCfg = Release|Win32
+ {57C27529-8CA9-4FC3-9C02-DA05B172F785}.Release|Win32.Build.0 = Release|Win32
+ {8C27D792-2648-4F5E-9ED0-374276327308}.Debug|Win32.ActiveCfg = Debug|Win32
+ {8C27D792-2648-4F5E-9ED0-374276327308}.Debug|Win32.Build.0 = Debug|Win32
+ {8C27D792-2648-4F5E-9ED0-374276327308}.Release|Win32.ActiveCfg = Release|Win32
+ {8C27D792-2648-4F5E-9ED0-374276327308}.Release|Win32.Build.0 = Release|Win32
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1}.Debug|Win32.ActiveCfg = Debug|Win32
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1}.Debug|Win32.Build.0 = Debug|Win32
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1}.Release|Win32.ActiveCfg = Release|Win32
+ {9A72A362-E617-4205-B9F2-43C6FB280FA1}.Release|Win32.Build.0 = Release|Win32
+ {A0D94973-D355-47A5-A1E2-3456F321F010}.Debug|Win32.ActiveCfg = Debug|Win32
+ {A0D94973-D355-47A5-A1E2-3456F321F010}.Debug|Win32.Build.0 = Debug|Win32
+ {A0D94973-D355-47A5-A1E2-3456F321F010}.Release|Win32.ActiveCfg = Release|Win32
+ {A0D94973-D355-47A5-A1E2-3456F321F010}.Release|Win32.Build.0 = Release|Win32
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}.Debug|Win32.ActiveCfg = Debug|Win32
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}.Debug|Win32.Build.0 = Debug|Win32
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}.Release|Win32.ActiveCfg = Release|Win32
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B}.Release|Win32.Build.0 = Release|Win32
+ {EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}.Debug|Win32.ActiveCfg = Debug|Win32
+ {EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}.Debug|Win32.Build.0 = Debug|Win32
+ {EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}.Release|Win32.ActiveCfg = Release|Win32
+ {EB79415F-2F17-4BDC-AADD-4CA4C2D21B73}.Release|Win32.Build.0 = Release|Win32
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A}.Debug|Win32.ActiveCfg = Debug|Win32
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A}.Debug|Win32.Build.0 = Debug|Win32
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A}.Release|Win32.ActiveCfg = Release|Win32
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A}.Release|Win32.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {8C27D792-2648-4F5E-9ED0-374276327308} = {3C050794-ECB2-85EB-D650-18D00BF2A989}
+ {F22022F0-2D3B-5610-4E80-C674A8E01C5A} = {3C050794-ECB2-85EB-D650-18D00BF2A989}
+ {A0D94973-D355-47A5-A1E2-3456F321F010} = {3C050794-ECB2-85EB-D650-18D00BF2A989}
+ {1832A374-8A74-4F9E-B536-69A699B3E165} = {3C050794-ECB2-85EB-D650-18D00BF2A989}
+ {BFE8E2A7-3B3B-43B0-A994-3058B852DB8B} = {3C050794-ECB2-85EB-D650-18D00BF2A989}
+ EndGlobalSection
+EndGlobal
diff --git a/third_party/courgette/courgette_minimal_tool.cc b/courgette/courgette_minimal_tool.cc
index de5cd9e..84de068 100644
--- a/third_party/courgette/courgette_minimal_tool.cc
+++ b/courgette/courgette_minimal_tool.cc
@@ -1,50 +1,50 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// 'courgette_minimal_tool' is not meant to be a serious command-line tool. It
-// has the minimum logic to apply a Courgette patch to a file. The main purpose
-// is to monitor the code size of the patcher.
-
-#include <string>
-
-#include "base/file_util.h"
-
-#include "third_party/courgette/bsdiff.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
-
-void PrintHelp() {
- fprintf(stderr,
- "Usage:\n"
- " courgette_minimal_tool <old-file-input> <patch-file-input>"
- " <new-file-output>\n"
- "\n");
-}
-
-void UsageProblem(const char* message) {
- fprintf(stderr, "%s\n", message);
- PrintHelp();
- exit(1);
-}
-
-void Problem(const char* message) {
- fprintf(stderr, "%s\n", message);
- exit(1);
-}
-
-int wmain(int argc, const wchar_t* argv[]) {
- if (argc != 4)
- UsageProblem("bad args");
-
- courgette::Status status =
- courgette::ApplyEnsemblePatch(argv[1], argv[2], argv[3]);
-
- if (status != courgette::C_OK) {
- if (status == courgette::C_READ_OPEN_ERROR) Problem("Can't open file.");
- if (status == courgette::C_WRITE_OPEN_ERROR) Problem("Can't open file.");
- if (status == courgette::C_READ_ERROR) Problem("Can't read from file.");
- if (status == courgette::C_WRITE_ERROR) Problem("Can't write to file.");
- Problem("patch failed.");
- }
-}
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// 'courgette_minimal_tool' is not meant to be a serious command-line tool. It
+// has the minimum logic to apply a Courgette patch to a file. The main purpose
+// is to monitor the code size of the patcher.
+
+#include <string>
+
+#include "base/file_util.h"
+
+#include "courgette/third_party/bsdiff.h"
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
+
+void PrintHelp() {
+ fprintf(stderr,
+ "Usage:\n"
+ " courgette_minimal_tool <old-file-input> <patch-file-input>"
+ " <new-file-output>\n"
+ "\n");
+}
+
+void UsageProblem(const char* message) {
+ fprintf(stderr, "%s\n", message);
+ PrintHelp();
+ exit(1);
+}
+
+void Problem(const char* message) {
+ fprintf(stderr, "%s\n", message);
+ exit(1);
+}
+
+int wmain(int argc, const wchar_t* argv[]) {
+ if (argc != 4)
+ UsageProblem("bad args");
+
+ courgette::Status status =
+ courgette::ApplyEnsemblePatch(argv[1], argv[2], argv[3]);
+
+ if (status != courgette::C_OK) {
+ if (status == courgette::C_READ_OPEN_ERROR) Problem("Can't open file.");
+ if (status == courgette::C_WRITE_OPEN_ERROR) Problem("Can't open file.");
+ if (status == courgette::C_READ_ERROR) Problem("Can't read from file.");
+ if (status == courgette::C_WRITE_ERROR) Problem("Can't write to file.");
+ Problem("patch failed.");
+ }
+}
diff --git a/third_party/courgette/courgette_tool.cc b/courgette/courgette_tool.cc
index 867101a7..c07f2da 100644
--- a/third_party/courgette/courgette_tool.cc
+++ b/courgette/courgette_tool.cc
@@ -1,405 +1,404 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <vector>
-#include <string>
-
-#include "base/at_exit.h"
-#include "base/basictypes.h"
-#include "base/command_line.h"
-#include "base/file_util.h"
-#include "base/logging.h"
-#include "base/string_util.h"
-
-#include "third_party/courgette/bsdiff.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
-
-
-void PrintHelp() {
- fprintf(stderr,
- "Usage:\n"
- " courgette_tool -dis <executable_file> <binary_assembly_file>\n"
- " courgette_tool -asm <binary_assembly_file> <executable_file>\n"
- " courgette_tool -disadj "
- "<executable_file> <reference> <binary_assembly_file>\n"
- " courgette_tool -gen <v1> <v2> <patch>\n"
- " courgette_tool -apply <v1> <patch> <v2>\n"
- "\n");
-}
-
-void UsageProblem(const char* message) {
- fprintf(stderr, "%s", message);
- fprintf(stderr, "\n");
- PrintHelp();
- exit(1);
-}
-
-void Problem(const char* format, ...) {
- va_list args;
- va_start(args, format);
- vfprintf(stderr, format, args);
- fprintf(stderr, "\n");
- va_end(args);
- exit(1);
-}
-
-std::string ReadOrFail(const std::wstring& file_name, const char* kind) {
- FilePath file_path(file_name);
- std::string buffer;
- if (!file_util::ReadFileToString(file_path, &buffer))
- Problem("Can't read %s file.", kind);
- return buffer;
-}
-
-void WriteSinkToFile(const courgette::SinkStream *sink,
- const std::wstring& output_file) {
- FilePath output_path(output_file);
- int count =
- file_util::WriteFile(output_path,
- reinterpret_cast<const char*>(sink->Buffer()),
- sink->Length());
- if (count == -1)
- Problem("Cant write output.");
- if (count != sink->Length())
- Problem("Incomplete write.");
-}
-
-void Disassemble(const std::wstring& input_file,
- const std::wstring& output_file) {
- std::string buffer = ReadOrFail(input_file, "input");
-
- courgette::AssemblyProgram* program = NULL;
- const courgette::Status parse_status =
- courgette::ParseWin32X86PE(buffer.c_str(), buffer.length(), &program);
-
- if (parse_status != courgette::C_OK)
- Problem("Can't parse input.");
-
- courgette::EncodedProgram* encoded = NULL;
- const courgette::Status encode_status = Encode(program, &encoded);
-
- courgette::DeleteAssemblyProgram(program);
-
- if (encode_status != courgette::C_OK)
- Problem("Can't encode program.");
-
- courgette::SinkStreamSet sinks;
-
- const courgette::Status write_status =
- courgette::WriteEncodedProgram(encoded, &sinks);
- if (write_status != courgette::C_OK)
- Problem("Can't serialize encoded program.");
-
- courgette::DeleteEncodedProgram(encoded);
-
- courgette::SinkStream sink;
- sinks.CopyTo(&sink);
-
- WriteSinkToFile(&sink, output_file);
-}
-
-void DisassembleAndAdjust(const std::wstring& program_file,
- const std::wstring& model_file,
- const std::wstring& output_file) {
- std::string program_buffer = ReadOrFail(program_file, "program");
- std::string model_buffer = ReadOrFail(model_file, "reference");
-
- courgette::AssemblyProgram* program = NULL;
- const courgette::Status parse_program_status =
- courgette::ParseWin32X86PE(program_buffer.c_str(),
- program_buffer.length(),
- &program);
- if (parse_program_status != courgette::C_OK)
- Problem("Can't parse program input.");
-
- courgette::AssemblyProgram* model = NULL;
- const courgette::Status parse_model_status =
- courgette::ParseWin32X86PE(model_buffer.c_str(),
- model_buffer.length(),
- &model);
- if (parse_model_status != courgette::C_OK)
- Problem("Can't parse model input.");
-
- const courgette::Status adjust_status = Adjust(*model, program);
- if (adjust_status != courgette::C_OK)
- Problem("Can't adjust program.");
-
- courgette::EncodedProgram* encoded = NULL;
- const courgette::Status encode_status = Encode(program, &encoded);
-
- courgette::DeleteAssemblyProgram(program);
-
- if (encode_status != courgette::C_OK)
- Problem("Can't encode program.");
-
- courgette::SinkStreamSet sinks;
-
- const courgette::Status write_status =
- courgette::WriteEncodedProgram(encoded, &sinks);
- if (write_status != courgette::C_OK)
- Problem("Can't serialize encoded program.");
-
- courgette::DeleteEncodedProgram(encoded);
-
- courgette::SinkStream sink;
- sinks.CopyTo(&sink);
-
- WriteSinkToFile(&sink, output_file);
-}
-
-// Diffs two executable files, write a set of files for the diff, one file per
-// stream of the EncodedProgram format. Each file is the bsdiff between the
-// original file's stream and the new file's stream. This is completely
-// uninteresting to users, but it is handy for seeing how much each which
-// streams are contributing to the final file size. Adjustment is optional.
-void DisassembleAdjustDiff(const std::wstring& model_file,
- const std::wstring& program_file,
- const std::wstring& output_file_root,
- bool adjust) {
- std::string model_buffer = ReadOrFail(model_file, "'old'");
- std::string program_buffer = ReadOrFail(program_file, "'new'");
-
- courgette::AssemblyProgram* model = NULL;
- const courgette::Status parse_model_status =
- courgette::ParseWin32X86PE(model_buffer.c_str(),
- model_buffer.length(),
- &model);
- if (parse_model_status != courgette::C_OK)
- Problem("Can't parse model input.");
-
- courgette::AssemblyProgram* program = NULL;
- const courgette::Status parse_program_status =
- courgette::ParseWin32X86PE(program_buffer.c_str(),
- program_buffer.length(),
- &program);
- if (parse_program_status != courgette::C_OK)
- Problem("Can't parse program input.");
-
- if (adjust) {
- const courgette::Status adjust_status = Adjust(*model, program);
- if (adjust_status != courgette::C_OK)
- Problem("Can't adjust program.");
- }
-
- courgette::EncodedProgram* encoded_program = NULL;
- const courgette::Status encode_program_status =
- Encode(program, &encoded_program);
- courgette::DeleteAssemblyProgram(program);
- if (encode_program_status != courgette::C_OK)
- Problem("Can't encode program.");
-
- courgette::EncodedProgram* encoded_model = NULL;
- const courgette::Status encode_model_status = Encode(model, &encoded_model);
- courgette::DeleteAssemblyProgram(model);
- if (encode_model_status != courgette::C_OK)
- Problem("Can't encode model.");
-
- courgette::SinkStreamSet program_sinks;
- const courgette::Status write_program_status =
- courgette::WriteEncodedProgram(encoded_program, &program_sinks);
- if (write_program_status != courgette::C_OK)
- Problem("Can't serialize encoded program.");
- courgette::DeleteEncodedProgram(encoded_program);
-
- courgette::SinkStreamSet model_sinks;
- const courgette::Status write_model_status =
- courgette::WriteEncodedProgram(encoded_model, &model_sinks);
- if (write_model_status != courgette::C_OK)
- Problem("Can't serialize encoded model.");
- courgette::DeleteEncodedProgram(encoded_program);
-
- for (int i = 0; ; ++i) {
- courgette::SinkStream* old_stream = model_sinks.stream(i);
- courgette::SinkStream* new_stream = program_sinks.stream(i);
- if (old_stream == NULL && new_stream == NULL)
- break;
-
- courgette::SourceStream old_source;
- courgette::SourceStream new_source;
- old_source.Init(*old_stream);
- new_source.Init(*new_stream);
- courgette::SinkStream patch_stream;
- courgette::BSDiffStatus status =
- courgette::CreateBinaryPatch(&old_source, &new_source, &patch_stream);
- if (status != courgette::OK) Problem("-xxx failed.");
-
- WriteSinkToFile(&patch_stream,
- output_file_root + L"-" + IntToWString(i));
- }
-}
-
-void Assemble(const std::wstring& input_file,
- const std::wstring& output_file) {
- std::string buffer = ReadOrFail(input_file, "input");
-
- courgette::SourceStreamSet sources;
- if (!sources.Init(buffer.c_str(), buffer.length()))
- Problem("Bad input file.");
-
- courgette::EncodedProgram* encoded = NULL;
- const courgette::Status read_status = ReadEncodedProgram(&sources, &encoded);
- if (read_status != courgette::C_OK)
- Problem("Bad encoded program.");
-
- courgette::SinkStream sink;
-
- const courgette::Status assemble_status = courgette::Assemble(encoded, &sink);
- if (assemble_status != courgette::C_OK)
- Problem("Can't assemble.");
-
- WriteSinkToFile(&sink, output_file);
-}
-
-void GenerateEnsemblePatch(const std::wstring& old_file,
- const std::wstring& new_file,
- const std::wstring& patch_file) {
- std::string old_buffer = ReadOrFail(old_file, "'old' input");
- std::string new_buffer = ReadOrFail(new_file, "'new' input");
-
- courgette::SourceStream old_stream;
- courgette::SourceStream new_stream;
- old_stream.Init(old_buffer);
- new_stream.Init(new_buffer);
-
- courgette::SinkStream patch_stream;
- courgette::Status status =
- courgette::GenerateEnsemblePatch(&old_stream, &new_stream, &patch_stream);
-
- if (status != courgette::C_OK) Problem("-gen failed.");
-
- WriteSinkToFile(&patch_stream, patch_file);
-}
-
-void ApplyEnsemblePatch(const std::wstring& old_file,
- const std::wstring& patch_file,
- const std::wstring& new_file) {
- std::string old_buffer = ReadOrFail(old_file, "'old' input");
- std::string patch_buffer = ReadOrFail(patch_file, "'patch' input");
-
- courgette::SourceStream old_stream;
- courgette::SourceStream patch_stream;
- old_stream.Init(old_buffer);
- patch_stream.Init(patch_buffer);
- courgette::SinkStream new_stream;
- courgette::Status status =
- courgette::ApplyEnsemblePatch(&old_stream, &patch_stream, &new_stream);
-
- if (status != courgette::C_OK) Problem("-apply failed.");
-
- WriteSinkToFile(&new_stream, new_file);
-}
-
-void GenerateBSDiffPatch(const std::wstring& old_file,
- const std::wstring& new_file,
- const std::wstring& patch_file) {
- std::string old_buffer = ReadOrFail(old_file, "'old' input");
- std::string new_buffer = ReadOrFail(new_file, "'new' input");
-
- courgette::SourceStream old_stream;
- courgette::SourceStream new_stream;
- old_stream.Init(old_buffer);
- new_stream.Init(new_buffer);
-
- courgette::SinkStream patch_stream;
- courgette::BSDiffStatus status =
- courgette::CreateBinaryPatch(&old_stream, &new_stream, &patch_stream);
-
- if (status != courgette::OK) Problem("-genbsdiff failed.");
-
- WriteSinkToFile(&patch_stream, patch_file);
-}
-
-void ApplyBSDiffPatch(const std::wstring& old_file,
- const std::wstring& patch_file,
- const std::wstring& new_file) {
- std::string old_buffer = ReadOrFail(old_file, "'old' input");
- std::string patch_buffer = ReadOrFail(patch_file, "'patch' input");
-
- courgette::SourceStream old_stream;
- courgette::SourceStream patch_stream;
- old_stream.Init(old_buffer);
- patch_stream.Init(patch_buffer);
-
- courgette::SinkStream new_stream;
- courgette::BSDiffStatus status =
- courgette::ApplyBinaryPatch(&old_stream, &patch_stream, &new_stream);
-
- if (status != courgette::OK) Problem("-applybsdiff failed.");
-
- WriteSinkToFile(&new_stream, new_file);
-}
-
-int main(int argc, const char* argv[]) {
- base::AtExitManager at_exit_manager;
- CommandLine::Init(argc, argv);
- const CommandLine& command_line = *CommandLine::ForCurrentProcess();
-
- bool cmd_dis = command_line.HasSwitch(L"dis");
- bool cmd_asm = command_line.HasSwitch(L"asm");
- bool cmd_disadj = command_line.HasSwitch(L"disadj");
- bool cmd_make_patch = command_line.HasSwitch(L"gen");
- bool cmd_apply_patch = command_line.HasSwitch(L"apply");
- bool cmd_make_bsdiff_patch = command_line.HasSwitch(L"genbsdiff");
- bool cmd_apply_bsdiff_patch = command_line.HasSwitch(L"applybsdiff");
- bool cmd_spread_1_adjusted = command_line.HasSwitch(L"gen1a");
- bool cmd_spread_1_unadjusted = command_line.HasSwitch(L"gen1u");
-
- std::vector<std::wstring> values = command_line.GetLooseValues();
-
- // '-repeat=N' is for debugging. Running many iterations can reveal leaks and
- // bugs in cleanup.
- int repeat_count = 1;
- std::wstring repeat_switch = command_line.GetSwitchValue(L"repeat");
- if (!repeat_switch.empty())
- if (!StringToInt(repeat_switch, &repeat_count))
- repeat_count = 1;
-
- if (cmd_dis + cmd_asm + cmd_disadj + cmd_make_patch + cmd_apply_patch +
- cmd_make_bsdiff_patch + cmd_apply_bsdiff_patch +
- cmd_spread_1_adjusted + cmd_spread_1_unadjusted
- != 1)
- UsageProblem(
- "Must have exactly one of:\n"
- " -asm, -dis, -disadj, -gen or -apply, -genbsdiff or -applybsdiff.");
-
- while (repeat_count-- > 0) {
- if (cmd_dis) {
- if (values.size() != 2)
- UsageProblem("-dis <executable_file> <courgette_file>");
- Disassemble(values[0], values[1]);
- } else if (cmd_asm) {
- if (values.size() != 2)
- UsageProblem("-asm <courgette_file_input> <executable_file_output>");
- Assemble(values[0], values[1]);
- } else if (cmd_disadj) {
- if (values.size() != 3)
- UsageProblem("-disadj <executable_file> <model> <courgette_file>");
- DisassembleAndAdjust(values[0], values[1], values[2]);
- } else if (cmd_make_patch) {
- if (values.size() != 3)
- UsageProblem("-gen <old_file> <new_file> <patch_file>");
- GenerateEnsemblePatch(values[0], values[1], values[2]);
- } else if (cmd_apply_patch) {
- if (values.size() != 3)
- UsageProblem("-apply <old_file> <patch_file> <new_file>");
- ApplyEnsemblePatch(values[0], values[1], values[2]);
- } else if (cmd_make_bsdiff_patch) {
- if (values.size() != 3)
- UsageProblem("-genbsdiff <old_file> <new_file> <patch_file>");
- GenerateBSDiffPatch(values[0], values[1], values[2]);
- } else if (cmd_apply_bsdiff_patch) {
- if (values.size() != 3)
- UsageProblem("-applybsdiff <old_file> <patch_file> <new_file>");
- ApplyBSDiffPatch(values[0], values[1], values[2]);
- } else if (cmd_spread_1_adjusted || cmd_spread_1_unadjusted) {
- if (values.size() != 3)
- UsageProblem("-gen1[au] <old_file> <new_file> <patch_files_root>");
- DisassembleAdjustDiff(values[0], values[1], values[2],
- cmd_spread_1_adjusted);
- } else {
- UsageProblem("No operation specified");
- }
- }
-}
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <vector>
+#include <string>
+
+#include "base/at_exit.h"
+#include "base/basictypes.h"
+#include "base/command_line.h"
+#include "base/file_util.h"
+#include "base/logging.h"
+#include "base/string_util.h"
+
+#include "courgette/third_party/bsdiff.h"
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
+
+
+void PrintHelp() {
+ fprintf(stderr,
+ "Usage:\n"
+ " courgette -dis <executable_file> <binary_assembly_file>\n"
+ " courgette -asm <binary_assembly_file> <executable_file>\n"
+ " courgette -disadj <executable_file> <reference> <binary_assembly_file>\n"
+ " courgette -gen <v1> <v2> <patch>\n"
+ " courgette -apply <v1> <patch> <v2>\n"
+ "\n");
+}
+
+void UsageProblem(const char* message) {
+ fprintf(stderr, "%s", message);
+ fprintf(stderr, "\n");
+ PrintHelp();
+ exit(1);
+}
+
+void Problem(const char* format, ...) {
+ va_list args;
+ va_start(args, format);
+ vfprintf(stderr, format, args);
+ fprintf(stderr, "\n");
+ va_end(args);
+ exit(1);
+}
+
+std::string ReadOrFail(const std::wstring& file_name, const char* kind) {
+ FilePath file_path(file_name);
+ std::string buffer;
+ if (!file_util::ReadFileToString(file_path, &buffer))
+ Problem("Can't read %s file.", kind);
+ return buffer;
+}
+
+void WriteSinkToFile(const courgette::SinkStream *sink,
+ const std::wstring& output_file) {
+ FilePath output_path(output_file);
+ int count =
+ file_util::WriteFile(output_path,
+ reinterpret_cast<const char*>(sink->Buffer()),
+ sink->Length());
+ if (count == -1)
+ Problem("Cant write output.");
+ if (count != sink->Length())
+ Problem("Incomplete write.");
+}
+
+void Disassemble(const std::wstring& input_file,
+ const std::wstring& output_file) {
+ std::string buffer = ReadOrFail(input_file, "input");
+
+ courgette::AssemblyProgram* program = NULL;
+ const courgette::Status parse_status =
+ courgette::ParseWin32X86PE(buffer.c_str(), buffer.length(), &program);
+
+ if (parse_status != courgette::C_OK)
+ Problem("Can't parse input.");
+
+ courgette::EncodedProgram* encoded = NULL;
+ const courgette::Status encode_status = Encode(program, &encoded);
+
+ courgette::DeleteAssemblyProgram(program);
+
+ if (encode_status != courgette::C_OK)
+ Problem("Can't encode program.");
+
+ courgette::SinkStreamSet sinks;
+
+ const courgette::Status write_status =
+ courgette::WriteEncodedProgram(encoded, &sinks);
+ if (write_status != courgette::C_OK)
+ Problem("Can't serialize encoded program.");
+
+ courgette::DeleteEncodedProgram(encoded);
+
+ courgette::SinkStream sink;
+ sinks.CopyTo(&sink);
+
+ WriteSinkToFile(&sink, output_file);
+}
+
+void DisassembleAndAdjust(const std::wstring& program_file,
+ const std::wstring& model_file,
+ const std::wstring& output_file) {
+ std::string program_buffer = ReadOrFail(program_file, "program");
+ std::string model_buffer = ReadOrFail(model_file, "reference");
+
+ courgette::AssemblyProgram* program = NULL;
+ const courgette::Status parse_program_status =
+ courgette::ParseWin32X86PE(program_buffer.c_str(),
+ program_buffer.length(),
+ &program);
+ if (parse_program_status != courgette::C_OK)
+ Problem("Can't parse program input.");
+
+ courgette::AssemblyProgram* model = NULL;
+ const courgette::Status parse_model_status =
+ courgette::ParseWin32X86PE(model_buffer.c_str(),
+ model_buffer.length(),
+ &model);
+ if (parse_model_status != courgette::C_OK)
+ Problem("Can't parse model input.");
+
+ const courgette::Status adjust_status = Adjust(*model, program);
+ if (adjust_status != courgette::C_OK)
+ Problem("Can't adjust program.");
+
+ courgette::EncodedProgram* encoded = NULL;
+ const courgette::Status encode_status = Encode(program, &encoded);
+
+ courgette::DeleteAssemblyProgram(program);
+
+ if (encode_status != courgette::C_OK)
+ Problem("Can't encode program.");
+
+ courgette::SinkStreamSet sinks;
+
+ const courgette::Status write_status =
+ courgette::WriteEncodedProgram(encoded, &sinks);
+ if (write_status != courgette::C_OK)
+ Problem("Can't serialize encoded program.");
+
+ courgette::DeleteEncodedProgram(encoded);
+
+ courgette::SinkStream sink;
+ sinks.CopyTo(&sink);
+
+ WriteSinkToFile(&sink, output_file);
+}
+
+// Diffs two executable files, write a set of files for the diff, one file per
+// stream of the EncodedProgram format. Each file is the bsdiff between the
+// original file's stream and the new file's stream. This is completely
+// uninteresting to users, but it is handy for seeing how much each which
+// streams are contributing to the final file size. Adjustment is optional.
+void DisassembleAdjustDiff(const std::wstring& model_file,
+ const std::wstring& program_file,
+ const std::wstring& output_file_root,
+ bool adjust) {
+ std::string model_buffer = ReadOrFail(model_file, "'old'");
+ std::string program_buffer = ReadOrFail(program_file, "'new'");
+
+ courgette::AssemblyProgram* model = NULL;
+ const courgette::Status parse_model_status =
+ courgette::ParseWin32X86PE(model_buffer.c_str(),
+ model_buffer.length(),
+ &model);
+ if (parse_model_status != courgette::C_OK)
+ Problem("Can't parse model input.");
+
+ courgette::AssemblyProgram* program = NULL;
+ const courgette::Status parse_program_status =
+ courgette::ParseWin32X86PE(program_buffer.c_str(),
+ program_buffer.length(),
+ &program);
+ if (parse_program_status != courgette::C_OK)
+ Problem("Can't parse program input.");
+
+ if (adjust) {
+ const courgette::Status adjust_status = Adjust(*model, program);
+ if (adjust_status != courgette::C_OK)
+ Problem("Can't adjust program.");
+ }
+
+ courgette::EncodedProgram* encoded_program = NULL;
+ const courgette::Status encode_program_status =
+ Encode(program, &encoded_program);
+ courgette::DeleteAssemblyProgram(program);
+ if (encode_program_status != courgette::C_OK)
+ Problem("Can't encode program.");
+
+ courgette::EncodedProgram* encoded_model = NULL;
+ const courgette::Status encode_model_status = Encode(model, &encoded_model);
+ courgette::DeleteAssemblyProgram(model);
+ if (encode_model_status != courgette::C_OK)
+ Problem("Can't encode model.");
+
+ courgette::SinkStreamSet program_sinks;
+ const courgette::Status write_program_status =
+ courgette::WriteEncodedProgram(encoded_program, &program_sinks);
+ if (write_program_status != courgette::C_OK)
+ Problem("Can't serialize encoded program.");
+ courgette::DeleteEncodedProgram(encoded_program);
+
+ courgette::SinkStreamSet model_sinks;
+ const courgette::Status write_model_status =
+ courgette::WriteEncodedProgram(encoded_model, &model_sinks);
+ if (write_model_status != courgette::C_OK)
+ Problem("Can't serialize encoded model.");
+ courgette::DeleteEncodedProgram(encoded_program);
+
+ for (int i = 0; ; ++i) {
+ courgette::SinkStream* old_stream = model_sinks.stream(i);
+ courgette::SinkStream* new_stream = program_sinks.stream(i);
+ if (old_stream == NULL && new_stream == NULL)
+ break;
+
+ courgette::SourceStream old_source;
+ courgette::SourceStream new_source;
+ old_source.Init(*old_stream);
+ new_source.Init(*new_stream);
+ courgette::SinkStream patch_stream;
+ courgette::BSDiffStatus status =
+ courgette::CreateBinaryPatch(&old_source, &new_source, &patch_stream);
+ if (status != courgette::OK) Problem("-xxx failed.");
+
+ WriteSinkToFile(&patch_stream,
+ output_file_root + L"-" + IntToWString(i));
+ }
+}
+
+void Assemble(const std::wstring& input_file,
+ const std::wstring& output_file) {
+ std::string buffer = ReadOrFail(input_file, "input");
+
+ courgette::SourceStreamSet sources;
+ if (!sources.Init(buffer.c_str(), buffer.length()))
+ Problem("Bad input file.");
+
+ courgette::EncodedProgram* encoded = NULL;
+ const courgette::Status read_status = ReadEncodedProgram(&sources, &encoded);
+ if (read_status != courgette::C_OK)
+ Problem("Bad encoded program.");
+
+ courgette::SinkStream sink;
+
+ const courgette::Status assemble_status = courgette::Assemble(encoded, &sink);
+ if (assemble_status != courgette::C_OK)
+ Problem("Can't assemble.");
+
+ WriteSinkToFile(&sink, output_file);
+}
+
+void GenerateEnsemblePatch(const std::wstring& old_file,
+ const std::wstring& new_file,
+ const std::wstring& patch_file) {
+ std::string old_buffer = ReadOrFail(old_file, "'old' input");
+ std::string new_buffer = ReadOrFail(new_file, "'new' input");
+
+ courgette::SourceStream old_stream;
+ courgette::SourceStream new_stream;
+ old_stream.Init(old_buffer);
+ new_stream.Init(new_buffer);
+
+ courgette::SinkStream patch_stream;
+ courgette::Status status =
+ courgette::GenerateEnsemblePatch(&old_stream, &new_stream, &patch_stream);
+
+ if (status != courgette::C_OK) Problem("-gen failed.");
+
+ WriteSinkToFile(&patch_stream, patch_file);
+}
+
+void ApplyEnsemblePatch(const std::wstring& old_file,
+ const std::wstring& patch_file,
+ const std::wstring& new_file) {
+ std::string old_buffer = ReadOrFail(old_file, "'old' input");
+ std::string patch_buffer = ReadOrFail(patch_file, "'patch' input");
+
+ courgette::SourceStream old_stream;
+ courgette::SourceStream patch_stream;
+ old_stream.Init(old_buffer);
+ patch_stream.Init(patch_buffer);
+ courgette::SinkStream new_stream;
+ courgette::Status status =
+ courgette::ApplyEnsemblePatch(&old_stream, &patch_stream, &new_stream);
+
+ if (status != courgette::C_OK) Problem("-apply failed.");
+
+ WriteSinkToFile(&new_stream, new_file);
+}
+
+void GenerateBSDiffPatch(const std::wstring& old_file,
+ const std::wstring& new_file,
+ const std::wstring& patch_file) {
+ std::string old_buffer = ReadOrFail(old_file, "'old' input");
+ std::string new_buffer = ReadOrFail(new_file, "'new' input");
+
+ courgette::SourceStream old_stream;
+ courgette::SourceStream new_stream;
+ old_stream.Init(old_buffer);
+ new_stream.Init(new_buffer);
+
+ courgette::SinkStream patch_stream;
+ courgette::BSDiffStatus status =
+ courgette::CreateBinaryPatch(&old_stream, &new_stream, &patch_stream);
+
+ if (status != courgette::OK) Problem("-genbsdiff failed.");
+
+ WriteSinkToFile(&patch_stream, patch_file);
+}
+
+void ApplyBSDiffPatch(const std::wstring& old_file,
+ const std::wstring& patch_file,
+ const std::wstring& new_file) {
+ std::string old_buffer = ReadOrFail(old_file, "'old' input");
+ std::string patch_buffer = ReadOrFail(patch_file, "'patch' input");
+
+ courgette::SourceStream old_stream;
+ courgette::SourceStream patch_stream;
+ old_stream.Init(old_buffer);
+ patch_stream.Init(patch_buffer);
+
+ courgette::SinkStream new_stream;
+ courgette::BSDiffStatus status =
+ courgette::ApplyBinaryPatch(&old_stream, &patch_stream, &new_stream);
+
+ if (status != courgette::OK) Problem("-applybsdiff failed.");
+
+ WriteSinkToFile(&new_stream, new_file);
+}
+
+int main(int argc, const char* argv[]) {
+ base::AtExitManager at_exit_manager;
+ CommandLine::Init(argc, argv);
+ const CommandLine& command_line = *CommandLine::ForCurrentProcess();
+
+ bool cmd_dis = command_line.HasSwitch(L"dis");
+ bool cmd_asm = command_line.HasSwitch(L"asm");
+ bool cmd_disadj = command_line.HasSwitch(L"disadj");
+ bool cmd_make_patch = command_line.HasSwitch(L"gen");
+ bool cmd_apply_patch = command_line.HasSwitch(L"apply");
+ bool cmd_make_bsdiff_patch = command_line.HasSwitch(L"genbsdiff");
+ bool cmd_apply_bsdiff_patch = command_line.HasSwitch(L"applybsdiff");
+ bool cmd_spread_1_adjusted = command_line.HasSwitch(L"gen1a");
+ bool cmd_spread_1_unadjusted = command_line.HasSwitch(L"gen1u");
+
+ std::vector<std::wstring> values = command_line.GetLooseValues();
+
+ // '-repeat=N' is for debugging. Running many iterations can reveal leaks and
+ // bugs in cleanup.
+ int repeat_count = 1;
+ std::wstring repeat_switch = command_line.GetSwitchValue(L"repeat");
+ if (!repeat_switch.empty())
+ if (!StringToInt(repeat_switch, &repeat_count))
+ repeat_count = 1;
+
+ if (cmd_dis + cmd_asm + cmd_disadj + cmd_make_patch + cmd_apply_patch +
+ cmd_make_bsdiff_patch + cmd_apply_bsdiff_patch +
+ cmd_spread_1_adjusted + cmd_spread_1_unadjusted
+ != 1)
+ UsageProblem(
+ "Must have exactly one of:\n"
+ " -asm, -dis, -disadj, -gen or -apply, -genbsdiff or -applybsdiff.");
+
+ while (repeat_count-- > 0) {
+ if (cmd_dis) {
+ if (values.size() != 2)
+ UsageProblem("-dis <executable_file> <courgette_file>");
+ Disassemble(values[0], values[1]);
+ } else if (cmd_asm) {
+ if (values.size() != 2)
+ UsageProblem("-asm <courgette_file_input> <executable_file_output>");
+ Assemble(values[0], values[1]);
+ } else if (cmd_disadj) {
+ if (values.size() != 3)
+ UsageProblem("-disadj <executable_file> <model> <courgette_file>");
+ DisassembleAndAdjust(values[0], values[1], values[2]);
+ } else if (cmd_make_patch) {
+ if (values.size() != 3)
+ UsageProblem("-gen <old_file> <new_file> <patch_file>");
+ GenerateEnsemblePatch(values[0], values[1], values[2]);
+ } else if (cmd_apply_patch) {
+ if (values.size() != 3)
+ UsageProblem("-apply <old_file> <patch_file> <new_file>");
+ ApplyEnsemblePatch(values[0], values[1], values[2]);
+ } else if (cmd_make_bsdiff_patch) {
+ if (values.size() != 3)
+ UsageProblem("-genbsdiff <old_file> <new_file> <patch_file>");
+ GenerateBSDiffPatch(values[0], values[1], values[2]);
+ } else if (cmd_apply_bsdiff_patch) {
+ if (values.size() != 3)
+ UsageProblem("-applybsdiff <old_file> <patch_file> <new_file>");
+ ApplyBSDiffPatch(values[0], values[1], values[2]);
+ } else if (cmd_spread_1_adjusted || cmd_spread_1_unadjusted) {
+ if (values.size() != 3)
+ UsageProblem("-gen1[au] <old_file> <new_file> <patch_files_root>");
+ DisassembleAdjustDiff(values[0], values[1], values[2],
+ cmd_spread_1_adjusted);
+ } else {
+ UsageProblem("No operation specified");
+ }
+ }
+}
diff --git a/third_party/courgette/crc.cc b/courgette/crc.cc
index 6bf51fe..60c8c93 100644
--- a/third_party/courgette/crc.cc
+++ b/courgette/crc.cc
@@ -1,22 +1,22 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Calculate Crc by calling CRC method in LZMA SDK
-
-#include "third_party/courgette/crc.h"
-
-extern "C" {
-#include "third_party/lzma_sdk/7zCrc.h"
-}
-
-namespace courgette {
-
-uint32 CalculateCrc(const uint8* buffer, size_t size) {
- // CrcGenerateTable();
- uint32 crc = 0xffffffffL;
- // crc = ~CrcCalc(buffer, size);
- return crc;
-}
-
-} // namespace
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Calculate Crc by calling CRC method in LZMA SDK
+
+#include "courgette/crc.h"
+
+extern "C" {
+#include "third_party/lzma_sdk/7zCrc.h"
+}
+
+namespace courgette {
+
+uint32 CalculateCrc(const uint8* buffer, size_t size) {
+ // CrcGenerateTable();
+ uint32 crc = 0xffffffffL;
+ // crc = ~CrcCalc(buffer, size);
+ return crc;
+}
+
+} // namespace
diff --git a/third_party/courgette/crc.h b/courgette/crc.h
index 6f4fbb0..c3662bb 100644
--- a/third_party/courgette/crc.h
+++ b/courgette/crc.h
@@ -1,17 +1,17 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef COURGETTE_CRC_H_
-#define COURGETTE_CRC_H_
-
-#include "base/basictypes.h"
-
-namespace courgette {
-
-// Calculates Crc of the given buffer by calling CRC method in LZMA SDK
-//
-uint32 CalculateCrc(const uint8* buffer, size_t size);
-
-} // namespace courgette
-#endif // COURGETTE_CRC_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COURGETTE_CRC_H_
+#define COURGETTE_CRC_H_
+
+#include "base/basictypes.h"
+
+namespace courgette {
+
+// Calculates Crc of the given buffer by calling CRC method in LZMA SDK
+//
+uint32 CalculateCrc(const uint8* buffer, size_t size);
+
+} // namespace courgette
+#endif // COURGETTE_CRC_H_
diff --git a/third_party/courgette/difference_estimator.cc b/courgette/difference_estimator.cc
index 943eafb..e591f9b 100644
--- a/third_party/courgette/difference_estimator.cc
+++ b/courgette/difference_estimator.cc
@@ -1,118 +1,118 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// We want to measure the similarity of two sequences of bytes as a surrogate
-// for measuring how well a second sequence will compress differentially to the
-// first sequence.
-
-#include "third_party/courgette/difference_estimator.h"
-
-#include "base/hash_tables.h"
-
-namespace courgette {
-
-// Our difference measure is the number of k-tuples that occur in Subject that
-// don't occur in Base.
-const int kTupleSize = 4;
-
-namespace {
-
-COMPILE_ASSERT(kTupleSize >= 4 && kTupleSize <= 8, kTupleSize_between_4_and_8);
-
-size_t HashTuple(const uint8* source) {
- size_t hash1 = *reinterpret_cast<const uint32*>(source);
- size_t hash2 = *reinterpret_cast<const uint32*>(source + kTupleSize - 4);
- size_t hash = ((hash1 * 17 + hash2 * 37) + (hash1 >> 17)) ^ (hash2 >> 23);
- return hash;
-}
-
-bool RegionsEqual(const Region& a, const Region& b) {
- if (a.length() != b.length())
- return false;
- return memcmp(a.start(), b.start(), a.length()) == 0;
-}
-
-} // anonymous namepace
-
-class DifferenceEstimator::Base {
- public:
- explicit Base(const Region& region) : region_(region) { }
-
- void Init() {
- const uint8* start = region_.start();
- const uint8* end = region_.end() - (kTupleSize - 1);
- for (const uint8* p = start; p < end; ++p) {
- size_t hash = HashTuple(p);
- hashes_.insert(hash);
- }
- }
-
- const Region& region() const { return region_; }
-
- private:
- Region region_;
- base::hash_set<size_t> hashes_;
-
- friend class DifferenceEstimator;
- DISALLOW_COPY_AND_ASSIGN(Base);
-};
-
-class DifferenceEstimator::Subject {
- public:
- explicit Subject(const Region& region) : region_(region) {}
-
- const Region& region() const { return region_; }
-
- private:
- Region region_;
-
- DISALLOW_COPY_AND_ASSIGN(Subject);
-};
-
-DifferenceEstimator::DifferenceEstimator() {}
-
-DifferenceEstimator::~DifferenceEstimator() {
- for (size_t i = 0; i < owned_bases_.size(); ++i)
- delete owned_bases_[i];
- for (size_t i = 0; i < owned_subjects_.size(); ++i)
- delete owned_subjects_[i];
-}
-
-DifferenceEstimator::Base* DifferenceEstimator::MakeBase(const Region& region) {
- Base* base = new Base(region);
- base->Init();
- owned_bases_.push_back(base);
- return base;
-}
-
-DifferenceEstimator::Subject* DifferenceEstimator::MakeSubject(
- const Region& region) {
- Subject* subject = new Subject(region);
- owned_subjects_.push_back(subject);
- return subject;
-}
-
-size_t DifferenceEstimator::Measure(Base* base, Subject* subject) {
- size_t mismatches = 0;
- const uint8* start = subject->region().start();
- const uint8* end = subject->region().end() - (kTupleSize - 1);
-
- const uint8* p = start;
- while (p < end) {
- size_t hash = HashTuple(p);
- if (base->hashes_.find(hash) == base->hashes_.end()) {
- ++mismatches;
- }
- p += 1;
- }
-
- if (mismatches == 0) {
- if (RegionsEqual(base->region(), subject->region()))
- return 0;
- }
- ++mismatches; // Guarantee not zero.
- return mismatches;
-}
-
-} // namespace
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// We want to measure the similarity of two sequences of bytes as a surrogate
+// for measuring how well a second sequence will compress differentially to the
+// first sequence.
+
+#include "courgette/difference_estimator.h"
+
+#include "base/hash_tables.h"
+
+namespace courgette {
+
+// Our difference measure is the number of k-tuples that occur in Subject that
+// don't occur in Base.
+const int kTupleSize = 4;
+
+namespace {
+
+COMPILE_ASSERT(kTupleSize >= 4 && kTupleSize <= 8, kTupleSize_between_4_and_8);
+
+size_t HashTuple(const uint8* source) {
+ size_t hash1 = *reinterpret_cast<const uint32*>(source);
+ size_t hash2 = *reinterpret_cast<const uint32*>(source + kTupleSize - 4);
+ size_t hash = ((hash1 * 17 + hash2 * 37) + (hash1 >> 17)) ^ (hash2 >> 23);
+ return hash;
+}
+
+bool RegionsEqual(const Region& a, const Region& b) {
+ if (a.length() != b.length())
+ return false;
+ return memcmp(a.start(), b.start(), a.length()) == 0;
+}
+
+} // anonymous namepace
+
+class DifferenceEstimator::Base {
+ public:
+ explicit Base(const Region& region) : region_(region) { }
+
+ void Init() {
+ const uint8* start = region_.start();
+ const uint8* end = region_.end() - (kTupleSize - 1);
+ for (const uint8* p = start; p < end; ++p) {
+ size_t hash = HashTuple(p);
+ hashes_.insert(hash);
+ }
+ }
+
+ const Region& region() const { return region_; }
+
+ private:
+ Region region_;
+ base::hash_set<size_t> hashes_;
+
+ friend class DifferenceEstimator;
+ DISALLOW_COPY_AND_ASSIGN(Base);
+};
+
+class DifferenceEstimator::Subject {
+ public:
+ explicit Subject(const Region& region) : region_(region) {}
+
+ const Region& region() const { return region_; }
+
+ private:
+ Region region_;
+
+ DISALLOW_COPY_AND_ASSIGN(Subject);
+};
+
+DifferenceEstimator::DifferenceEstimator() {}
+
+DifferenceEstimator::~DifferenceEstimator() {
+ for (size_t i = 0; i < owned_bases_.size(); ++i)
+ delete owned_bases_[i];
+ for (size_t i = 0; i < owned_subjects_.size(); ++i)
+ delete owned_subjects_[i];
+}
+
+DifferenceEstimator::Base* DifferenceEstimator::MakeBase(const Region& region) {
+ Base* base = new Base(region);
+ base->Init();
+ owned_bases_.push_back(base);
+ return base;
+}
+
+DifferenceEstimator::Subject* DifferenceEstimator::MakeSubject(
+ const Region& region) {
+ Subject* subject = new Subject(region);
+ owned_subjects_.push_back(subject);
+ return subject;
+}
+
+size_t DifferenceEstimator::Measure(Base* base, Subject* subject) {
+ size_t mismatches = 0;
+ const uint8* start = subject->region().start();
+ const uint8* end = subject->region().end() - (kTupleSize - 1);
+
+ const uint8* p = start;
+ while (p < end) {
+ size_t hash = HashTuple(p);
+ if (base->hashes_.find(hash) == base->hashes_.end()) {
+ ++mismatches;
+ }
+ p += 1;
+ }
+
+ if (mismatches == 0) {
+ if (RegionsEqual(base->region(), subject->region()))
+ return 0;
+ }
+ ++mismatches; // Guarantee not zero.
+ return mismatches;
+}
+
+} // namespace
diff --git a/third_party/courgette/difference_estimator.h b/courgette/difference_estimator.h
index bd550ec..295ff93 100644
--- a/third_party/courgette/difference_estimator.h
+++ b/courgette/difference_estimator.h
@@ -1,58 +1,58 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// A DifferenceEstimator class provides a means for quickly estimating the
-// difference between two regions of memory.
-
-#ifndef COURGETTE_DIFFERENCE_ESTIMATOR_H_
-#define COURGETTE_DIFFERENCE_ESTIMATOR_H_
-
-#include <vector>
-
-#include "third_party/courgette/region.h"
-
-namespace courgette {
-
-// A DifferenceEstimator simplifies the task of determining which 'Subject' byte
-// strings (stored in regions of memory) are good matches to existing 'Base'
-// regions. The ultimate measure would be to try full differential compression
-// and measure the output size, but an estimate that correlates well with the
-// full compression is more efficient.
-//
-// The measure is asymmetric, if the Subject is a small substring of the Base
-// then it should match very well.
-//
-// The comparison is staged: first make Base and Subject objects for the regions
-// and then call 'Measure' to get the estimate. The staging allows multiple
-// comparisons to be more efficient by precomputing information used in the
-// comparison.
-//
-class DifferenceEstimator {
- public:
- DifferenceEstimator();
- ~DifferenceEstimator();
-
- class Base;
- class Subject;
-
- // This DifferenceEstimator owns the objects returned by MakeBase and
- // MakeSubject. Caller continues to own memory at |region| and must not free
- // it until ~DifferenceEstimator has been called.
- Base* MakeBase(const Region& region);
- Subject* MakeSubject(const Region& region);
-
- // Returns a value correlated with the size of the bsdiff or xdelta difference
- // from |base| to |subject|. Returns zero iff the base and subject regions
- // are bytewise identical.
- size_t Measure(Base* base, Subject* subject);
-
- private:
- std::vector<Base*> owned_bases_;
- std::vector<Subject*> owned_subjects_;
- DISALLOW_COPY_AND_ASSIGN(DifferenceEstimator);
-};
-
-} // namespace
-
-#endif // COURGETTE_DIFFERENCE_ESTIMATOR_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// A DifferenceEstimator class provides a means for quickly estimating the
+// difference between two regions of memory.
+
+#ifndef COURGETTE_DIFFERENCE_ESTIMATOR_H_
+#define COURGETTE_DIFFERENCE_ESTIMATOR_H_
+
+#include <vector>
+
+#include "courgette/region.h"
+
+namespace courgette {
+
+// A DifferenceEstimator simplifies the task of determining which 'Subject' byte
+// strings (stored in regions of memory) are good matches to existing 'Base'
+// regions. The ultimate measure would be to try full differential compression
+// and measure the output size, but an estimate that correlates well with the
+// full compression is more efficient.
+//
+// The measure is asymmetric, if the Subject is a small substring of the Base
+// then it should match very well.
+//
+// The comparison is staged: first make Base and Subject objects for the regions
+// and then call 'Measure' to get the estimate. The staging allows multiple
+// comparisons to be more efficient by precomputing information used in the
+// comparison.
+//
+class DifferenceEstimator {
+ public:
+ DifferenceEstimator();
+ ~DifferenceEstimator();
+
+ class Base;
+ class Subject;
+
+ // This DifferenceEstimator owns the objects returned by MakeBase and
+ // MakeSubject. Caller continues to own memory at |region| and must not free
+ // it until ~DifferenceEstimator has been called.
+ Base* MakeBase(const Region& region);
+ Subject* MakeSubject(const Region& region);
+
+ // Returns a value correlated with the size of the bsdiff or xdelta difference
+ // from |base| to |subject|. Returns zero iff the base and subject regions
+ // are bytewise identical.
+ size_t Measure(Base* base, Subject* subject);
+
+ private:
+ std::vector<Base*> owned_bases_;
+ std::vector<Subject*> owned_subjects_;
+ DISALLOW_COPY_AND_ASSIGN(DifferenceEstimator);
+};
+
+} // namespace
+
+#endif // COURGETTE_DIFFERENCE_ESTIMATOR_H_
diff --git a/third_party/courgette/difference_estimator_unittest.cc b/courgette/difference_estimator_unittest.cc
index 6cc8afd..913752b 100644
--- a/third_party/courgette/difference_estimator_unittest.cc
+++ b/courgette/difference_estimator_unittest.cc
@@ -1,58 +1,58 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/courgette/difference_estimator.h"
-
-#include <string>
-
-#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/courgette/region.h"
-
-using courgette::DifferenceEstimator;
-using courgette::Region;
-
-TEST(DifferenceEstimatorTest, TestSame) {
- static const char kString1[] = "Hello world";
- // kString2 is stack allocated to prevent string sharing.
- const char kString2[] = "Hello world";
- DifferenceEstimator difference_estimator;
- DifferenceEstimator::Base* base =
- difference_estimator.MakeBase(Region(kString1, sizeof(kString1)));
- DifferenceEstimator::Subject* subject =
- difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)));
- EXPECT_EQ(0, difference_estimator.Measure(base, subject));
-}
-
-TEST(DifferenceEstimatorTest, TestDifferent) {
- static const char kString1[] = "Hello world";
- static const char kString2[] = "Hello universe";
- DifferenceEstimator difference_estimator;
- DifferenceEstimator::Base* base =
- difference_estimator.MakeBase(Region(kString1, sizeof(kString1)));
- DifferenceEstimator::Subject* subject =
- difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)));
- EXPECT_EQ(10, difference_estimator.Measure(base, subject));
-}
-
-TEST(DifferenceEstimatorTest, TestDifferentSuperstring) {
- static const char kString1[] = "abcdabcdabcd";
- static const char kString2[] = "abcdabcdabcdabcd";
- DifferenceEstimator difference_estimator;
- DifferenceEstimator::Base* base =
- difference_estimator.MakeBase(Region(kString1, sizeof(kString1)-1));
- DifferenceEstimator::Subject* subject =
- difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)-1));
- EXPECT_EQ(1, difference_estimator.Measure(base, subject));
-}
-
-TEST(DifferenceEstimatorTest, TestDifferentSubstring) {
- static const char kString1[] = "abcdabcdabcdabcd";
- static const char kString2[] = "abcdabcdabcd";
- DifferenceEstimator difference_estimator;
- DifferenceEstimator::Base* base =
- difference_estimator.MakeBase(Region(kString1, sizeof(kString1)-1));
- DifferenceEstimator::Subject* subject =
- difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)-1));
- EXPECT_EQ(1, difference_estimator.Measure(base, subject));
-}
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "courgette/difference_estimator.h"
+
+#include <string>
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "courgette/region.h"
+
+using courgette::DifferenceEstimator;
+using courgette::Region;
+
+TEST(DifferenceEstimatorTest, TestSame) {
+ static const char kString1[] = "Hello world";
+ // kString2 is stack allocated to prevent string sharing.
+ const char kString2[] = "Hello world";
+ DifferenceEstimator difference_estimator;
+ DifferenceEstimator::Base* base =
+ difference_estimator.MakeBase(Region(kString1, sizeof(kString1)));
+ DifferenceEstimator::Subject* subject =
+ difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)));
+ EXPECT_EQ(0, difference_estimator.Measure(base, subject));
+}
+
+TEST(DifferenceEstimatorTest, TestDifferent) {
+ static const char kString1[] = "Hello world";
+ static const char kString2[] = "Hello universe";
+ DifferenceEstimator difference_estimator;
+ DifferenceEstimator::Base* base =
+ difference_estimator.MakeBase(Region(kString1, sizeof(kString1)));
+ DifferenceEstimator::Subject* subject =
+ difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)));
+ EXPECT_EQ(10, difference_estimator.Measure(base, subject));
+}
+
+TEST(DifferenceEstimatorTest, TestDifferentSuperstring) {
+ static const char kString1[] = "abcdabcdabcd";
+ static const char kString2[] = "abcdabcdabcdabcd";
+ DifferenceEstimator difference_estimator;
+ DifferenceEstimator::Base* base =
+ difference_estimator.MakeBase(Region(kString1, sizeof(kString1)-1));
+ DifferenceEstimator::Subject* subject =
+ difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)-1));
+ EXPECT_EQ(1, difference_estimator.Measure(base, subject));
+}
+
+TEST(DifferenceEstimatorTest, TestDifferentSubstring) {
+ static const char kString1[] = "abcdabcdabcdabcd";
+ static const char kString2[] = "abcdabcdabcd";
+ DifferenceEstimator difference_estimator;
+ DifferenceEstimator::Base* base =
+ difference_estimator.MakeBase(Region(kString1, sizeof(kString1)-1));
+ DifferenceEstimator::Subject* subject =
+ difference_estimator.MakeSubject(Region(kString2, sizeof(kString2)-1));
+ EXPECT_EQ(1, difference_estimator.Measure(base, subject));
+}
diff --git a/third_party/courgette/disassembler.cc b/courgette/disassembler.cc
index 6ebb2da..6395d18 100644
--- a/third_party/courgette/disassembler.cc
+++ b/courgette/disassembler.cc
@@ -1,436 +1,436 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/courgette/disassembler.h"
-
-#include <algorithm>
-#include <iostream>
-#include <string>
-#include <vector>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-
-#include "third_party/courgette/assembly_program.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/encoded_program.h"
-#include "third_party/courgette/image_info.h"
-
-// COURGETTE_HISTOGRAM_TARGETS prints out a histogram of how frequently
-// different target addresses are referenced. Purely for debugging.
-#define COURGETTE_HISTOGRAM_TARGETS 0
-
-namespace courgette {
-
-class DisassemblerWin32X86 : public Disassembler {
- public:
- explicit DisassemblerWin32X86(PEInfo* pe_info)
- : pe_info_(pe_info),
- incomplete_disassembly_(false) {
- }
-
- virtual bool Disassemble(AssemblyProgram* target);
-
- virtual void Destroy() { delete this; }
-
- protected:
- PEInfo& pe_info() { return *pe_info_; }
-
- void ParseFile(AssemblyProgram* target);
- bool ParseAbs32Relocs();
- void ParseRel32RelocsFromSections();
- void ParseRel32RelocsFromSection(const Section* section);
-
- void ParseNonSectionFileRegion(uint32 start_file_offset,
- uint32 end_file_offset,
- AssemblyProgram* program);
- void ParseFileRegion(const Section* section,
- uint32 start_file_offset, uint32 end_file_offset,
- AssemblyProgram* program);
-
-#if COURGETTE_HISTOGRAM_TARGETS
- void HistogramTargets(const char* kind, const std::map<RVA, int>& map);
-#endif
-
- PEInfo* pe_info_;
- bool incomplete_disassembly_; // 'true' if can leave out 'uninteresting' bits
-
- std::vector<RVA> abs32_locations_;
- std::vector<RVA> rel32_locations_;
-
-#if COURGETTE_HISTOGRAM_TARGETS
- std::map<RVA, int> abs32_target_rvas_;
- std::map<RVA, int> rel32_target_rvas_;
-#endif
-};
-
-bool DisassemblerWin32X86::Disassemble(AssemblyProgram* target) {
- if (!pe_info().ok())
- return false;
-
- target->set_image_base(pe_info().image_base());
-
- if (!ParseAbs32Relocs())
- return false;
-
- ParseRel32RelocsFromSections();
-
- ParseFile(target);
-
- target->DefaultAssignIndexes();
- return true;
-}
-
-static uint32 Read32LittleEndian(const void* address) {
- return *reinterpret_cast<const uint32*>(address);
-}
-
-bool DisassemblerWin32X86::ParseAbs32Relocs() {
- abs32_locations_.clear();
- if (!pe_info().ParseRelocs(&abs32_locations_))
- return false;
-
- std::sort(abs32_locations_.begin(), abs32_locations_.end());
-
-#if COURGETTE_HISTOGRAM_TARGETS
- for (size_t i = 0; i < abs32_locations_.size(); ++i) {
- RVA rva = abs32_locations_[i];
- // The 4 bytes at the relocation are a reference to some address.
- uint32 target_address = Read32LittleEndian(pe_info().RVAToPointer(rva));
- ++abs32_target_rvas_[target_address - pe_info().image_base()];
- }
-#endif
- return true;
-}
-
-void DisassemblerWin32X86::ParseRel32RelocsFromSections() {
- uint32 file_offset = 0;
- while (file_offset < pe_info().length()) {
- const Section* section = pe_info().FindNextSection(file_offset);
- if (section == NULL)
- break;
- if (file_offset < section->file_offset_of_raw_data)
- file_offset = section->file_offset_of_raw_data;
- ParseRel32RelocsFromSection(section);
- file_offset += section->size_of_raw_data;
- }
- std::sort(rel32_locations_.begin(), rel32_locations_.end());
-
-#if COURGETTE_HISTOGRAM_TARGETS
- LOG(INFO) << "abs32_locations_ " << abs32_locations_.size();
- LOG(INFO) << "rel32_locations_ " << rel32_locations_.size();
- LOG(INFO) << "abs32_target_rvas_ " << abs32_target_rvas_.size();
- LOG(INFO) << "rel32_target_rvas_ " << rel32_target_rvas_.size();
-
- int common = 0;
- std::map<RVA, int>::iterator abs32_iter = abs32_target_rvas_.begin();
- std::map<RVA, int>::iterator rel32_iter = rel32_target_rvas_.begin();
- while (abs32_iter != abs32_target_rvas_.end() &&
- rel32_iter != rel32_target_rvas_.end()) {
- if (abs32_iter->first < rel32_iter->first)
- ++abs32_iter;
- else if (rel32_iter->first < abs32_iter->first)
- ++rel32_iter;
- else {
- ++common;
- ++abs32_iter;
- ++rel32_iter;
- }
- }
- LOG(INFO) << "common " << common;
-#endif
-}
-
-void DisassemblerWin32X86::ParseRel32RelocsFromSection(const Section* section) {
- // TODO(sra): use characteristic.
- bool isCode = strcmp(section->name, ".text") == 0;
- if (!isCode)
- return;
-
- uint32 start_file_offset = section->file_offset_of_raw_data;
- uint32 end_file_offset = start_file_offset + section->size_of_raw_data;
- RVA relocs_start_rva = pe_info().base_relocation_table().address_;
-
- const uint8* start_pointer = pe_info().FileOffsetToPointer(start_file_offset);
- const uint8* end_pointer = pe_info().FileOffsetToPointer(end_file_offset);
-
- RVA start_rva = pe_info().FileOffsetToRVA(start_file_offset);
- RVA end_rva = start_rva + section->virtual_size;
-
- // Quick way to convert from Pointer to RVA within a single Section is to
- // subtract 'pointer_to_rva'.
- const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
-
- std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
-
- // Find the rel32 relocations.
- const uint8* p = start_pointer;
- while (p < end_pointer) {
- RVA current_rva = p - adjust_pointer_to_rva;
- if (current_rva == relocs_start_rva) {
- uint32 relocs_size = pe_info().base_relocation_table().size_;
- if (relocs_size) {
- p += relocs_size;
- continue;
- }
- }
-
- //while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
- // ++abs32_pos;
-
- // Heuristic discovery of rel32 locations in instruction stream: are the
- // next few bytes the start of an instruction containing a rel32
- // addressing mode?
- const uint8* rel32 = NULL;
-
- if (p + 5 < end_pointer) {
- if (*p == 0xE8 || *p == 0xE9) { // jmp rel32 and call rel32
- rel32 = p + 1;
- }
- }
- if (p + 6 < end_pointer) {
- if (*p == 0x0F && (*(p+1) & 0xF0) == 0x80) { // Jcc long form
- if (p[1] != 0x8A && p[1] != 0x8B) // JPE/JPO unlikely
- rel32 = p + 2;
- }
- }
- if (rel32) {
- RVA rel32_rva = rel32 - adjust_pointer_to_rva;
-
- // Is there an abs32 reloc overlapping the candidate?
- while (abs32_pos != abs32_locations_.end() && *abs32_pos < rel32_rva - 3)
- ++abs32_pos;
- // Now: (*abs32_pos > rel32_rva - 4) i.e. the lowest addressed 4-byte
- // region that could overlap rel32_rva.
- if (abs32_pos != abs32_locations_.end()) {
- if (*abs32_pos < rel32_rva + 4) {
- // Beginning of abs32 reloc is before end of rel32 reloc so they
- // overlap. Skip four bytes past the abs32 reloc.
- p += (*abs32_pos + 4) - current_rva;
- continue;
- }
- }
-
- RVA target_rva = rel32_rva + 4 + Read32LittleEndian(rel32);
- // To be valid, rel32 target must be within image, and within this
- // section.
- if (pe_info().IsValidRVA(target_rva) &&
- start_rva <= target_rva && target_rva < end_rva) {
- rel32_locations_.push_back(rel32_rva);
-#if COURGETTE_HISTOGRAM_TARGETS
- ++rel32_target_rvas_[target_rva];
-#endif
- p += 4;
- continue;
- }
- }
- p += 1;
- }
-}
-
-void DisassemblerWin32X86::ParseFile(AssemblyProgram* program) {
- // Walk all the bytes in the file, whether or not in a section.
- uint32 file_offset = 0;
- while (file_offset < pe_info().length()) {
- const Section* section = pe_info().FindNextSection(file_offset);
- if (section == NULL) {
- // No more sections. There should not be extra stuff following last
- // section.
- // ParseNonSectionFileRegion(file_offset, pe_info().length(), program);
- break;
- }
- if (file_offset < section->file_offset_of_raw_data) {
- uint32 section_start_offset = section->file_offset_of_raw_data;
- ParseNonSectionFileRegion(file_offset, section_start_offset, program);
- file_offset = section_start_offset;
- }
- uint32 end = file_offset + section->size_of_raw_data;
- ParseFileRegion(section, file_offset, end, program);
- file_offset = end;
- }
-
-#if COURGETTE_HISTOGRAM_TARGETS
- HistogramTargets("abs32 relocs", abs32_target_rvas_);
- HistogramTargets("rel32 relocs", rel32_target_rvas_);
-#endif
-}
-
-void DisassemblerWin32X86::ParseNonSectionFileRegion(
- uint32 start_file_offset,
- uint32 end_file_offset,
- AssemblyProgram* program) {
- if (incomplete_disassembly_)
- return;
-
- const uint8* start = pe_info().FileOffsetToPointer(start_file_offset);
- const uint8* end = pe_info().FileOffsetToPointer(end_file_offset);
-
- const uint8* p = start;
-
- while (p < end) {
- program->EmitByteInstruction(*p);
- ++p;
- }
-}
-
-void DisassemblerWin32X86::ParseFileRegion(
- const Section* section,
- uint32 start_file_offset, uint32 end_file_offset,
- AssemblyProgram* program) {
- RVA relocs_start_rva = pe_info().base_relocation_table().address_;
-
- const uint8* start_pointer = pe_info().FileOffsetToPointer(start_file_offset);
- const uint8* end_pointer = pe_info().FileOffsetToPointer(end_file_offset);
-
- RVA start_rva = pe_info().FileOffsetToRVA(start_file_offset);
- RVA end_rva = start_rva + section->virtual_size;
-
- // Quick way to convert from Pointer to RVA within a single Section is to
- // subtract 'pointer_to_rva'.
- const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
-
- std::vector<RVA>::iterator rel32_pos = rel32_locations_.begin();
- std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
-
- program->EmitOriginInstruction(start_rva);
-
- const uint8* p = start_pointer;
-
- while (p < end_pointer) {
- RVA current_rva = p - adjust_pointer_to_rva;
-
- // The base relocation table is usually in the .relocs section, but it could
- // actually be anywhere. Make sure we skip it because we will regenerate it
- // during assembly.
- if (current_rva == relocs_start_rva) {
- program->EmitMakeRelocsInstruction();
- uint32 relocs_size = pe_info().base_relocation_table().size_;
- if (relocs_size) {
- p += relocs_size;
- continue;
- }
- }
-
- while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
- ++abs32_pos;
-
- if (abs32_pos != abs32_locations_.end() && *abs32_pos == current_rva) {
- uint32 target_address = Read32LittleEndian(p);
- RVA target_rva = target_address - pe_info().image_base();
- // TODO(sra): target could be Label+offset. It is not clear how to guess
- // which it might be. We assume offset==0.
- program->EmitAbs32(program->FindOrMakeAbs32Label(target_rva));
- p += 4;
- continue;
- }
-
- while (rel32_pos != rel32_locations_.end() && *rel32_pos < current_rva)
- ++rel32_pos;
-
- if (rel32_pos != rel32_locations_.end() && *rel32_pos == current_rva) {
- RVA target_rva = current_rva + 4 + Read32LittleEndian(p);
- program->EmitRel32(program->FindOrMakeRel32Label(target_rva));
- p += 4;
- continue;
- }
-
- if (incomplete_disassembly_) {
- if ((abs32_pos == abs32_locations_.end() || end_rva <= *abs32_pos) &&
- (rel32_pos == rel32_locations_.end() || end_rva <= *rel32_pos) &&
- (end_rva <= relocs_start_rva || current_rva >= relocs_start_rva)) {
- // No more relocs in this section, don't bother encoding bytes.
- break;
- }
- }
-
- program->EmitByteInstruction(*p);
- p += 1;
- }
-}
-
-#if COURGETTE_HISTOGRAM_TARGETS
-// Histogram is printed to std::cout. It is purely for debugging the algorithm
-// and is only enabled manually in 'exploration' builds. I don't want to add
-// command-line configuration for this feature because this code has to be
-// small, which means compiled-out.
-void DisassemblerWin32X86::HistogramTargets(const char* kind,
- const std::map<RVA, int>& map) {
- int total = 0;
- std::map<int, std::vector<RVA> > h;
- for (std::map<RVA, int>::const_iterator p = map.begin();
- p != map.end();
- ++p) {
- h[p->second].push_back(p->first);
- total += p->second;
- }
-
- std::cout << total << " " << kind << " to "
- << map.size() << " unique targets" << std::endl;
-
- std::cout << "indegree: #targets-with-indegree (example)" << std::endl;
- const int kFirstN = 15;
- bool someSkipped = false;
- int index = 0;
- for (std::map<int, std::vector<RVA> >::reverse_iterator p = h.rbegin();
- p != h.rend();
- ++p) {
- ++index;
- if (index <= kFirstN || p->first <= 3) {
- if (someSkipped) {
- std::cout << "..." << std::endl;
- }
- size_t count = p->second.size();
- std::cout << std::dec << p->first << ": " << count;
- if (count <= 2) {
- for (size_t i = 0; i < count; ++i)
- std::cout << " " << pe_info().DescribeRVA(p->second[i]);
- }
- std::cout << std::endl;
- someSkipped = false;
- } else {
- someSkipped = true;
- }
- }
-}
-#endif // COURGETTE_HISTOGRAM_TARGETS
-
-Disassembler* Disassembler::MakeDisassemberWin32X86(PEInfo* pe_info) {
- return new DisassemblerWin32X86(pe_info);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-Status ParseWin32X86PE(const void* buffer, size_t length,
- AssemblyProgram** output) {
- *output = NULL;
-
- PEInfo* pe_info = new PEInfo();
- pe_info->Init(buffer, length);
-
- if (!pe_info->ParseHeader()) {
- delete pe_info;
- return C_INPUT_NOT_RECOGNIZED;
- }
-
- Disassembler* disassembler = Disassembler::MakeDisassemberWin32X86(pe_info);
- AssemblyProgram* program = new AssemblyProgram();
-
- if (!disassembler->Disassemble(program)) {
- delete program;
- disassembler->Destroy();
- delete pe_info;
- return C_DISASSEMBLY_FAILED;
- }
-
- disassembler->Destroy();
- delete pe_info;
- *output = program;
- return C_OK;
-}
-
-void DeleteAssemblyProgram(AssemblyProgram* program) {
- delete program;
-}
-
-} // namespace courgette
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "courgette/disassembler.h"
+
+#include <algorithm>
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+
+#include "courgette/assembly_program.h"
+#include "courgette/courgette.h"
+#include "courgette/encoded_program.h"
+#include "courgette/image_info.h"
+
+// COURGETTE_HISTOGRAM_TARGETS prints out a histogram of how frequently
+// different target addresses are referenced. Purely for debugging.
+#define COURGETTE_HISTOGRAM_TARGETS 0
+
+namespace courgette {
+
+class DisassemblerWin32X86 : public Disassembler {
+ public:
+ explicit DisassemblerWin32X86(PEInfo* pe_info)
+ : pe_info_(pe_info),
+ incomplete_disassembly_(false) {
+ }
+
+ virtual bool Disassemble(AssemblyProgram* target);
+
+ virtual void Destroy() { delete this; }
+
+ protected:
+ PEInfo& pe_info() { return *pe_info_; }
+
+ void ParseFile(AssemblyProgram* target);
+ bool ParseAbs32Relocs();
+ void ParseRel32RelocsFromSections();
+ void ParseRel32RelocsFromSection(const Section* section);
+
+ void ParseNonSectionFileRegion(uint32 start_file_offset,
+ uint32 end_file_offset,
+ AssemblyProgram* program);
+ void ParseFileRegion(const Section* section,
+ uint32 start_file_offset, uint32 end_file_offset,
+ AssemblyProgram* program);
+
+#if COURGETTE_HISTOGRAM_TARGETS
+ void HistogramTargets(const char* kind, const std::map<RVA, int>& map);
+#endif
+
+ PEInfo* pe_info_;
+ bool incomplete_disassembly_; // 'true' if can leave out 'uninteresting' bits
+
+ std::vector<RVA> abs32_locations_;
+ std::vector<RVA> rel32_locations_;
+
+#if COURGETTE_HISTOGRAM_TARGETS
+ std::map<RVA, int> abs32_target_rvas_;
+ std::map<RVA, int> rel32_target_rvas_;
+#endif
+};
+
+bool DisassemblerWin32X86::Disassemble(AssemblyProgram* target) {
+ if (!pe_info().ok())
+ return false;
+
+ target->set_image_base(pe_info().image_base());
+
+ if (!ParseAbs32Relocs())
+ return false;
+
+ ParseRel32RelocsFromSections();
+
+ ParseFile(target);
+
+ target->DefaultAssignIndexes();
+ return true;
+}
+
+static uint32 Read32LittleEndian(const void* address) {
+ return *reinterpret_cast<const uint32*>(address);
+}
+
+bool DisassemblerWin32X86::ParseAbs32Relocs() {
+ abs32_locations_.clear();
+ if (!pe_info().ParseRelocs(&abs32_locations_))
+ return false;
+
+ std::sort(abs32_locations_.begin(), abs32_locations_.end());
+
+#if COURGETTE_HISTOGRAM_TARGETS
+ for (size_t i = 0; i < abs32_locations_.size(); ++i) {
+ RVA rva = abs32_locations_[i];
+ // The 4 bytes at the relocation are a reference to some address.
+ uint32 target_address = Read32LittleEndian(pe_info().RVAToPointer(rva));
+ ++abs32_target_rvas_[target_address - pe_info().image_base()];
+ }
+#endif
+ return true;
+}
+
+void DisassemblerWin32X86::ParseRel32RelocsFromSections() {
+ uint32 file_offset = 0;
+ while (file_offset < pe_info().length()) {
+ const Section* section = pe_info().FindNextSection(file_offset);
+ if (section == NULL)
+ break;
+ if (file_offset < section->file_offset_of_raw_data)
+ file_offset = section->file_offset_of_raw_data;
+ ParseRel32RelocsFromSection(section);
+ file_offset += section->size_of_raw_data;
+ }
+ std::sort(rel32_locations_.begin(), rel32_locations_.end());
+
+#if COURGETTE_HISTOGRAM_TARGETS
+ LOG(INFO) << "abs32_locations_ " << abs32_locations_.size();
+ LOG(INFO) << "rel32_locations_ " << rel32_locations_.size();
+ LOG(INFO) << "abs32_target_rvas_ " << abs32_target_rvas_.size();
+ LOG(INFO) << "rel32_target_rvas_ " << rel32_target_rvas_.size();
+
+ int common = 0;
+ std::map<RVA, int>::iterator abs32_iter = abs32_target_rvas_.begin();
+ std::map<RVA, int>::iterator rel32_iter = rel32_target_rvas_.begin();
+ while (abs32_iter != abs32_target_rvas_.end() &&
+ rel32_iter != rel32_target_rvas_.end()) {
+ if (abs32_iter->first < rel32_iter->first)
+ ++abs32_iter;
+ else if (rel32_iter->first < abs32_iter->first)
+ ++rel32_iter;
+ else {
+ ++common;
+ ++abs32_iter;
+ ++rel32_iter;
+ }
+ }
+ LOG(INFO) << "common " << common;
+#endif
+}
+
+void DisassemblerWin32X86::ParseRel32RelocsFromSection(const Section* section) {
+ // TODO(sra): use characteristic.
+ bool isCode = strcmp(section->name, ".text") == 0;
+ if (!isCode)
+ return;
+
+ uint32 start_file_offset = section->file_offset_of_raw_data;
+ uint32 end_file_offset = start_file_offset + section->size_of_raw_data;
+ RVA relocs_start_rva = pe_info().base_relocation_table().address_;
+
+ const uint8* start_pointer = pe_info().FileOffsetToPointer(start_file_offset);
+ const uint8* end_pointer = pe_info().FileOffsetToPointer(end_file_offset);
+
+ RVA start_rva = pe_info().FileOffsetToRVA(start_file_offset);
+ RVA end_rva = start_rva + section->virtual_size;
+
+ // Quick way to convert from Pointer to RVA within a single Section is to
+ // subtract 'pointer_to_rva'.
+ const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
+
+ std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
+
+ // Find the rel32 relocations.
+ const uint8* p = start_pointer;
+ while (p < end_pointer) {
+ RVA current_rva = p - adjust_pointer_to_rva;
+ if (current_rva == relocs_start_rva) {
+ uint32 relocs_size = pe_info().base_relocation_table().size_;
+ if (relocs_size) {
+ p += relocs_size;
+ continue;
+ }
+ }
+
+ //while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
+ // ++abs32_pos;
+
+ // Heuristic discovery of rel32 locations in instruction stream: are the
+ // next few bytes the start of an instruction containing a rel32
+ // addressing mode?
+ const uint8* rel32 = NULL;
+
+ if (p + 5 < end_pointer) {
+ if (*p == 0xE8 || *p == 0xE9) { // jmp rel32 and call rel32
+ rel32 = p + 1;
+ }
+ }
+ if (p + 6 < end_pointer) {
+ if (*p == 0x0F && (*(p+1) & 0xF0) == 0x80) { // Jcc long form
+ if (p[1] != 0x8A && p[1] != 0x8B) // JPE/JPO unlikely
+ rel32 = p + 2;
+ }
+ }
+ if (rel32) {
+ RVA rel32_rva = rel32 - adjust_pointer_to_rva;
+
+ // Is there an abs32 reloc overlapping the candidate?
+ while (abs32_pos != abs32_locations_.end() && *abs32_pos < rel32_rva - 3)
+ ++abs32_pos;
+ // Now: (*abs32_pos > rel32_rva - 4) i.e. the lowest addressed 4-byte
+ // region that could overlap rel32_rva.
+ if (abs32_pos != abs32_locations_.end()) {
+ if (*abs32_pos < rel32_rva + 4) {
+ // Beginning of abs32 reloc is before end of rel32 reloc so they
+ // overlap. Skip four bytes past the abs32 reloc.
+ p += (*abs32_pos + 4) - current_rva;
+ continue;
+ }
+ }
+
+ RVA target_rva = rel32_rva + 4 + Read32LittleEndian(rel32);
+ // To be valid, rel32 target must be within image, and within this
+ // section.
+ if (pe_info().IsValidRVA(target_rva) &&
+ start_rva <= target_rva && target_rva < end_rva) {
+ rel32_locations_.push_back(rel32_rva);
+#if COURGETTE_HISTOGRAM_TARGETS
+ ++rel32_target_rvas_[target_rva];
+#endif
+ p += 4;
+ continue;
+ }
+ }
+ p += 1;
+ }
+}
+
+void DisassemblerWin32X86::ParseFile(AssemblyProgram* program) {
+ // Walk all the bytes in the file, whether or not in a section.
+ uint32 file_offset = 0;
+ while (file_offset < pe_info().length()) {
+ const Section* section = pe_info().FindNextSection(file_offset);
+ if (section == NULL) {
+ // No more sections. There should not be extra stuff following last
+ // section.
+ // ParseNonSectionFileRegion(file_offset, pe_info().length(), program);
+ break;
+ }
+ if (file_offset < section->file_offset_of_raw_data) {
+ uint32 section_start_offset = section->file_offset_of_raw_data;
+ ParseNonSectionFileRegion(file_offset, section_start_offset, program);
+ file_offset = section_start_offset;
+ }
+ uint32 end = file_offset + section->size_of_raw_data;
+ ParseFileRegion(section, file_offset, end, program);
+ file_offset = end;
+ }
+
+#if COURGETTE_HISTOGRAM_TARGETS
+ HistogramTargets("abs32 relocs", abs32_target_rvas_);
+ HistogramTargets("rel32 relocs", rel32_target_rvas_);
+#endif
+}
+
+void DisassemblerWin32X86::ParseNonSectionFileRegion(
+ uint32 start_file_offset,
+ uint32 end_file_offset,
+ AssemblyProgram* program) {
+ if (incomplete_disassembly_)
+ return;
+
+ const uint8* start = pe_info().FileOffsetToPointer(start_file_offset);
+ const uint8* end = pe_info().FileOffsetToPointer(end_file_offset);
+
+ const uint8* p = start;
+
+ while (p < end) {
+ program->EmitByteInstruction(*p);
+ ++p;
+ }
+}
+
+void DisassemblerWin32X86::ParseFileRegion(
+ const Section* section,
+ uint32 start_file_offset, uint32 end_file_offset,
+ AssemblyProgram* program) {
+ RVA relocs_start_rva = pe_info().base_relocation_table().address_;
+
+ const uint8* start_pointer = pe_info().FileOffsetToPointer(start_file_offset);
+ const uint8* end_pointer = pe_info().FileOffsetToPointer(end_file_offset);
+
+ RVA start_rva = pe_info().FileOffsetToRVA(start_file_offset);
+ RVA end_rva = start_rva + section->virtual_size;
+
+ // Quick way to convert from Pointer to RVA within a single Section is to
+ // subtract 'pointer_to_rva'.
+ const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
+
+ std::vector<RVA>::iterator rel32_pos = rel32_locations_.begin();
+ std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
+
+ program->EmitOriginInstruction(start_rva);
+
+ const uint8* p = start_pointer;
+
+ while (p < end_pointer) {
+ RVA current_rva = p - adjust_pointer_to_rva;
+
+ // The base relocation table is usually in the .relocs section, but it could
+ // actually be anywhere. Make sure we skip it because we will regenerate it
+ // during assembly.
+ if (current_rva == relocs_start_rva) {
+ program->EmitMakeRelocsInstruction();
+ uint32 relocs_size = pe_info().base_relocation_table().size_;
+ if (relocs_size) {
+ p += relocs_size;
+ continue;
+ }
+ }
+
+ while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
+ ++abs32_pos;
+
+ if (abs32_pos != abs32_locations_.end() && *abs32_pos == current_rva) {
+ uint32 target_address = Read32LittleEndian(p);
+ RVA target_rva = target_address - pe_info().image_base();
+ // TODO(sra): target could be Label+offset. It is not clear how to guess
+ // which it might be. We assume offset==0.
+ program->EmitAbs32(program->FindOrMakeAbs32Label(target_rva));
+ p += 4;
+ continue;
+ }
+
+ while (rel32_pos != rel32_locations_.end() && *rel32_pos < current_rva)
+ ++rel32_pos;
+
+ if (rel32_pos != rel32_locations_.end() && *rel32_pos == current_rva) {
+ RVA target_rva = current_rva + 4 + Read32LittleEndian(p);
+ program->EmitRel32(program->FindOrMakeRel32Label(target_rva));
+ p += 4;
+ continue;
+ }
+
+ if (incomplete_disassembly_) {
+ if ((abs32_pos == abs32_locations_.end() || end_rva <= *abs32_pos) &&
+ (rel32_pos == rel32_locations_.end() || end_rva <= *rel32_pos) &&
+ (end_rva <= relocs_start_rva || current_rva >= relocs_start_rva)) {
+ // No more relocs in this section, don't bother encoding bytes.
+ break;
+ }
+ }
+
+ program->EmitByteInstruction(*p);
+ p += 1;
+ }
+}
+
+#if COURGETTE_HISTOGRAM_TARGETS
+// Histogram is printed to std::cout. It is purely for debugging the algorithm
+// and is only enabled manually in 'exploration' builds. I don't want to add
+// command-line configuration for this feature because this code has to be
+// small, which means compiled-out.
+void DisassemblerWin32X86::HistogramTargets(const char* kind,
+ const std::map<RVA, int>& map) {
+ int total = 0;
+ std::map<int, std::vector<RVA> > h;
+ for (std::map<RVA, int>::const_iterator p = map.begin();
+ p != map.end();
+ ++p) {
+ h[p->second].push_back(p->first);
+ total += p->second;
+ }
+
+ std::cout << total << " " << kind << " to "
+ << map.size() << " unique targets" << std::endl;
+
+ std::cout << "indegree: #targets-with-indegree (example)" << std::endl;
+ const int kFirstN = 15;
+ bool someSkipped = false;
+ int index = 0;
+ for (std::map<int, std::vector<RVA> >::reverse_iterator p = h.rbegin();
+ p != h.rend();
+ ++p) {
+ ++index;
+ if (index <= kFirstN || p->first <= 3) {
+ if (someSkipped) {
+ std::cout << "..." << std::endl;
+ }
+ size_t count = p->second.size();
+ std::cout << std::dec << p->first << ": " << count;
+ if (count <= 2) {
+ for (size_t i = 0; i < count; ++i)
+ std::cout << " " << pe_info().DescribeRVA(p->second[i]);
+ }
+ std::cout << std::endl;
+ someSkipped = false;
+ } else {
+ someSkipped = true;
+ }
+ }
+}
+#endif // COURGETTE_HISTOGRAM_TARGETS
+
+Disassembler* Disassembler::MakeDisassemberWin32X86(PEInfo* pe_info) {
+ return new DisassemblerWin32X86(pe_info);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+Status ParseWin32X86PE(const void* buffer, size_t length,
+ AssemblyProgram** output) {
+ *output = NULL;
+
+ PEInfo* pe_info = new PEInfo();
+ pe_info->Init(buffer, length);
+
+ if (!pe_info->ParseHeader()) {
+ delete pe_info;
+ return C_INPUT_NOT_RECOGNIZED;
+ }
+
+ Disassembler* disassembler = Disassembler::MakeDisassemberWin32X86(pe_info);
+ AssemblyProgram* program = new AssemblyProgram();
+
+ if (!disassembler->Disassemble(program)) {
+ delete program;
+ disassembler->Destroy();
+ delete pe_info;
+ return C_DISASSEMBLY_FAILED;
+ }
+
+ disassembler->Destroy();
+ delete pe_info;
+ *output = program;
+ return C_OK;
+}
+
+void DeleteAssemblyProgram(AssemblyProgram* program) {
+ delete program;
+}
+
+} // namespace courgette
diff --git a/third_party/courgette/disassembler.h b/courgette/disassembler.h
index 595412e..fa7c908 100644
--- a/third_party/courgette/disassembler.h
+++ b/courgette/disassembler.h
@@ -1,39 +1,38 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef COURGETTE_DISASSEMBLER_H_
-#define COURGETTE_DISASSEMBLER_H_
-
-#include "base/basictypes.h"
-
-namespace courgette {
-
-class AssemblyProgram;
-class PEInfo;
-
-class Disassembler {
- public:
- // Factory methods for making disassemblers for various kinds of executables.
- // We have only one so far.
-
- static Disassembler* MakeDisassemberWin32X86(PEInfo* pe_info);
-
- // Disassembles the item passed to the factory method into the output
- // parameter 'program'.
- virtual bool Disassemble(AssemblyProgram* program) = 0;
-
- // Deletes 'this' disassembler.
- virtual void Destroy() = 0;
-
- protected:
- Disassembler() {}
- virtual ~Disassembler() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Disassembler);
-};
-
-} // namespace courgette
-#endif // COURGETTE_DISASSEMBLER_H_
-
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COURGETTE_DISASSEMBLER_H_
+#define COURGETTE_DISASSEMBLER_H_
+
+#include "base/basictypes.h"
+
+namespace courgette {
+
+class AssemblyProgram;
+class PEInfo;
+
+class Disassembler {
+ public:
+ // Factory methods for making disassemblers for various kinds of executables.
+ // We have only one so far.
+
+ static Disassembler* MakeDisassemberWin32X86(PEInfo* pe_info);
+
+ // Disassembles the item passed to the factory method into the output
+ // parameter 'program'.
+ virtual bool Disassemble(AssemblyProgram* program) = 0;
+
+ // Deletes 'this' disassembler.
+ virtual void Destroy() = 0;
+
+ protected:
+ Disassembler() {}
+ virtual ~Disassembler() {}
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(Disassembler);
+};
+
+} // namespace courgette
+#endif // COURGETTE_DISASSEMBLER_H_
diff --git a/third_party/courgette/encode_decode_unittest.cc b/courgette/encode_decode_unittest.cc
index 25a3913..436479d8 100644
--- a/third_party/courgette/encode_decode_unittest.cc
+++ b/courgette/encode_decode_unittest.cc
@@ -8,8 +8,8 @@
#include "base/file_util.h"
#include "base/string_util.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -20,7 +20,6 @@ class EncodeDecodeTest : public testing::Test {
private:
void SetUp() {
PathService::Get(base::DIR_SOURCE_ROOT, &testdata_dir_);
- // file_util::AppendToPath(&testdata_dir_, L"third_party");
file_util::AppendToPath(&testdata_dir_, L"courgette");
file_util::AppendToPath(&testdata_dir_, L"testdata");
}
diff --git a/third_party/courgette/encoded_program.cc b/courgette/encoded_program.cc
index 0e9f164..f606f96 100644
--- a/third_party/courgette/encoded_program.cc
+++ b/courgette/encoded_program.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/courgette/encoded_program.h"
+#include "courgette/encoded_program.h"
#include <algorithm>
#include <map>
@@ -12,8 +12,8 @@
#include "base/logging.h"
#include "base/sys_info.h"
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
namespace courgette {
diff --git a/third_party/courgette/encoded_program.h b/courgette/encoded_program.h
index 7331042..df1119c 100644
--- a/third_party/courgette/encoded_program.h
+++ b/courgette/encoded_program.h
@@ -8,7 +8,7 @@
#include <vector>
#include "base/basictypes.h"
-#include "third_party/courgette/image_info.h"
+#include "courgette/image_info.h"
namespace courgette {
@@ -81,4 +81,3 @@ class EncodedProgram {
} // namespace courgette
#endif // COURGETTE_ENCODED_FORMAT_H_
-
diff --git a/third_party/courgette/encoded_program_fuzz_unittest.cc b/courgette/encoded_program_fuzz_unittest.cc
index 9cd5020..adc09d9 100644
--- a/third_party/courgette/encoded_program_fuzz_unittest.cc
+++ b/courgette/encoded_program_fuzz_unittest.cc
@@ -1,236 +1,235 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Fuzz testing for EncodedProgram serialized format and assembly.
-//
-// We would like some assurance that if an EncodedProgram is malformed we will
-// not crash. The EncodedProgram could be malformed either due to malicious
-// attack to due to an error in patch generation.
-//
-// We try a lot of arbitrary modifications to the serialized form and make sure
-// that the outcome is not a crash.
-
-#include <string>
-
-#include "base/path_service.h"
-#include "base/file_util.h"
-#include "base/string_util.h"
-#include "base/test_suite.h"
-
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
-
-#include "testing/gtest/include/gtest/gtest.h"
-
-class DecodeFuzzTest : public testing::Test {
- public:
- void FuzzExe(const char *) const;
-
- private:
- virtual void SetUp() {
- PathService::Get(base::DIR_SOURCE_ROOT, &testdata_dir_);
- // testdata_dir_ = testdata_dir_.Append(L"third_party");
- testdata_dir_ = testdata_dir_.Append(L"courgette");
- testdata_dir_ = testdata_dir_.Append(L"testdata");
- }
-
- virtual void TearDown() { }
-
- void FuzzByte(const std::string& buffer, const std::string& output,
- size_t index) const;
- void FuzzBits(const std::string& buffer, const std::string& output,
- size_t index, int bits_to_flip) const;
-
- // Returns true if could assemble, false if rejected.
- bool TryAssemble(const std::string& buffer, std::string* output) const;
-
- // Returns contents of |file_name| as uninterprested bytes stored in a string.
- std::string FileContents(const char* file_name) const;
-
- // Full path name of testdata directory
- FilePath testdata_dir_;
-};
-
-// Reads a test file into a string.
-std::string DecodeFuzzTest::FileContents(const char* file_name) const {
- FilePath file_path = testdata_dir_.AppendASCII(file_name);
- std::string file_contents;
- if (!file_util::ReadFileToString(file_path, &file_contents)) {
- EXPECT_TRUE(!"Could not read test data");
- }
- return file_contents;
-}
-
-// Loads an executable and does fuzz testing in the serialized format.
-void DecodeFuzzTest::FuzzExe(const char* file_name) const {
- std::string file1 = FileContents(file_name);
-
- const void* original_buffer = file1.c_str();
- size_t original_length = file1.size();
-
- courgette::AssemblyProgram* program = NULL;
- const courgette::Status parse_status =
- courgette::ParseWin32X86PE(original_buffer, original_length, &program);
- EXPECT_EQ(courgette::C_OK, parse_status);
-
- courgette::EncodedProgram* encoded = NULL;
-
- const courgette::Status encode_status = Encode(program, &encoded);
- EXPECT_EQ(courgette::C_OK, encode_status);
-
- DeleteAssemblyProgram(program);
-
- courgette::SinkStreamSet sinks;
- const courgette::Status write_status = WriteEncodedProgram(encoded, &sinks);
- EXPECT_EQ(courgette::C_OK, write_status);
-
- DeleteEncodedProgram(encoded);
-
- courgette::SinkStream sink;
- bool can_collect = sinks.CopyTo(&sink);
- EXPECT_TRUE(can_collect);
-
- size_t length = sink.Length();
-
- std::string base_buffer(reinterpret_cast<const char*>(sink.Buffer()), length);
- std::string base_output;
- bool ok = TryAssemble(base_buffer, &base_output);
- EXPECT_EQ(true, ok);
-
- // Now we have a good serialized EncodedProgram in |base_buffer|. Time to
- // fuzz.
-
- // More intense fuzzing on the first part because it contains more control
- // information like substeam lengths.
- size_t position = 0;
- for ( ; position < 100 && position < length; position += 1) {
- FuzzByte(base_buffer, base_output, position);
- }
- // We would love to fuzz every position, but it takes too long.
- for ( ; position < length; position += 900) {
- FuzzByte(base_buffer, base_output, position);
- }
-}
-
-// FuzzByte tries to break the EncodedProgram deserializer and assembler. It
-// takes a good serialization of and EncodedProgram, flips some bits, and checks
-// that the behaviour is reasonable. It has testing checks for unreasonable
-// behaviours.
-void DecodeFuzzTest::FuzzByte(const std::string& base_buffer,
- const std::string& base_output,
- size_t index) const {
- printf("Fuzzing position %d\n", static_cast<int>(index));
-
- // The following 10 values are a compromize between run time and coverage of
- // the 255 'wrong' values at this byte position.
-
- // 0xFF flips all the bits.
- FuzzBits(base_buffer, base_output, index, 0xFF);
- // 0x7F flips the most bits without changing Varint32 framing.
- FuzzBits(base_buffer, base_output, index, 0x7F);
- // These all flip one bit.
- FuzzBits(base_buffer, base_output, index, 0x80);
- FuzzBits(base_buffer, base_output, index, 0x40);
- FuzzBits(base_buffer, base_output, index, 0x20);
- FuzzBits(base_buffer, base_output, index, 0x10);
- FuzzBits(base_buffer, base_output, index, 0x08);
- FuzzBits(base_buffer, base_output, index, 0x04);
- FuzzBits(base_buffer, base_output, index, 0x02);
- FuzzBits(base_buffer, base_output, index, 0x01);
-}
-
-// FuzzBits tries to break the EncodedProgram deserializer and assembler. It
-// takes a good serialization of and EncodedProgram, flips some bits, and checks
-// that the behaviour is reasonable.
-//
-// There are EXPECT calls to check for unreasonable behaviour. These are
-// somewhat arbitrary in that the parameters cannot easily be derived from first
-// principles. They may need updating as the serialized format evolves.
-void DecodeFuzzTest::FuzzBits(const std::string& base_buffer,
- const std::string& base_output,
- size_t index, int bits_to_flip) const {
- std::string modified_buffer = base_buffer;
- std::string modified_output;
- modified_buffer[index] ^= bits_to_flip;
-
- bool ok = TryAssemble(modified_buffer, &modified_output);
-
- if (ok) {
- // We normally expect TryAssemble to fail. But sometimes it succeeds.
- // What could have happened? We changed one byte in the serialized form:
- //
- // * If we changed one of the copied bytes, we would see a single byte
- // change in the output.
- // * If we changed an address table element, all the references to that
- // address would be different.
- // * If we changed a copy count, we would run out of data in some stream,
- // or leave data remaining, so should not be here.
- // * If we changed an origin address, it could affect all relocations based
- // off that address. If no relocations were based off the address then
- // there will be no changes.
- // * If we changed an origin address, it could cause some abs32 relocs to
- // shift from one page to the next, changing the number and layout of
- // blocks in the base relocation table.
-
- // Generated length could vary slightly due to base relocation table layout.
- // In the worst case the number of base relocation blocks doubles, approx
- // 12/4096 or 0.3% size of file.
- size_t base_length = base_output.length();
- size_t modified_length = modified_output.length();
- ptrdiff_t diff = base_length - modified_length;
- if (diff < -200 || diff > 200) {
- EXPECT_EQ(base_length, modified_length);
- }
-
- size_t changed_byte_count = 0;
- for (size_t i = 0; i < base_length && i < modified_length; ++i) {
- changed_byte_count += (base_output[i] != modified_output[i]);
- }
-
- if (index > 60) { // Beyond the origin addresses ...
- EXPECT_NE(0, changed_byte_count); // ... we expect some difference.
- }
- // Currently all changes are smaller than this number:
- EXPECT_GE(45000u, changed_byte_count);
- }
-}
-
-bool DecodeFuzzTest::TryAssemble(const std::string& buffer,
- std::string* output) const {
- courgette::EncodedProgram *encoded = NULL;
- bool result = false;
-
- courgette::SourceStreamSet sources;
- bool can_get_source_streams = sources.Init(buffer.c_str(), buffer.length());
- if (can_get_source_streams) {
- const courgette::Status read_status =
- ReadEncodedProgram(&sources, &encoded);
- if (read_status == courgette::C_OK) {
- courgette::SinkStream assembled;
- const courgette::Status assemble_status = Assemble(encoded, &assembled);
-
- if (assemble_status == courgette::C_OK) {
- const void* assembled_buffer = assembled.Buffer();
- size_t assembled_length = assembled.Length();
-
- output->clear();
- output->assign(reinterpret_cast<const char*>(assembled_buffer),
- assembled_length);
- result = true;
- }
- }
- }
-
- DeleteEncodedProgram(encoded);
-
- return result;
-}
-
-TEST_F(DecodeFuzzTest, All) {
- FuzzExe("setup1.exe");
-}
-
-int main(int argc, char** argv) {
- return TestSuite(argc, argv).Run();
-}
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Fuzz testing for EncodedProgram serialized format and assembly.
+//
+// We would like some assurance that if an EncodedProgram is malformed we will
+// not crash. The EncodedProgram could be malformed either due to malicious
+// attack to due to an error in patch generation.
+//
+// We try a lot of arbitrary modifications to the serialized form and make sure
+// that the outcome is not a crash.
+
+#include <string>
+
+#include "base/path_service.h"
+#include "base/file_util.h"
+#include "base/string_util.h"
+#include "base/test_suite.h"
+
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+class DecodeFuzzTest : public testing::Test {
+ public:
+ void FuzzExe(const char *) const;
+
+ private:
+ virtual void SetUp() {
+ PathService::Get(base::DIR_SOURCE_ROOT, &testdata_dir_);
+ testdata_dir_ = testdata_dir_.Append(L"courgette");
+ testdata_dir_ = testdata_dir_.Append(L"testdata");
+ }
+
+ virtual void TearDown() { }
+
+ void FuzzByte(const std::string& buffer, const std::string& output,
+ size_t index) const;
+ void FuzzBits(const std::string& buffer, const std::string& output,
+ size_t index, int bits_to_flip) const;
+
+ // Returns true if could assemble, false if rejected.
+ bool TryAssemble(const std::string& buffer, std::string* output) const;
+
+ // Returns contents of |file_name| as uninterprested bytes stored in a string.
+ std::string FileContents(const char* file_name) const;
+
+ // Full path name of testdata directory
+ FilePath testdata_dir_;
+};
+
+// Reads a test file into a string.
+std::string DecodeFuzzTest::FileContents(const char* file_name) const {
+ FilePath file_path = testdata_dir_.AppendASCII(file_name);
+ std::string file_contents;
+ if (!file_util::ReadFileToString(file_path, &file_contents)) {
+ EXPECT_TRUE(!"Could not read test data");
+ }
+ return file_contents;
+}
+
+// Loads an executable and does fuzz testing in the serialized format.
+void DecodeFuzzTest::FuzzExe(const char* file_name) const {
+ std::string file1 = FileContents(file_name);
+
+ const void* original_buffer = file1.c_str();
+ size_t original_length = file1.size();
+
+ courgette::AssemblyProgram* program = NULL;
+ const courgette::Status parse_status =
+ courgette::ParseWin32X86PE(original_buffer, original_length, &program);
+ EXPECT_EQ(courgette::C_OK, parse_status);
+
+ courgette::EncodedProgram* encoded = NULL;
+
+ const courgette::Status encode_status = Encode(program, &encoded);
+ EXPECT_EQ(courgette::C_OK, encode_status);
+
+ DeleteAssemblyProgram(program);
+
+ courgette::SinkStreamSet sinks;
+ const courgette::Status write_status = WriteEncodedProgram(encoded, &sinks);
+ EXPECT_EQ(courgette::C_OK, write_status);
+
+ DeleteEncodedProgram(encoded);
+
+ courgette::SinkStream sink;
+ bool can_collect = sinks.CopyTo(&sink);
+ EXPECT_TRUE(can_collect);
+
+ size_t length = sink.Length();
+
+ std::string base_buffer(reinterpret_cast<const char*>(sink.Buffer()), length);
+ std::string base_output;
+ bool ok = TryAssemble(base_buffer, &base_output);
+ EXPECT_EQ(true, ok);
+
+ // Now we have a good serialized EncodedProgram in |base_buffer|. Time to
+ // fuzz.
+
+ // More intense fuzzing on the first part because it contains more control
+ // information like substeam lengths.
+ size_t position = 0;
+ for ( ; position < 100 && position < length; position += 1) {
+ FuzzByte(base_buffer, base_output, position);
+ }
+ // We would love to fuzz every position, but it takes too long.
+ for ( ; position < length; position += 900) {
+ FuzzByte(base_buffer, base_output, position);
+ }
+}
+
+// FuzzByte tries to break the EncodedProgram deserializer and assembler. It
+// takes a good serialization of and EncodedProgram, flips some bits, and checks
+// that the behaviour is reasonable. It has testing checks for unreasonable
+// behaviours.
+void DecodeFuzzTest::FuzzByte(const std::string& base_buffer,
+ const std::string& base_output,
+ size_t index) const {
+ printf("Fuzzing position %d\n", static_cast<int>(index));
+
+ // The following 10 values are a compromize between run time and coverage of
+ // the 255 'wrong' values at this byte position.
+
+ // 0xFF flips all the bits.
+ FuzzBits(base_buffer, base_output, index, 0xFF);
+ // 0x7F flips the most bits without changing Varint32 framing.
+ FuzzBits(base_buffer, base_output, index, 0x7F);
+ // These all flip one bit.
+ FuzzBits(base_buffer, base_output, index, 0x80);
+ FuzzBits(base_buffer, base_output, index, 0x40);
+ FuzzBits(base_buffer, base_output, index, 0x20);
+ FuzzBits(base_buffer, base_output, index, 0x10);
+ FuzzBits(base_buffer, base_output, index, 0x08);
+ FuzzBits(base_buffer, base_output, index, 0x04);
+ FuzzBits(base_buffer, base_output, index, 0x02);
+ FuzzBits(base_buffer, base_output, index, 0x01);
+}
+
+// FuzzBits tries to break the EncodedProgram deserializer and assembler. It
+// takes a good serialization of and EncodedProgram, flips some bits, and checks
+// that the behaviour is reasonable.
+//
+// There are EXPECT calls to check for unreasonable behaviour. These are
+// somewhat arbitrary in that the parameters cannot easily be derived from first
+// principles. They may need updating as the serialized format evolves.
+void DecodeFuzzTest::FuzzBits(const std::string& base_buffer,
+ const std::string& base_output,
+ size_t index, int bits_to_flip) const {
+ std::string modified_buffer = base_buffer;
+ std::string modified_output;
+ modified_buffer[index] ^= bits_to_flip;
+
+ bool ok = TryAssemble(modified_buffer, &modified_output);
+
+ if (ok) {
+ // We normally expect TryAssemble to fail. But sometimes it succeeds.
+ // What could have happened? We changed one byte in the serialized form:
+ //
+ // * If we changed one of the copied bytes, we would see a single byte
+ // change in the output.
+ // * If we changed an address table element, all the references to that
+ // address would be different.
+ // * If we changed a copy count, we would run out of data in some stream,
+ // or leave data remaining, so should not be here.
+ // * If we changed an origin address, it could affect all relocations based
+ // off that address. If no relocations were based off the address then
+ // there will be no changes.
+ // * If we changed an origin address, it could cause some abs32 relocs to
+ // shift from one page to the next, changing the number and layout of
+ // blocks in the base relocation table.
+
+ // Generated length could vary slightly due to base relocation table layout.
+ // In the worst case the number of base relocation blocks doubles, approx
+ // 12/4096 or 0.3% size of file.
+ size_t base_length = base_output.length();
+ size_t modified_length = modified_output.length();
+ ptrdiff_t diff = base_length - modified_length;
+ if (diff < -200 || diff > 200) {
+ EXPECT_EQ(base_length, modified_length);
+ }
+
+ size_t changed_byte_count = 0;
+ for (size_t i = 0; i < base_length && i < modified_length; ++i) {
+ changed_byte_count += (base_output[i] != modified_output[i]);
+ }
+
+ if (index > 60) { // Beyond the origin addresses ...
+ EXPECT_NE(0, changed_byte_count); // ... we expect some difference.
+ }
+ // Currently all changes are smaller than this number:
+ EXPECT_GE(45000u, changed_byte_count);
+ }
+}
+
+bool DecodeFuzzTest::TryAssemble(const std::string& buffer,
+ std::string* output) const {
+ courgette::EncodedProgram *encoded = NULL;
+ bool result = false;
+
+ courgette::SourceStreamSet sources;
+ bool can_get_source_streams = sources.Init(buffer.c_str(), buffer.length());
+ if (can_get_source_streams) {
+ const courgette::Status read_status =
+ ReadEncodedProgram(&sources, &encoded);
+ if (read_status == courgette::C_OK) {
+ courgette::SinkStream assembled;
+ const courgette::Status assemble_status = Assemble(encoded, &assembled);
+
+ if (assemble_status == courgette::C_OK) {
+ const void* assembled_buffer = assembled.Buffer();
+ size_t assembled_length = assembled.Length();
+
+ output->clear();
+ output->assign(reinterpret_cast<const char*>(assembled_buffer),
+ assembled_length);
+ result = true;
+ }
+ }
+ }
+
+ DeleteEncodedProgram(encoded);
+
+ return result;
+}
+
+TEST_F(DecodeFuzzTest, All) {
+ FuzzExe("setup1.exe");
+}
+
+int main(int argc, char** argv) {
+ return TestSuite(argc, argv).Run();
+}
diff --git a/third_party/courgette/encoded_program_unittest.cc b/courgette/encoded_program_unittest.cc
index 9b0025e..aedb838 100644
--- a/third_party/courgette/encoded_program_unittest.cc
+++ b/courgette/encoded_program_unittest.cc
@@ -2,9 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/courgette/encoded_program.h"
+#include "courgette/encoded_program.h"
-#include "third_party/courgette/streams.h"
+#include "courgette/streams.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(EncodedProgramTest, Test) {
@@ -62,4 +62,3 @@ TEST(EncodedProgramTest, Test) {
EXPECT_EQ(0, memcmp(assembled_buffer, golden, 8));
}
-
diff --git a/third_party/courgette/ensemble.cc b/courgette/ensemble.cc
index 4c8f013..15bfb3e 100644
--- a/third_party/courgette/ensemble.cc
+++ b/courgette/ensemble.cc
@@ -1,102 +1,102 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// *** File comments
-
-#include "third_party/courgette/ensemble.h"
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "base/string_util.h"
-
-#include "third_party/courgette/image_info.h"
-#include "third_party/courgette/region.h"
-#include "third_party/courgette/streams.h"
-#include "third_party/courgette/simple_delta.h"
-
-namespace courgette {
-
-Element::Element(Kind kind, Ensemble* ensemble, const Region& region)
- : kind_(kind), ensemble_(ensemble), region_(region) {
-}
-
-std::string Element::Name() const {
- return ensemble_->name() + "("
- + IntToString(kind()) + ","
- + Uint64ToString(offset_in_ensemble()) + ","
- + Uint64ToString(region().length()) + ")";
-}
-
-// A subclass of Element that has a PEInfo.
-class ElementWinPE : public Element {
- public:
- ElementWinPE(Kind kind, Ensemble* ensemble, const Region& region,
- PEInfo* info)
- : Element(kind, ensemble, region),
- pe_info_(info) {
- }
-
- virtual PEInfo* GetPEInfo() const { return pe_info_; }
-
- protected:
- ~ElementWinPE() { delete pe_info_; }
-
- private:
- PEInfo* pe_info_; // Owned by |this|.
-};
-
-// Scans the Ensemble's region, sniffing out Elements. We assume that the
-// elements do not overlap.
-Status Ensemble::FindEmbeddedElements() {
- size_t length = region_.length();
- const uint8* start = region_.start();
-
- size_t position = 0;
- while (position < length) {
- // Quick test; Windows executables begin with 'MZ'.
- if (start[position] == 'M' &&
- position + 1 < length && start[position + 1] == 'Z') {
- courgette::PEInfo *info = new courgette::PEInfo();
- info->Init(start + position, length - position);
- if (info->ParseHeader()) {
- Region region(start + position, info->length());
-
- if (info->has_text_section()) {
- Element* element = new ElementWinPE(Element::WIN32_X86_WITH_CODE,
- this, region, info);
- owned_elements_.push_back(element);
- elements_.push_back(element);
- position += region.length();
- continue;
- }
-
- // If we had a clever transformation for resource-only executables we
- // should identify the suitable elements here:
- if (!info->has_text_section() && false) {
- Element* element = new ElementWinPE(Element::WIN32_NOCODE,
- this, region, info);
- owned_elements_.push_back(element);
- elements_.push_back(element);
- position += region.length();
- continue;
- }
- }
- delete info;
- }
-
- // This is where to add new formats, e.g. Linux executables, Dalvik
- // executables etc.
-
- // No Element found at current position.
- ++position;
- }
- return C_OK;
-}
-
-Ensemble::~Ensemble() {
- for (size_t i = 0; i < owned_elements_.size(); ++i)
- delete owned_elements_[i];
-}
-
-} // namespace
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// *** File comments
+
+#include "courgette/ensemble.h"
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "base/string_util.h"
+
+#include "courgette/image_info.h"
+#include "courgette/region.h"
+#include "courgette/streams.h"
+#include "courgette/simple_delta.h"
+
+namespace courgette {
+
+Element::Element(Kind kind, Ensemble* ensemble, const Region& region)
+ : kind_(kind), ensemble_(ensemble), region_(region) {
+}
+
+std::string Element::Name() const {
+ return ensemble_->name() + "("
+ + IntToString(kind()) + ","
+ + Uint64ToString(offset_in_ensemble()) + ","
+ + Uint64ToString(region().length()) + ")";
+}
+
+// A subclass of Element that has a PEInfo.
+class ElementWinPE : public Element {
+ public:
+ ElementWinPE(Kind kind, Ensemble* ensemble, const Region& region,
+ PEInfo* info)
+ : Element(kind, ensemble, region),
+ pe_info_(info) {
+ }
+
+ virtual PEInfo* GetPEInfo() const { return pe_info_; }
+
+ protected:
+ ~ElementWinPE() { delete pe_info_; }
+
+ private:
+ PEInfo* pe_info_; // Owned by |this|.
+};
+
+// Scans the Ensemble's region, sniffing out Elements. We assume that the
+// elements do not overlap.
+Status Ensemble::FindEmbeddedElements() {
+ size_t length = region_.length();
+ const uint8* start = region_.start();
+
+ size_t position = 0;
+ while (position < length) {
+ // Quick test; Windows executables begin with 'MZ'.
+ if (start[position] == 'M' &&
+ position + 1 < length && start[position + 1] == 'Z') {
+ courgette::PEInfo *info = new courgette::PEInfo();
+ info->Init(start + position, length - position);
+ if (info->ParseHeader()) {
+ Region region(start + position, info->length());
+
+ if (info->has_text_section()) {
+ Element* element = new ElementWinPE(Element::WIN32_X86_WITH_CODE,
+ this, region, info);
+ owned_elements_.push_back(element);
+ elements_.push_back(element);
+ position += region.length();
+ continue;
+ }
+
+ // If we had a clever transformation for resource-only executables we
+ // should identify the suitable elements here:
+ if (!info->has_text_section() && false) {
+ Element* element = new ElementWinPE(Element::WIN32_NOCODE,
+ this, region, info);
+ owned_elements_.push_back(element);
+ elements_.push_back(element);
+ position += region.length();
+ continue;
+ }
+ }
+ delete info;
+ }
+
+ // This is where to add new formats, e.g. Linux executables, Dalvik
+ // executables etc.
+
+ // No Element found at current position.
+ ++position;
+ }
+ return C_OK;
+}
+
+Ensemble::~Ensemble() {
+ for (size_t i = 0; i < owned_elements_.size(); ++i)
+ delete owned_elements_[i];
+}
+
+} // namespace
diff --git a/third_party/courgette/ensemble.h b/courgette/ensemble.h
index 7602c3f..6a58cb0 100644
--- a/third_party/courgette/ensemble.h
+++ b/courgette/ensemble.h
@@ -1,257 +1,257 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// The main idea in Courgette is to do patching *under a tranformation*. The
-// input is transformed into a new representation, patching occurs in the new
-// repesentation, and then the tranform is reversed to get the patched data.
-//
-// The idea is applied to pieces (or 'Elements') of the whole (or 'Ensemble').
-// Each of the elements has to go through the same set of steps in lock-step,
-// but there may be many different kinds of elements, which have different
-// transformation.
-//
-// This file declares all the main types involved in creating and applying a
-// patch with this structure.
-
-#ifndef COURGETTE_ENSEMBLE_H_
-#define COURGETTE_ENSEMBLE_H_
-
-#include <vector>
-#include <string>
-
-#include "base/basictypes.h"
-
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/region.h"
-#include "third_party/courgette/streams.h"
-
-namespace courgette {
-
-// Forward declarations:
-class Ensemble;
-class PEInfo;
-
-// An Element is a region of an Ensemble with an identifyable kind.
-//
-class Element {
- public:
- enum Kind { WIN32_X86_WITH_CODE, WIN32_NOCODE };
-
- virtual ~Element() {}
-
- Kind kind() const { return kind_; }
- const Region& region() const { return region_; }
-
- // The name is used only for debugging and logging.
- virtual std::string Name() const;
-
- // Returns the byte position of this Element relative to the start of
- // containing Ensemble.
- size_t offset_in_ensemble() const;
-
- // Some subclasses of Element might have a PEInfo.
- virtual PEInfo* GetPEInfo() const { return NULL; }
-
- protected:
- Element(Kind kind, Ensemble* ensemble, const Region& region);
-
- private:
- Kind kind_;
- Ensemble* ensemble_;
- Region region_;
-
- DISALLOW_COPY_AND_ASSIGN(Element);
-};
-
-
-class Ensemble {
- public:
- Ensemble(const Region& region, const char* name)
- : region_(region), name_(name) {}
- ~Ensemble();
-
- const Region& region() const { return region_; }
- const std::string& name() const { return name_; }
-
- // Scans the region to find Elements within the region().
- Status FindEmbeddedElements();
-
- // Returns the elements found by 'FindEmbeddedElements'.
- const std::vector<Element*>& elements() const { return elements_; }
-
-
- private:
- Region region_; // The memory, owned by caller, containing the
- // Ensemble's data.
- std::string name_; // A debugging/logging name for the Ensemble.
-
- std::vector<Element*> elements_; // Embedded elements discovered.
- std::vector<Element*> owned_elements_; // For deallocation.
-
- DISALLOW_COPY_AND_ASSIGN(Ensemble);
-};
-
-inline size_t Element::offset_in_ensemble() const {
- return region().start() - ensemble_->region().start();
-}
-
-// The 'CourgettePatchFile' is class is a 'namespace' for the constants that
-// appear in a Courgette patch file.
-struct CourgettePatchFile {
- //
- // The Courgette patch format interleaves the data for N embedded Elements.
- //
- // Format of a patch file:
- // header:
- // magic
- // version
- // source-checksum
- // target-checksum
- // multiple-streams:
- // stream 0:
- // number-of-transformed-elements (N) - varint32
- // transformation-1-method-id
- // transformation-2-method-id
- // ...
- // transformation-1-initial-parameters
- // transformation-2-initial-parameters
- // ...
- // stream 1:
- // correction:
- // transformation-1-parameters
- // transformation-2-parameters
- // ...
- // stream 2:
- // correction:
- // transformed-element-1
- // transformed-element-2
- // ...
- // stream 3:
- // correction:
- // base-file
- // element-1
- // element-2
- // ...
-
- static const uint32 kMagic = 'C' | ('o' << 8) | ('u' << 16);
-
- static const uint32 kVersion = 20090320;
-
- // Transformation method IDs.
- enum TransformationMethodId {
- T_COURGETTE_WIN32_X86 = 1, // Windows 32 bit 'Portable Executable' x86.
- };
-};
-
-// For any transform you would implement both a TransformationPatcher and a
-// TransformationPatchGenerator.
-//
-// TransformationPatcher is the interface which abstracts out the actual
-// transformation used on an Element. The patching itself happens outside the
-// actions of a TransformationPatcher. There are four steps.
-//
-// The first step is an Init step. The parameters to the Init step identify the
-// element, for example, range of locations within the original ensemble that
-// correspond to the element.
-//
-// PredictTransformParameters, explained below.
-//
-// The two final steps are 'Transform' - to transform the element into a new
-// representation, and to 'Reform' - to transform from the new representation
-// back to the original form.
-//
-// The Transform step takes some parameters. This allows the transform to be
-// customized to the particular element, or to receive some assistance in the
-// analysis required to perform the transform. The transform parameters might
-// be extensive but mostly predicable, so preceeding Transform is a
-// PredictTransformParameters step.
-//
-class TransformationPatcher {
- public:
- virtual ~TransformationPatcher() {}
-
- // First step: provides parameters for the patching. This would at a minimum
- // identify the element within the ensemble being patched.
- virtual Status Init(SourceStream* parameter_stream) = 0;
-
- // Second step: predicts transform parameters.
- virtual Status PredictTransformParameters(
- SinkStreamSet* predicted_parameters) = 0;
-
- // Third step: transforms element from original representation into alternate
- // representation.
- virtual Status Transform(SourceStreamSet* corrected_parameters,
- SinkStreamSet* transformed_element) = 0;
-
- // Final step: transforms element back from alternate representation into
- // original representation.
- virtual Status Reform(SourceStreamSet* transformed_element,
- SinkStream* reformed_element) = 0;
-};
-
-// TransformationPatchGenerator is the interface which abstracts out the actual
-// transformation used (and adjustment used) when differentially compressing one
-// Element from the |new_ensemble| against a corresponding element in the
-// |old_ensemble|.
-//
-// This is not a pure interface. There is a small amount of inheritance
-// implementation for the fields and actions common to all
-// TransformationPatchGenerators.
-//
-// When TransformationPatchGenerator is subclassed, there will be a
-// corresponding subclass of TransformationPatcher.
-//
-class TransformationPatchGenerator {
- public:
- TransformationPatchGenerator(Element* old_element,
- Element* new_element,
- TransformationPatcher* patcher);
-
- virtual ~TransformationPatchGenerator();
-
- // Returns the TransformationMethodId that identies this transformation.
- virtual CourgettePatchFile::TransformationMethodId Kind() = 0;
-
- // Writes the parameters that will be passed to TransformationPatcher::Init.
- virtual Status WriteInitialParameters(SinkStream* parameter_stream) = 0;
-
- // Predicts the transform parameters for the |old_element|. This must match
- // exactly the output that will be produced by the PredictTransformParameters
- // method of the corresponding subclass of TransformationPatcher. This method
- // is not pure. The default implementation delegates to the patcher to
- // guarantee matching output.
- virtual Status PredictTransformParameters(SinkStreamSet* prediction);
-
- // Writes the desired parameters for the transform of the old element from the
- // file representation to the alternate representation.
- virtual Status CorrectedTransformParameters(SinkStreamSet* parameters) = 0;
-
- // Writes both |old_element| and |new_element| in the new representation.
- // |old_corrected_parameters| will match the |corrected_parameters| passed to
- // the Transform method of the corresponding sublcass of
- // TransformationPatcher.
- //
- // The output written to |old_transformed_element| must match exactly the
- // output written by the Transform method of the corresponding subclass of
- // TransformationPatcher.
- virtual Status Transform(SourceStreamSet* old_corrected_parameters,
- SinkStreamSet* old_transformed_element,
- SinkStreamSet* new_transformed_element) = 0;
-
- // Transforms the new transformed_element back from the alternate
- // representation into the original file format. This must match exactly the
- // output that will be produced by the corresponding subclass of
- // TransformationPatcher::Reform. This method is not pure. The default
- // implementation delegates to the patcher.
- virtual Status Reform(SourceStreamSet* transformed_element,
- SinkStream* reformed_element);
-
- protected:
- Element* old_element_;
- Element* new_element_;
- TransformationPatcher* patcher_;
-};
-
-} // namespace
-#endif // COURGETTE_ENSEMBLE_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// The main idea in Courgette is to do patching *under a tranformation*. The
+// input is transformed into a new representation, patching occurs in the new
+// repesentation, and then the tranform is reversed to get the patched data.
+//
+// The idea is applied to pieces (or 'Elements') of the whole (or 'Ensemble').
+// Each of the elements has to go through the same set of steps in lock-step,
+// but there may be many different kinds of elements, which have different
+// transformation.
+//
+// This file declares all the main types involved in creating and applying a
+// patch with this structure.
+
+#ifndef COURGETTE_ENSEMBLE_H_
+#define COURGETTE_ENSEMBLE_H_
+
+#include <vector>
+#include <string>
+
+#include "base/basictypes.h"
+
+#include "courgette/courgette.h"
+#include "courgette/region.h"
+#include "courgette/streams.h"
+
+namespace courgette {
+
+// Forward declarations:
+class Ensemble;
+class PEInfo;
+
+// An Element is a region of an Ensemble with an identifyable kind.
+//
+class Element {
+ public:
+ enum Kind { WIN32_X86_WITH_CODE, WIN32_NOCODE };
+
+ virtual ~Element() {}
+
+ Kind kind() const { return kind_; }
+ const Region& region() const { return region_; }
+
+ // The name is used only for debugging and logging.
+ virtual std::string Name() const;
+
+ // Returns the byte position of this Element relative to the start of
+ // containing Ensemble.
+ size_t offset_in_ensemble() const;
+
+ // Some subclasses of Element might have a PEInfo.
+ virtual PEInfo* GetPEInfo() const { return NULL; }
+
+ protected:
+ Element(Kind kind, Ensemble* ensemble, const Region& region);
+
+ private:
+ Kind kind_;
+ Ensemble* ensemble_;
+ Region region_;
+
+ DISALLOW_COPY_AND_ASSIGN(Element);
+};
+
+
+class Ensemble {
+ public:
+ Ensemble(const Region& region, const char* name)
+ : region_(region), name_(name) {}
+ ~Ensemble();
+
+ const Region& region() const { return region_; }
+ const std::string& name() const { return name_; }
+
+ // Scans the region to find Elements within the region().
+ Status FindEmbeddedElements();
+
+ // Returns the elements found by 'FindEmbeddedElements'.
+ const std::vector<Element*>& elements() const { return elements_; }
+
+
+ private:
+ Region region_; // The memory, owned by caller, containing the
+ // Ensemble's data.
+ std::string name_; // A debugging/logging name for the Ensemble.
+
+ std::vector<Element*> elements_; // Embedded elements discovered.
+ std::vector<Element*> owned_elements_; // For deallocation.
+
+ DISALLOW_COPY_AND_ASSIGN(Ensemble);
+};
+
+inline size_t Element::offset_in_ensemble() const {
+ return region().start() - ensemble_->region().start();
+}
+
+// The 'CourgettePatchFile' is class is a 'namespace' for the constants that
+// appear in a Courgette patch file.
+struct CourgettePatchFile {
+ //
+ // The Courgette patch format interleaves the data for N embedded Elements.
+ //
+ // Format of a patch file:
+ // header:
+ // magic
+ // version
+ // source-checksum
+ // target-checksum
+ // multiple-streams:
+ // stream 0:
+ // number-of-transformed-elements (N) - varint32
+ // transformation-1-method-id
+ // transformation-2-method-id
+ // ...
+ // transformation-1-initial-parameters
+ // transformation-2-initial-parameters
+ // ...
+ // stream 1:
+ // correction:
+ // transformation-1-parameters
+ // transformation-2-parameters
+ // ...
+ // stream 2:
+ // correction:
+ // transformed-element-1
+ // transformed-element-2
+ // ...
+ // stream 3:
+ // correction:
+ // base-file
+ // element-1
+ // element-2
+ // ...
+
+ static const uint32 kMagic = 'C' | ('o' << 8) | ('u' << 16);
+
+ static const uint32 kVersion = 20090320;
+
+ // Transformation method IDs.
+ enum TransformationMethodId {
+ T_COURGETTE_WIN32_X86 = 1, // Windows 32 bit 'Portable Executable' x86.
+ };
+};
+
+// For any transform you would implement both a TransformationPatcher and a
+// TransformationPatchGenerator.
+//
+// TransformationPatcher is the interface which abstracts out the actual
+// transformation used on an Element. The patching itself happens outside the
+// actions of a TransformationPatcher. There are four steps.
+//
+// The first step is an Init step. The parameters to the Init step identify the
+// element, for example, range of locations within the original ensemble that
+// correspond to the element.
+//
+// PredictTransformParameters, explained below.
+//
+// The two final steps are 'Transform' - to transform the element into a new
+// representation, and to 'Reform' - to transform from the new representation
+// back to the original form.
+//
+// The Transform step takes some parameters. This allows the transform to be
+// customized to the particular element, or to receive some assistance in the
+// analysis required to perform the transform. The transform parameters might
+// be extensive but mostly predicable, so preceeding Transform is a
+// PredictTransformParameters step.
+//
+class TransformationPatcher {
+ public:
+ virtual ~TransformationPatcher() {}
+
+ // First step: provides parameters for the patching. This would at a minimum
+ // identify the element within the ensemble being patched.
+ virtual Status Init(SourceStream* parameter_stream) = 0;
+
+ // Second step: predicts transform parameters.
+ virtual Status PredictTransformParameters(
+ SinkStreamSet* predicted_parameters) = 0;
+
+ // Third step: transforms element from original representation into alternate
+ // representation.
+ virtual Status Transform(SourceStreamSet* corrected_parameters,
+ SinkStreamSet* transformed_element) = 0;
+
+ // Final step: transforms element back from alternate representation into
+ // original representation.
+ virtual Status Reform(SourceStreamSet* transformed_element,
+ SinkStream* reformed_element) = 0;
+};
+
+// TransformationPatchGenerator is the interface which abstracts out the actual
+// transformation used (and adjustment used) when differentially compressing one
+// Element from the |new_ensemble| against a corresponding element in the
+// |old_ensemble|.
+//
+// This is not a pure interface. There is a small amount of inheritance
+// implementation for the fields and actions common to all
+// TransformationPatchGenerators.
+//
+// When TransformationPatchGenerator is subclassed, there will be a
+// corresponding subclass of TransformationPatcher.
+//
+class TransformationPatchGenerator {
+ public:
+ TransformationPatchGenerator(Element* old_element,
+ Element* new_element,
+ TransformationPatcher* patcher);
+
+ virtual ~TransformationPatchGenerator();
+
+ // Returns the TransformationMethodId that identies this transformation.
+ virtual CourgettePatchFile::TransformationMethodId Kind() = 0;
+
+ // Writes the parameters that will be passed to TransformationPatcher::Init.
+ virtual Status WriteInitialParameters(SinkStream* parameter_stream) = 0;
+
+ // Predicts the transform parameters for the |old_element|. This must match
+ // exactly the output that will be produced by the PredictTransformParameters
+ // method of the corresponding subclass of TransformationPatcher. This method
+ // is not pure. The default implementation delegates to the patcher to
+ // guarantee matching output.
+ virtual Status PredictTransformParameters(SinkStreamSet* prediction);
+
+ // Writes the desired parameters for the transform of the old element from the
+ // file representation to the alternate representation.
+ virtual Status CorrectedTransformParameters(SinkStreamSet* parameters) = 0;
+
+ // Writes both |old_element| and |new_element| in the new representation.
+ // |old_corrected_parameters| will match the |corrected_parameters| passed to
+ // the Transform method of the corresponding sublcass of
+ // TransformationPatcher.
+ //
+ // The output written to |old_transformed_element| must match exactly the
+ // output written by the Transform method of the corresponding subclass of
+ // TransformationPatcher.
+ virtual Status Transform(SourceStreamSet* old_corrected_parameters,
+ SinkStreamSet* old_transformed_element,
+ SinkStreamSet* new_transformed_element) = 0;
+
+ // Transforms the new transformed_element back from the alternate
+ // representation into the original file format. This must match exactly the
+ // output that will be produced by the corresponding subclass of
+ // TransformationPatcher::Reform. This method is not pure. The default
+ // implementation delegates to the patcher.
+ virtual Status Reform(SourceStreamSet* transformed_element,
+ SinkStream* reformed_element);
+
+ protected:
+ Element* old_element_;
+ Element* new_element_;
+ TransformationPatcher* patcher_;
+};
+
+} // namespace
+#endif // COURGETTE_ENSEMBLE_H_
diff --git a/third_party/courgette/ensemble_apply.cc b/courgette/ensemble_apply.cc
index 7954ca4..5a9edfd4 100644
--- a/third_party/courgette/ensemble_apply.cc
+++ b/courgette/ensemble_apply.cc
@@ -1,412 +1,412 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains the code to apply a Courgette patch.
-
-#include "third_party/courgette/ensemble.h"
-
-#include "base/basictypes.h"
-#include "base/file_util.h"
-#include "base/logging.h"
-
-#include "third_party/courgette/crc.h"
-#include "third_party/courgette/image_info.h"
-#include "third_party/courgette/region.h"
-#include "third_party/courgette/streams.h"
-#include "third_party/courgette/simple_delta.h"
-#include "third_party/courgette/win32_x86_patcher.h"
-
-namespace courgette {
-
-// EnsemblePatchApplication is all the logic and data required to apply the
-// multi-stage patch.
-class EnsemblePatchApplication {
- public:
- EnsemblePatchApplication();
- ~EnsemblePatchApplication();
-
- Status ReadHeader(SourceStream* header_stream);
-
- Status InitBase(const Region& region);
-
- Status ValidateBase();
-
- Status ReadInitialParameters(SourceStream* initial_parameters);
-
- Status PredictTransformParameters(SinkStreamSet* predicted_parameters);
-
- Status SubpatchTransformParameters(SinkStreamSet* prediction,
- SourceStream* correction,
- SourceStreamSet* corrected_parameters);
-
- Status TransformUp(SourceStreamSet* parameters,
- SinkStreamSet* transformed_elements);
-
- Status SubpatchTransformedElements(SinkStreamSet* elements,
- SourceStream* correction,
- SourceStreamSet* corrected_elements);
-
- Status TransformDown(SourceStreamSet* transformed_elements,
- SinkStream* basic_elements);
-
- Status SubpatchFinalOutput(SourceStream* original,
- SourceStream* correction,
- SinkStream* corrected_ensemble);
-
- private:
- Status SubpatchStreamSets(SinkStreamSet* predicted_items,
- SourceStream* correction,
- SourceStreamSet* corrected_items,
- SinkStream* corrected_items_storage);
-
- Region base_region_; // Location of in-memory copy of 'old' version.
-
- uint32 source_checksum_;
- uint32 target_checksum_;
-
- std::vector<TransformationPatcher*> patchers_;
-
- SinkStream corrected_parameters_storage_;
- SinkStream corrected_elements_storage_;
-
- DISALLOW_COPY_AND_ASSIGN(EnsemblePatchApplication);
-};
-
-EnsemblePatchApplication::EnsemblePatchApplication()
- : source_checksum_(0), target_checksum_(0) {
-}
-
-EnsemblePatchApplication::~EnsemblePatchApplication() {
- for (size_t i = 0; i < patchers_.size(); ++i) {
- delete patchers_[i];
- }
-}
-
-Status EnsemblePatchApplication::ReadHeader(SourceStream* header_stream) {
- uint32 magic;
- if (!header_stream->ReadVarint32(&magic))
- return C_BAD_ENSEMBLE_MAGIC;
-
- if (magic != CourgettePatchFile::kMagic)
- return C_BAD_ENSEMBLE_MAGIC;
-
- uint32 version;
- if (!header_stream->ReadVarint32(&version))
- return C_BAD_ENSEMBLE_VERSION;
-
- if (version != CourgettePatchFile::kVersion)
- return C_BAD_ENSEMBLE_VERSION;
-
- if (!header_stream->ReadVarint32(&source_checksum_))
- return C_BAD_ENSEMBLE_HEADER;
-
- if (!header_stream->ReadVarint32(&target_checksum_))
- return C_BAD_ENSEMBLE_HEADER;
-
- return C_OK;
-}
-
-Status EnsemblePatchApplication::InitBase(const Region& region) {
- base_region_.assign(region);
- return C_OK;
-}
-
-Status EnsemblePatchApplication::ValidateBase() {
- uint32 checksum = CalculateCrc(base_region_.start(), base_region_.length());
- if (source_checksum_ != checksum)
- return C_BAD_ENSEMBLE_CRC;
-
- return C_OK;
-}
-
-Status EnsemblePatchApplication::ReadInitialParameters(
- SourceStream* transformation_parameters) {
- uint32 number_of_transformations = 0;
- if (!transformation_parameters->ReadVarint32(&number_of_transformations))
- return C_BAD_ENSEMBLE_HEADER;
-
- for (size_t i = 0; i < number_of_transformations; ++i) {
- uint32 kind;
- if (!transformation_parameters->ReadVarint32(&kind))
- return C_BAD_ENSEMBLE_HEADER;
-
- if (kind == CourgettePatchFile::T_COURGETTE_WIN32_X86) {
- TransformationPatcher* patcher =
- new CourgetteWin32X86Patcher(base_region_);
- patchers_.push_back(patcher);
- } else {
- return C_BAD_ENSEMBLE_HEADER;
- }
- }
-
- for (size_t i = 0; i < patchers_.size(); ++i) {
- Status status = patchers_[i]->Init(transformation_parameters);
- if (status != C_OK)
- return status;
- }
-
- // All transformation_parameters should have been consumed by the above loop.
- if (!transformation_parameters->Empty())
- return C_BAD_ENSEMBLE_HEADER;
-
- return C_OK;
-}
-
-Status EnsemblePatchApplication::PredictTransformParameters(
- SinkStreamSet* all_predicted_parameters) {
- for (size_t i = 0; i < patchers_.size(); ++i) {
- SinkStreamSet single_predicted_parameters;
- Status status =
- patchers_[i]->PredictTransformParameters(&single_predicted_parameters);
- if (status != C_OK)
- return status;
- if (!all_predicted_parameters->WriteSet(&single_predicted_parameters))
- return C_STREAM_ERROR;
- }
- return C_OK;
-}
-
-Status EnsemblePatchApplication::SubpatchTransformParameters(
- SinkStreamSet* predicted_parameters,
- SourceStream* correction,
- SourceStreamSet* corrected_parameters) {
- return SubpatchStreamSets(predicted_parameters,
- correction,
- corrected_parameters,
- &corrected_parameters_storage_);
-}
-
-Status EnsemblePatchApplication::TransformUp(
- SourceStreamSet* parameters,
- SinkStreamSet* transformed_elements) {
- for (size_t i = 0; i < patchers_.size(); ++i) {
- SourceStreamSet single_parameters;
- if (!parameters->ReadSet(&single_parameters))
- return C_STREAM_ERROR;
- SinkStreamSet single_transformed_element;
- Status status = patchers_[i]->Transform(&single_parameters,
- &single_transformed_element);
- if (status != C_OK)
- return status;
- if (!single_parameters.Empty())
- return C_STREAM_NOT_CONSUMED;
- if (!transformed_elements->WriteSet(&single_transformed_element))
- return C_STREAM_ERROR;
- }
-
- if (!parameters->Empty())
- return C_STREAM_NOT_CONSUMED;
- return C_OK;
-}
-
-Status EnsemblePatchApplication::SubpatchTransformedElements(
- SinkStreamSet* predicted_elements,
- SourceStream* correction,
- SourceStreamSet* corrected_elements) {
- return SubpatchStreamSets(predicted_elements,
- correction,
- corrected_elements,
- &corrected_elements_storage_);
-}
-
-Status EnsemblePatchApplication::TransformDown(
- SourceStreamSet* transformed_elements,
- SinkStream* basic_elements) {
- // Construct blob of original input followed by reformed elements.
-
- // The original input:
- basic_elements->Write(base_region_.start(), base_region_.length());
-
- for (size_t i = 0; i < patchers_.size(); ++i) {
- SourceStreamSet single_corrected_element;
- if (!transformed_elements->ReadSet(&single_corrected_element))
- return C_STREAM_ERROR;
- Status status = patchers_[i]->Reform(&single_corrected_element,
- basic_elements);
- if (status != C_OK)
- return status;
- if (!single_corrected_element.Empty())
- return C_STREAM_NOT_CONSUMED;
- }
-
- if (!transformed_elements->Empty())
- return C_STREAM_NOT_CONSUMED;
-
- return C_OK;
-}
-
-Status EnsemblePatchApplication::SubpatchFinalOutput(
- SourceStream* original,
- SourceStream* correction,
- SinkStream* corrected_ensemble) {
- Status delta_status = ApplySimpleDelta(original, correction,
- corrected_ensemble);
- if (delta_status != C_OK)
- return delta_status;
-
- if (CalculateCrc(corrected_ensemble->Buffer(),
- corrected_ensemble->Length()) != target_checksum_)
- return C_BAD_ENSEMBLE_CRC;
-
- return C_OK;
-}
-
-Status EnsemblePatchApplication::SubpatchStreamSets(
- SinkStreamSet* predicted_items,
- SourceStream* correction,
- SourceStreamSet* corrected_items,
- SinkStream* corrected_items_storage) {
- SinkStream linearized_predicted_items;
- if (!predicted_items->CopyTo(&linearized_predicted_items))
- return C_STREAM_ERROR;
-
- SourceStream prediction;
- prediction.Init(linearized_predicted_items);
-
- Status status = ApplySimpleDelta(&prediction,
- correction,
- corrected_items_storage);
- if (status != C_OK)
- return status;
-
- if (!corrected_items->Init(corrected_items_storage->Buffer(),
- corrected_items_storage->Length()))
- return C_STREAM_ERROR;
-
- return C_OK;
-}
-
-Status ApplyEnsemblePatch(SourceStream* base,
- SourceStream* patch,
- SinkStream* output) {
- Status status;
- EnsemblePatchApplication patch_process;
-
- status = patch_process.ReadHeader(patch);
- if (status != C_OK)
- return status;
-
- status = patch_process.InitBase(Region(base->Buffer(), base->Remaining()));
- if (status != C_OK)
- return status;
-
- status = patch_process.ValidateBase();
- if (status != C_OK)
- return status;
-
- // The rest of the patch stream is a StreamSet.
- SourceStreamSet patch_streams;
- patch_streams.Init(patch);
-
- SourceStream* transformation_descriptions = patch_streams.stream(0);
- SourceStream* parameter_correction = patch_streams.stream(1);
- SourceStream* transformed_elements_correction = patch_streams.stream(2);
- SourceStream* ensemble_correction = patch_streams.stream(3);
-
- status = patch_process.ReadInitialParameters(transformation_descriptions);
- if (status != C_OK)
- return status;
-
- SinkStreamSet predicted_parameters;
- status = patch_process.PredictTransformParameters(&predicted_parameters);
- if (status != C_OK)
- return status;
-
- SourceStreamSet corrected_parameters;
- status = patch_process.SubpatchTransformParameters(&predicted_parameters,
- parameter_correction,
- &corrected_parameters);
- if (status != C_OK)
- return status;
-
- SinkStreamSet transformed_elements;
- status = patch_process.TransformUp(&corrected_parameters,
- &transformed_elements);
- if (status != C_OK)
- return status;
-
- SourceStreamSet corrected_transformed_elements;
- status = patch_process.SubpatchTransformedElements(
- &transformed_elements,
- transformed_elements_correction,
- &corrected_transformed_elements);
- if (status != C_OK)
- return status;
-
- SinkStream original_ensemble_and_corrected_base_elements;
- status = patch_process.TransformDown(
- &corrected_transformed_elements,
- &original_ensemble_and_corrected_base_elements);
- if (status != C_OK)
- return status;
-
- SourceStream final_patch_prediction;
- final_patch_prediction.Init(original_ensemble_and_corrected_base_elements);
- status = patch_process.SubpatchFinalOutput(&final_patch_prediction,
- ensemble_correction, output);
- if (status != C_OK)
- return status;
-
- return C_OK;
-}
-
-Status ApplyEnsemblePatch(const wchar_t* old_file_name,
- const wchar_t* patch_file_name,
- const wchar_t* new_file_name) {
- Status status;
-
- // First read enough of the patch file to validate the header is well-formed.
- // A few varint32 numbers should fit in 100.
- FilePath patch_file_path(patch_file_name);
- const int BIG_ENOUGH_FOR_HEADER = 100;
- char buffer[BIG_ENOUGH_FOR_HEADER];
- int read_count =
- file_util::ReadFile(patch_file_path, buffer, sizeof(buffer));
- if (read_count < 0)
- return C_READ_OPEN_ERROR;
-
- // 'Dry-run' the first step of the patch process to validate format of header.
- SourceStream patch_header_stream;
- patch_header_stream.Init(buffer, read_count);
- EnsemblePatchApplication patch_process;
- status = patch_process.ReadHeader(&patch_header_stream);
- if (status != C_OK)
- return status;
-
- // Header smells good so read the whole patch file for real.
- std::string patch_file_buffer;
- if (!file_util::ReadFileToString(patch_file_path, &patch_file_buffer))
- return C_READ_ERROR;
-
- // Read the old_file.
- FilePath old_file_path(old_file_name);
- std::string old_file_buffer;
- if (!file_util::ReadFileToString(old_file_path, &old_file_buffer))
- return C_READ_ERROR;
-
- // Apply patch on streams.
- SourceStream old_source_stream;
- SourceStream patch_source_stream;
- old_source_stream.Init(old_file_buffer);
- patch_source_stream.Init(patch_file_buffer);
- SinkStream new_sink_stream;
- status = ApplyEnsemblePatch(&old_source_stream, &patch_source_stream,
- &new_sink_stream);
-
- // Write the patched data to |new_file_name|.
- FilePath new_file_path(new_file_name);
- int written =
- file_util::WriteFile(
- new_file_path,
- reinterpret_cast<const char*>(new_sink_stream.Buffer()),
- new_sink_stream.Length());
- if (written == -1)
- return C_WRITE_OPEN_ERROR;
- if (written != new_sink_stream.Length())
- return C_WRITE_ERROR;
-
- return C_OK;
-}
-
-} // namespace
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This file contains the code to apply a Courgette patch.
+
+#include "courgette/ensemble.h"
+
+#include "base/basictypes.h"
+#include "base/file_util.h"
+#include "base/logging.h"
+
+#include "courgette/crc.h"
+#include "courgette/image_info.h"
+#include "courgette/region.h"
+#include "courgette/streams.h"
+#include "courgette/simple_delta.h"
+#include "courgette/win32_x86_patcher.h"
+
+namespace courgette {
+
+// EnsemblePatchApplication is all the logic and data required to apply the
+// multi-stage patch.
+class EnsemblePatchApplication {
+ public:
+ EnsemblePatchApplication();
+ ~EnsemblePatchApplication();
+
+ Status ReadHeader(SourceStream* header_stream);
+
+ Status InitBase(const Region& region);
+
+ Status ValidateBase();
+
+ Status ReadInitialParameters(SourceStream* initial_parameters);
+
+ Status PredictTransformParameters(SinkStreamSet* predicted_parameters);
+
+ Status SubpatchTransformParameters(SinkStreamSet* prediction,
+ SourceStream* correction,
+ SourceStreamSet* corrected_parameters);
+
+ Status TransformUp(SourceStreamSet* parameters,
+ SinkStreamSet* transformed_elements);
+
+ Status SubpatchTransformedElements(SinkStreamSet* elements,
+ SourceStream* correction,
+ SourceStreamSet* corrected_elements);
+
+ Status TransformDown(SourceStreamSet* transformed_elements,
+ SinkStream* basic_elements);
+
+ Status SubpatchFinalOutput(SourceStream* original,
+ SourceStream* correction,
+ SinkStream* corrected_ensemble);
+
+ private:
+ Status SubpatchStreamSets(SinkStreamSet* predicted_items,
+ SourceStream* correction,
+ SourceStreamSet* corrected_items,
+ SinkStream* corrected_items_storage);
+
+ Region base_region_; // Location of in-memory copy of 'old' version.
+
+ uint32 source_checksum_;
+ uint32 target_checksum_;
+
+ std::vector<TransformationPatcher*> patchers_;
+
+ SinkStream corrected_parameters_storage_;
+ SinkStream corrected_elements_storage_;
+
+ DISALLOW_COPY_AND_ASSIGN(EnsemblePatchApplication);
+};
+
+EnsemblePatchApplication::EnsemblePatchApplication()
+ : source_checksum_(0), target_checksum_(0) {
+}
+
+EnsemblePatchApplication::~EnsemblePatchApplication() {
+ for (size_t i = 0; i < patchers_.size(); ++i) {
+ delete patchers_[i];
+ }
+}
+
+Status EnsemblePatchApplication::ReadHeader(SourceStream* header_stream) {
+ uint32 magic;
+ if (!header_stream->ReadVarint32(&magic))
+ return C_BAD_ENSEMBLE_MAGIC;
+
+ if (magic != CourgettePatchFile::kMagic)
+ return C_BAD_ENSEMBLE_MAGIC;
+
+ uint32 version;
+ if (!header_stream->ReadVarint32(&version))
+ return C_BAD_ENSEMBLE_VERSION;
+
+ if (version != CourgettePatchFile::kVersion)
+ return C_BAD_ENSEMBLE_VERSION;
+
+ if (!header_stream->ReadVarint32(&source_checksum_))
+ return C_BAD_ENSEMBLE_HEADER;
+
+ if (!header_stream->ReadVarint32(&target_checksum_))
+ return C_BAD_ENSEMBLE_HEADER;
+
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::InitBase(const Region& region) {
+ base_region_.assign(region);
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::ValidateBase() {
+ uint32 checksum = CalculateCrc(base_region_.start(), base_region_.length());
+ if (source_checksum_ != checksum)
+ return C_BAD_ENSEMBLE_CRC;
+
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::ReadInitialParameters(
+ SourceStream* transformation_parameters) {
+ uint32 number_of_transformations = 0;
+ if (!transformation_parameters->ReadVarint32(&number_of_transformations))
+ return C_BAD_ENSEMBLE_HEADER;
+
+ for (size_t i = 0; i < number_of_transformations; ++i) {
+ uint32 kind;
+ if (!transformation_parameters->ReadVarint32(&kind))
+ return C_BAD_ENSEMBLE_HEADER;
+
+ if (kind == CourgettePatchFile::T_COURGETTE_WIN32_X86) {
+ TransformationPatcher* patcher =
+ new CourgetteWin32X86Patcher(base_region_);
+ patchers_.push_back(patcher);
+ } else {
+ return C_BAD_ENSEMBLE_HEADER;
+ }
+ }
+
+ for (size_t i = 0; i < patchers_.size(); ++i) {
+ Status status = patchers_[i]->Init(transformation_parameters);
+ if (status != C_OK)
+ return status;
+ }
+
+ // All transformation_parameters should have been consumed by the above loop.
+ if (!transformation_parameters->Empty())
+ return C_BAD_ENSEMBLE_HEADER;
+
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::PredictTransformParameters(
+ SinkStreamSet* all_predicted_parameters) {
+ for (size_t i = 0; i < patchers_.size(); ++i) {
+ SinkStreamSet single_predicted_parameters;
+ Status status =
+ patchers_[i]->PredictTransformParameters(&single_predicted_parameters);
+ if (status != C_OK)
+ return status;
+ if (!all_predicted_parameters->WriteSet(&single_predicted_parameters))
+ return C_STREAM_ERROR;
+ }
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::SubpatchTransformParameters(
+ SinkStreamSet* predicted_parameters,
+ SourceStream* correction,
+ SourceStreamSet* corrected_parameters) {
+ return SubpatchStreamSets(predicted_parameters,
+ correction,
+ corrected_parameters,
+ &corrected_parameters_storage_);
+}
+
+Status EnsemblePatchApplication::TransformUp(
+ SourceStreamSet* parameters,
+ SinkStreamSet* transformed_elements) {
+ for (size_t i = 0; i < patchers_.size(); ++i) {
+ SourceStreamSet single_parameters;
+ if (!parameters->ReadSet(&single_parameters))
+ return C_STREAM_ERROR;
+ SinkStreamSet single_transformed_element;
+ Status status = patchers_[i]->Transform(&single_parameters,
+ &single_transformed_element);
+ if (status != C_OK)
+ return status;
+ if (!single_parameters.Empty())
+ return C_STREAM_NOT_CONSUMED;
+ if (!transformed_elements->WriteSet(&single_transformed_element))
+ return C_STREAM_ERROR;
+ }
+
+ if (!parameters->Empty())
+ return C_STREAM_NOT_CONSUMED;
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::SubpatchTransformedElements(
+ SinkStreamSet* predicted_elements,
+ SourceStream* correction,
+ SourceStreamSet* corrected_elements) {
+ return SubpatchStreamSets(predicted_elements,
+ correction,
+ corrected_elements,
+ &corrected_elements_storage_);
+}
+
+Status EnsemblePatchApplication::TransformDown(
+ SourceStreamSet* transformed_elements,
+ SinkStream* basic_elements) {
+ // Construct blob of original input followed by reformed elements.
+
+ // The original input:
+ basic_elements->Write(base_region_.start(), base_region_.length());
+
+ for (size_t i = 0; i < patchers_.size(); ++i) {
+ SourceStreamSet single_corrected_element;
+ if (!transformed_elements->ReadSet(&single_corrected_element))
+ return C_STREAM_ERROR;
+ Status status = patchers_[i]->Reform(&single_corrected_element,
+ basic_elements);
+ if (status != C_OK)
+ return status;
+ if (!single_corrected_element.Empty())
+ return C_STREAM_NOT_CONSUMED;
+ }
+
+ if (!transformed_elements->Empty())
+ return C_STREAM_NOT_CONSUMED;
+
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::SubpatchFinalOutput(
+ SourceStream* original,
+ SourceStream* correction,
+ SinkStream* corrected_ensemble) {
+ Status delta_status = ApplySimpleDelta(original, correction,
+ corrected_ensemble);
+ if (delta_status != C_OK)
+ return delta_status;
+
+ if (CalculateCrc(corrected_ensemble->Buffer(),
+ corrected_ensemble->Length()) != target_checksum_)
+ return C_BAD_ENSEMBLE_CRC;
+
+ return C_OK;
+}
+
+Status EnsemblePatchApplication::SubpatchStreamSets(
+ SinkStreamSet* predicted_items,
+ SourceStream* correction,
+ SourceStreamSet* corrected_items,
+ SinkStream* corrected_items_storage) {
+ SinkStream linearized_predicted_items;
+ if (!predicted_items->CopyTo(&linearized_predicted_items))
+ return C_STREAM_ERROR;
+
+ SourceStream prediction;
+ prediction.Init(linearized_predicted_items);
+
+ Status status = ApplySimpleDelta(&prediction,
+ correction,
+ corrected_items_storage);
+ if (status != C_OK)
+ return status;
+
+ if (!corrected_items->Init(corrected_items_storage->Buffer(),
+ corrected_items_storage->Length()))
+ return C_STREAM_ERROR;
+
+ return C_OK;
+}
+
+Status ApplyEnsemblePatch(SourceStream* base,
+ SourceStream* patch,
+ SinkStream* output) {
+ Status status;
+ EnsemblePatchApplication patch_process;
+
+ status = patch_process.ReadHeader(patch);
+ if (status != C_OK)
+ return status;
+
+ status = patch_process.InitBase(Region(base->Buffer(), base->Remaining()));
+ if (status != C_OK)
+ return status;
+
+ status = patch_process.ValidateBase();
+ if (status != C_OK)
+ return status;
+
+ // The rest of the patch stream is a StreamSet.
+ SourceStreamSet patch_streams;
+ patch_streams.Init(patch);
+
+ SourceStream* transformation_descriptions = patch_streams.stream(0);
+ SourceStream* parameter_correction = patch_streams.stream(1);
+ SourceStream* transformed_elements_correction = patch_streams.stream(2);
+ SourceStream* ensemble_correction = patch_streams.stream(3);
+
+ status = patch_process.ReadInitialParameters(transformation_descriptions);
+ if (status != C_OK)
+ return status;
+
+ SinkStreamSet predicted_parameters;
+ status = patch_process.PredictTransformParameters(&predicted_parameters);
+ if (status != C_OK)
+ return status;
+
+ SourceStreamSet corrected_parameters;
+ status = patch_process.SubpatchTransformParameters(&predicted_parameters,
+ parameter_correction,
+ &corrected_parameters);
+ if (status != C_OK)
+ return status;
+
+ SinkStreamSet transformed_elements;
+ status = patch_process.TransformUp(&corrected_parameters,
+ &transformed_elements);
+ if (status != C_OK)
+ return status;
+
+ SourceStreamSet corrected_transformed_elements;
+ status = patch_process.SubpatchTransformedElements(
+ &transformed_elements,
+ transformed_elements_correction,
+ &corrected_transformed_elements);
+ if (status != C_OK)
+ return status;
+
+ SinkStream original_ensemble_and_corrected_base_elements;
+ status = patch_process.TransformDown(
+ &corrected_transformed_elements,
+ &original_ensemble_and_corrected_base_elements);
+ if (status != C_OK)
+ return status;
+
+ SourceStream final_patch_prediction;
+ final_patch_prediction.Init(original_ensemble_and_corrected_base_elements);
+ status = patch_process.SubpatchFinalOutput(&final_patch_prediction,
+ ensemble_correction, output);
+ if (status != C_OK)
+ return status;
+
+ return C_OK;
+}
+
+Status ApplyEnsemblePatch(const wchar_t* old_file_name,
+ const wchar_t* patch_file_name,
+ const wchar_t* new_file_name) {
+ Status status;
+
+ // First read enough of the patch file to validate the header is well-formed.
+ // A few varint32 numbers should fit in 100.
+ FilePath patch_file_path(patch_file_name);
+ const int BIG_ENOUGH_FOR_HEADER = 100;
+ char buffer[BIG_ENOUGH_FOR_HEADER];
+ int read_count =
+ file_util::ReadFile(patch_file_path, buffer, sizeof(buffer));
+ if (read_count < 0)
+ return C_READ_OPEN_ERROR;
+
+ // 'Dry-run' the first step of the patch process to validate format of header.
+ SourceStream patch_header_stream;
+ patch_header_stream.Init(buffer, read_count);
+ EnsemblePatchApplication patch_process;
+ status = patch_process.ReadHeader(&patch_header_stream);
+ if (status != C_OK)
+ return status;
+
+ // Header smells good so read the whole patch file for real.
+ std::string patch_file_buffer;
+ if (!file_util::ReadFileToString(patch_file_path, &patch_file_buffer))
+ return C_READ_ERROR;
+
+ // Read the old_file.
+ FilePath old_file_path(old_file_name);
+ std::string old_file_buffer;
+ if (!file_util::ReadFileToString(old_file_path, &old_file_buffer))
+ return C_READ_ERROR;
+
+ // Apply patch on streams.
+ SourceStream old_source_stream;
+ SourceStream patch_source_stream;
+ old_source_stream.Init(old_file_buffer);
+ patch_source_stream.Init(patch_file_buffer);
+ SinkStream new_sink_stream;
+ status = ApplyEnsemblePatch(&old_source_stream, &patch_source_stream,
+ &new_sink_stream);
+
+ // Write the patched data to |new_file_name|.
+ FilePath new_file_path(new_file_name);
+ int written =
+ file_util::WriteFile(
+ new_file_path,
+ reinterpret_cast<const char*>(new_sink_stream.Buffer()),
+ new_sink_stream.Length());
+ if (written == -1)
+ return C_WRITE_OPEN_ERROR;
+ if (written != new_sink_stream.Length())
+ return C_WRITE_ERROR;
+
+ return C_OK;
+}
+
+} // namespace
diff --git a/third_party/courgette/ensemble_create.cc b/courgette/ensemble_create.cc
index 4d64f1c..6e64474 100644
--- a/third_party/courgette/ensemble_create.cc
+++ b/courgette/ensemble_create.cc
@@ -1,382 +1,382 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// The main idea in Courgette is to do patching *under a tranformation*. The
-// input is transformed into a new representation, patching occurs in the new
-// repesentation, and then the tranform is reversed to get the patched data.
-//
-// The idea is applied to pieces (or 'elements') of the whole (or 'ensemble').
-// Each of the elements has to go through the same set of steps in lock-step.
-
-// This file contains the code to create the patch.
-
-
-#include "third_party/courgette/ensemble.h"
-
-#include <vector>
-#include <limits>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "base/time.h"
-
-#include "third_party/courgette/bsdiff.h"
-#include "third_party/courgette/crc.h"
-#include "third_party/courgette/difference_estimator.h"
-#include "third_party/courgette/image_info.h"
-#include "third_party/courgette/streams.h"
-#include "third_party/courgette/region.h"
-#include "third_party/courgette/simple_delta.h"
-
-#include "third_party/courgette/win32_x86_patcher.h"
-#include "third_party/courgette/win32_x86_generator.h"
-
-namespace courgette {
-
-TransformationPatchGenerator::TransformationPatchGenerator(
- Element* old_element,
- Element* new_element,
- TransformationPatcher* patcher)
- : old_element_(old_element),
- new_element_(new_element),
- patcher_(patcher) {
-}
-
-TransformationPatchGenerator::~TransformationPatchGenerator() {
- delete patcher_;
-}
-
-// The default implementation of PredictTransformParameters delegates to the
-// patcher.
-Status TransformationPatchGenerator::PredictTransformParameters(
- SinkStreamSet* prediction) {
- return patcher_->PredictTransformParameters(prediction);
-}
-
-// The default implementation of Reform delegates to the patcher.
-Status TransformationPatchGenerator::Reform(
- SourceStreamSet* transformed_element,
- SinkStream* reformed_element) {
- return patcher_->Reform(transformed_element, reformed_element);
-}
-
-// Makes a TransformationPatchGenerator of the appropriate variety for the
-// Element kind.
-TransformationPatchGenerator* MakeGenerator(Element* old_element,
- Element* new_element) {
- if (new_element->kind() == Element::WIN32_X86_WITH_CODE) {
- CourgetteWin32X86PatchGenerator* generator =
- new CourgetteWin32X86PatchGenerator(
- old_element,
- new_element,
- new CourgetteWin32X86Patcher(old_element->region()));
- return generator;
- } else {
- LOG(WARNING) << "Unexpected Element::Kind " << old_element->kind();
- return NULL;
- }
-}
-
-// FindGenerators finds TransformationPatchGenerators for the elements of
-// |new_ensemble|. For each element of |new_ensemble| we find the closest
-// matching element from |old_ensemble| and use that as the basis for
-// differential compression. The elements have to be the same kind so as to
-// support transformation into the same kind of 'new representation'.
-//
-Status FindGenerators(Ensemble* old_ensemble, Ensemble* new_ensemble,
- std::vector<TransformationPatchGenerator*>* generators) {
- base::Time start_find_time = base::Time::Now();
- old_ensemble->FindEmbeddedElements();
- new_ensemble->FindEmbeddedElements();
- LOG(INFO) << "done FindEmbeddedElements "
- << (base::Time::Now() - start_find_time).InSecondsF();
-
- std::vector<Element*> old_elements(old_ensemble->elements());
- std::vector<Element*> new_elements(new_ensemble->elements());
-
- LOG(INFO) << "old has " << old_elements.size() << " elements";
- LOG(INFO) << "new has " << new_elements.size() << " elements";
-
- DifferenceEstimator difference_estimator;
- std::vector<DifferenceEstimator::Base*> bases;
-
- base::Time start_bases_time = base::Time::Now();
- for (size_t i = 0; i < old_elements.size(); ++i) {
- bases.push_back(
- difference_estimator.MakeBase(old_elements[i]->region()));
- }
- LOG(INFO) << "done make bases "
- << (base::Time::Now() - start_bases_time).InSecondsF()
- << "s";
-
- for (size_t new_index = 0; new_index < new_elements.size(); ++new_index) {
- Element* new_element = new_elements[new_index];
- DifferenceEstimator::Subject* new_subject =
- difference_estimator.MakeSubject(new_element->region());
-
- // Search through old elements to find the best match.
- //
- // TODO(sra): This is O(N x M), i.e. O(N^2) since old_ensemble and
- // new_ensemble probably have a very similar structure. We can make the
- // search faster by making the comparison provided by DifferenceEstimator
- // more nuanced, returning early if the measured difference is greater than
- // the current best. This will be most effective if we can arrange that the
- // first elements we try to match are likely the 'right' ones. We could
- // prioritize elements that are of a similar size or similar position in the
- // sequence of elements.
- //
- Element* best_old_element = NULL;
- size_t best_difference = std::numeric_limits<size_t>::max();
- for (size_t old_index = 0; old_index < old_elements.size(); ++old_index) {
- Element* old_element = old_elements[old_index];
- // Elements of different kinds are incompatible.
- if (old_element->kind() != new_element->kind())
- continue;
-
- base::Time start_compare = base::Time::Now();
- DifferenceEstimator::Base* old_base = bases[old_index];
- size_t difference = difference_estimator.Measure(old_base, new_subject);
-
- LOG(INFO) << "Compare " << old_element->Name()
- << " to " << new_element->Name()
- << " --> " << difference
- << " in " << (base::Time::Now() - start_compare).InSecondsF()
- << "s";
- if (difference == 0) {
- LOG(INFO) << "Skip " << new_element->Name()
- << " - identical to " << old_element->Name();
- best_difference = 0;
- best_old_element = NULL;
- break;
- }
- if (difference < best_difference) {
- best_difference = difference;
- best_old_element = old_element;
- }
- }
-
- if (best_old_element) {
- LOG(INFO) << "Matched " << best_old_element->Name()
- << " to " << new_element->Name()
- << " --> " << best_difference;
- TransformationPatchGenerator* generator =
- MakeGenerator(best_old_element, new_element);
- if (generator)
- generators->push_back(generator);
- }
- }
-
- LOG(INFO) << "done FindGenerators "
- << "found " << generators->size() << " in "
- << (base::Time::Now() - start_find_time).InSecondsF() << "s";
-
- return C_OK;
-}
-
-void FreeGenerators(std::vector<TransformationPatchGenerator*>* generators) {
- for (size_t i = 0; i < generators->size(); ++i) {
- delete (*generators)[i];
- }
- generators->clear();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-Status GenerateEnsemblePatch(SourceStream* base,
- SourceStream* update,
- SinkStream* final_patch) {
- Region old_region(base->Buffer(), base->Remaining());
- Region new_region(update->Buffer(), update->Remaining());
- Ensemble old_ensemble(old_region, "old");
- Ensemble new_ensemble(new_region, "new");
- std::vector<TransformationPatchGenerator*> generators;
- Status generators_status = FindGenerators(&old_ensemble, &new_ensemble,
- &generators);
- if (generators_status != C_OK)
- return generators_status;
-
- SinkStreamSet patch_streams;
-
- SinkStream* tranformation_descriptions = patch_streams.stream(0);
- SinkStream* parameter_correction = patch_streams.stream(1);
- SinkStream* transformed_elements_correction = patch_streams.stream(2);
- SinkStream* ensemble_correction = patch_streams.stream(3);
-
- uint32 number_of_transformations = generators.size();
- tranformation_descriptions->WriteVarint32(number_of_transformations);
-
- for (size_t i = 0; i < number_of_transformations; ++i) {
- CourgettePatchFile::TransformationMethodId kind = generators[i]->Kind();
- tranformation_descriptions->WriteVarint32(kind);
- }
-
- for (size_t i = 0; i < number_of_transformations; ++i) {
- Status status =
- generators[i]->WriteInitialParameters(tranformation_descriptions);
- if (status != C_OK)
- return status;
- }
-
- //
- // Generate sub-patch for parameters.
- //
- SinkStreamSet predicted_parameters_sink;
- SinkStreamSet corrected_parameters_sink;
-
- for (size_t i = 0; i < number_of_transformations; ++i) {
- SinkStreamSet single_predicted_parameters;
- Status status;
- status = generators[i]->PredictTransformParameters(
- &single_predicted_parameters);
- if (status != C_OK)
- return status;
- if (!predicted_parameters_sink.WriteSet(&single_predicted_parameters))
- return C_STREAM_ERROR;
-
- SinkStreamSet single_corrected_parameters;
- status = generators[i]->CorrectedTransformParameters(
- &single_corrected_parameters);
- if (status != C_OK)
- return status;
- if (!corrected_parameters_sink.WriteSet(&single_corrected_parameters))
- return C_STREAM_ERROR;
- }
-
- SinkStream linearized_predicted_parameters;
- SinkStream linearized_corrected_parameters;
-
- if (!predicted_parameters_sink.CopyTo(&linearized_predicted_parameters))
- return C_STREAM_ERROR;
- if (!corrected_parameters_sink.CopyTo(&linearized_corrected_parameters))
- return C_STREAM_ERROR;
-
- SourceStream predicted_parameters_source;
- SourceStream corrected_parameters_source;
- predicted_parameters_source.Init(linearized_predicted_parameters);
- corrected_parameters_source.Init(linearized_corrected_parameters);
-
- Status delta1_status = GenerateSimpleDelta(&predicted_parameters_source,
- &corrected_parameters_source,
- parameter_correction);
- if (delta1_status != C_OK)
- return delta1_status;
-
- //
- // Generate sub-patch for elements.
- //
- corrected_parameters_source.Init(linearized_corrected_parameters);
- SourceStreamSet corrected_parameters_source_set;
- if (!corrected_parameters_source_set.Init(&corrected_parameters_source))
- return C_STREAM_ERROR;
-
- SinkStreamSet predicted_transformed_elements;
- SinkStreamSet corrected_transformed_elements;
-
- for (size_t i = 0; i < number_of_transformations; ++i) {
- SourceStreamSet single_parameters;
- if (!corrected_parameters_source_set.ReadSet(&single_parameters))
- return C_STREAM_ERROR;
- SinkStreamSet single_predicted_transformed_element;
- SinkStreamSet single_corrected_transformed_element;
- Status status = generators[i]->Transform(
- &single_parameters,
- &single_predicted_transformed_element,
- &single_corrected_transformed_element);
- if (status != C_OK)
- return status;
- if (!single_parameters.Empty())
- return C_STREAM_NOT_CONSUMED;
- if (!predicted_transformed_elements.WriteSet(
- &single_predicted_transformed_element))
- return C_STREAM_ERROR;
- if (!corrected_transformed_elements.WriteSet(
- &single_corrected_transformed_element))
- return C_STREAM_ERROR;
- }
-
- if (!corrected_parameters_source_set.Empty())
- return C_STREAM_NOT_CONSUMED;
-
- SinkStream linearized_predicted_transformed_elements;
- SinkStream linearized_corrected_transformed_elements;
-
- if (!predicted_transformed_elements.CopyTo(
- &linearized_predicted_transformed_elements))
- return C_STREAM_ERROR;
- if (!corrected_transformed_elements.CopyTo(
- &linearized_corrected_transformed_elements))
- return C_STREAM_ERROR;
-
- SourceStream predicted_transformed_elements_source;
- SourceStream corrected_transformed_elements_source;
- predicted_transformed_elements_source
- .Init(linearized_predicted_transformed_elements);
- corrected_transformed_elements_source
- .Init(linearized_corrected_transformed_elements);
-
- Status delta2_status =
- GenerateSimpleDelta(&predicted_transformed_elements_source,
- &corrected_transformed_elements_source,
- transformed_elements_correction);
- if (delta2_status != C_OK)
- return delta2_status;
-
- //
- // Generate sub-patch for whole enchilada.
- //
- SinkStream predicted_ensemble;
-
- predicted_ensemble.Write(base->Buffer(), base->Remaining());
-
- SourceStreamSet corrected_transformed_elements_source_set;
- corrected_transformed_elements_source
- .Init(linearized_corrected_transformed_elements);
- if (!corrected_transformed_elements_source_set
- .Init(&corrected_transformed_elements_source))
- return C_STREAM_ERROR;
-
- for (size_t i = 0; i < number_of_transformations; ++i) {
- SourceStreamSet single_corrected_transformed_element;
- if (!corrected_transformed_elements_source_set.ReadSet(
- &single_corrected_transformed_element))
- return C_STREAM_ERROR;
- Status status = generators[i]->Reform(&single_corrected_transformed_element,
- &predicted_ensemble);
- if (status != C_OK)
- return status;
- if (!single_corrected_transformed_element.Empty())
- return C_STREAM_NOT_CONSUMED;
- }
-
- if (!corrected_transformed_elements_source_set.Empty())
- return C_STREAM_NOT_CONSUMED;
-
- FreeGenerators(&generators);
-
- SourceStream predicted_ensemble_source;
- predicted_ensemble_source.Init(predicted_ensemble);
- Status delta3_status = GenerateSimpleDelta(&predicted_ensemble_source,
- update,
- ensemble_correction);
- if (delta3_status != C_OK)
- return delta3_status;
-
- //
- // Final output stream has a header followed by a StreamSet.
- //
- final_patch->WriteVarint32(CourgettePatchFile::kMagic);
- final_patch->WriteVarint32(CourgettePatchFile::kVersion);
-
- final_patch->WriteVarint32(
- CalculateCrc(old_region.start(), old_region.length()));
- final_patch->WriteVarint32(
- CalculateCrc(new_region.start(), new_region.length()));
-
- if (!patch_streams.CopyTo(final_patch))
- return C_STREAM_ERROR;
-
- return C_OK;
-}
-
-} // namespace
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// The main idea in Courgette is to do patching *under a tranformation*. The
+// input is transformed into a new representation, patching occurs in the new
+// repesentation, and then the tranform is reversed to get the patched data.
+//
+// The idea is applied to pieces (or 'elements') of the whole (or 'ensemble').
+// Each of the elements has to go through the same set of steps in lock-step.
+
+// This file contains the code to create the patch.
+
+
+#include "courgette/ensemble.h"
+
+#include <vector>
+#include <limits>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "base/time.h"
+
+#include "courgette/third_party/bsdiff.h"
+#include "courgette/crc.h"
+#include "courgette/difference_estimator.h"
+#include "courgette/image_info.h"
+#include "courgette/streams.h"
+#include "courgette/region.h"
+#include "courgette/simple_delta.h"
+
+#include "courgette/win32_x86_patcher.h"
+#include "courgette/win32_x86_generator.h"
+
+namespace courgette {
+
+TransformationPatchGenerator::TransformationPatchGenerator(
+ Element* old_element,
+ Element* new_element,
+ TransformationPatcher* patcher)
+ : old_element_(old_element),
+ new_element_(new_element),
+ patcher_(patcher) {
+}
+
+TransformationPatchGenerator::~TransformationPatchGenerator() {
+ delete patcher_;
+}
+
+// The default implementation of PredictTransformParameters delegates to the
+// patcher.
+Status TransformationPatchGenerator::PredictTransformParameters(
+ SinkStreamSet* prediction) {
+ return patcher_->PredictTransformParameters(prediction);
+}
+
+// The default implementation of Reform delegates to the patcher.
+Status TransformationPatchGenerator::Reform(
+ SourceStreamSet* transformed_element,
+ SinkStream* reformed_element) {
+ return patcher_->Reform(transformed_element, reformed_element);
+}
+
+// Makes a TransformationPatchGenerator of the appropriate variety for the
+// Element kind.
+TransformationPatchGenerator* MakeGenerator(Element* old_element,
+ Element* new_element) {
+ if (new_element->kind() == Element::WIN32_X86_WITH_CODE) {
+ CourgetteWin32X86PatchGenerator* generator =
+ new CourgetteWin32X86PatchGenerator(
+ old_element,
+ new_element,
+ new CourgetteWin32X86Patcher(old_element->region()));
+ return generator;
+ } else {
+ LOG(WARNING) << "Unexpected Element::Kind " << old_element->kind();
+ return NULL;
+ }
+}
+
+// FindGenerators finds TransformationPatchGenerators for the elements of
+// |new_ensemble|. For each element of |new_ensemble| we find the closest
+// matching element from |old_ensemble| and use that as the basis for
+// differential compression. The elements have to be the same kind so as to
+// support transformation into the same kind of 'new representation'.
+//
+Status FindGenerators(Ensemble* old_ensemble, Ensemble* new_ensemble,
+ std::vector<TransformationPatchGenerator*>* generators) {
+ base::Time start_find_time = base::Time::Now();
+ old_ensemble->FindEmbeddedElements();
+ new_ensemble->FindEmbeddedElements();
+ LOG(INFO) << "done FindEmbeddedElements "
+ << (base::Time::Now() - start_find_time).InSecondsF();
+
+ std::vector<Element*> old_elements(old_ensemble->elements());
+ std::vector<Element*> new_elements(new_ensemble->elements());
+
+ LOG(INFO) << "old has " << old_elements.size() << " elements";
+ LOG(INFO) << "new has " << new_elements.size() << " elements";
+
+ DifferenceEstimator difference_estimator;
+ std::vector<DifferenceEstimator::Base*> bases;
+
+ base::Time start_bases_time = base::Time::Now();
+ for (size_t i = 0; i < old_elements.size(); ++i) {
+ bases.push_back(
+ difference_estimator.MakeBase(old_elements[i]->region()));
+ }
+ LOG(INFO) << "done make bases "
+ << (base::Time::Now() - start_bases_time).InSecondsF()
+ << "s";
+
+ for (size_t new_index = 0; new_index < new_elements.size(); ++new_index) {
+ Element* new_element = new_elements[new_index];
+ DifferenceEstimator::Subject* new_subject =
+ difference_estimator.MakeSubject(new_element->region());
+
+ // Search through old elements to find the best match.
+ //
+ // TODO(sra): This is O(N x M), i.e. O(N^2) since old_ensemble and
+ // new_ensemble probably have a very similar structure. We can make the
+ // search faster by making the comparison provided by DifferenceEstimator
+ // more nuanced, returning early if the measured difference is greater than
+ // the current best. This will be most effective if we can arrange that the
+ // first elements we try to match are likely the 'right' ones. We could
+ // prioritize elements that are of a similar size or similar position in the
+ // sequence of elements.
+ //
+ Element* best_old_element = NULL;
+ size_t best_difference = std::numeric_limits<size_t>::max();
+ for (size_t old_index = 0; old_index < old_elements.size(); ++old_index) {
+ Element* old_element = old_elements[old_index];
+ // Elements of different kinds are incompatible.
+ if (old_element->kind() != new_element->kind())
+ continue;
+
+ base::Time start_compare = base::Time::Now();
+ DifferenceEstimator::Base* old_base = bases[old_index];
+ size_t difference = difference_estimator.Measure(old_base, new_subject);
+
+ LOG(INFO) << "Compare " << old_element->Name()
+ << " to " << new_element->Name()
+ << " --> " << difference
+ << " in " << (base::Time::Now() - start_compare).InSecondsF()
+ << "s";
+ if (difference == 0) {
+ LOG(INFO) << "Skip " << new_element->Name()
+ << " - identical to " << old_element->Name();
+ best_difference = 0;
+ best_old_element = NULL;
+ break;
+ }
+ if (difference < best_difference) {
+ best_difference = difference;
+ best_old_element = old_element;
+ }
+ }
+
+ if (best_old_element) {
+ LOG(INFO) << "Matched " << best_old_element->Name()
+ << " to " << new_element->Name()
+ << " --> " << best_difference;
+ TransformationPatchGenerator* generator =
+ MakeGenerator(best_old_element, new_element);
+ if (generator)
+ generators->push_back(generator);
+ }
+ }
+
+ LOG(INFO) << "done FindGenerators "
+ << "found " << generators->size() << " in "
+ << (base::Time::Now() - start_find_time).InSecondsF() << "s";
+
+ return C_OK;
+}
+
+void FreeGenerators(std::vector<TransformationPatchGenerator*>* generators) {
+ for (size_t i = 0; i < generators->size(); ++i) {
+ delete (*generators)[i];
+ }
+ generators->clear();
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+Status GenerateEnsemblePatch(SourceStream* base,
+ SourceStream* update,
+ SinkStream* final_patch) {
+ Region old_region(base->Buffer(), base->Remaining());
+ Region new_region(update->Buffer(), update->Remaining());
+ Ensemble old_ensemble(old_region, "old");
+ Ensemble new_ensemble(new_region, "new");
+ std::vector<TransformationPatchGenerator*> generators;
+ Status generators_status = FindGenerators(&old_ensemble, &new_ensemble,
+ &generators);
+ if (generators_status != C_OK)
+ return generators_status;
+
+ SinkStreamSet patch_streams;
+
+ SinkStream* tranformation_descriptions = patch_streams.stream(0);
+ SinkStream* parameter_correction = patch_streams.stream(1);
+ SinkStream* transformed_elements_correction = patch_streams.stream(2);
+ SinkStream* ensemble_correction = patch_streams.stream(3);
+
+ uint32 number_of_transformations = generators.size();
+ tranformation_descriptions->WriteVarint32(number_of_transformations);
+
+ for (size_t i = 0; i < number_of_transformations; ++i) {
+ CourgettePatchFile::TransformationMethodId kind = generators[i]->Kind();
+ tranformation_descriptions->WriteVarint32(kind);
+ }
+
+ for (size_t i = 0; i < number_of_transformations; ++i) {
+ Status status =
+ generators[i]->WriteInitialParameters(tranformation_descriptions);
+ if (status != C_OK)
+ return status;
+ }
+
+ //
+ // Generate sub-patch for parameters.
+ //
+ SinkStreamSet predicted_parameters_sink;
+ SinkStreamSet corrected_parameters_sink;
+
+ for (size_t i = 0; i < number_of_transformations; ++i) {
+ SinkStreamSet single_predicted_parameters;
+ Status status;
+ status = generators[i]->PredictTransformParameters(
+ &single_predicted_parameters);
+ if (status != C_OK)
+ return status;
+ if (!predicted_parameters_sink.WriteSet(&single_predicted_parameters))
+ return C_STREAM_ERROR;
+
+ SinkStreamSet single_corrected_parameters;
+ status = generators[i]->CorrectedTransformParameters(
+ &single_corrected_parameters);
+ if (status != C_OK)
+ return status;
+ if (!corrected_parameters_sink.WriteSet(&single_corrected_parameters))
+ return C_STREAM_ERROR;
+ }
+
+ SinkStream linearized_predicted_parameters;
+ SinkStream linearized_corrected_parameters;
+
+ if (!predicted_parameters_sink.CopyTo(&linearized_predicted_parameters))
+ return C_STREAM_ERROR;
+ if (!corrected_parameters_sink.CopyTo(&linearized_corrected_parameters))
+ return C_STREAM_ERROR;
+
+ SourceStream predicted_parameters_source;
+ SourceStream corrected_parameters_source;
+ predicted_parameters_source.Init(linearized_predicted_parameters);
+ corrected_parameters_source.Init(linearized_corrected_parameters);
+
+ Status delta1_status = GenerateSimpleDelta(&predicted_parameters_source,
+ &corrected_parameters_source,
+ parameter_correction);
+ if (delta1_status != C_OK)
+ return delta1_status;
+
+ //
+ // Generate sub-patch for elements.
+ //
+ corrected_parameters_source.Init(linearized_corrected_parameters);
+ SourceStreamSet corrected_parameters_source_set;
+ if (!corrected_parameters_source_set.Init(&corrected_parameters_source))
+ return C_STREAM_ERROR;
+
+ SinkStreamSet predicted_transformed_elements;
+ SinkStreamSet corrected_transformed_elements;
+
+ for (size_t i = 0; i < number_of_transformations; ++i) {
+ SourceStreamSet single_parameters;
+ if (!corrected_parameters_source_set.ReadSet(&single_parameters))
+ return C_STREAM_ERROR;
+ SinkStreamSet single_predicted_transformed_element;
+ SinkStreamSet single_corrected_transformed_element;
+ Status status = generators[i]->Transform(
+ &single_parameters,
+ &single_predicted_transformed_element,
+ &single_corrected_transformed_element);
+ if (status != C_OK)
+ return status;
+ if (!single_parameters.Empty())
+ return C_STREAM_NOT_CONSUMED;
+ if (!predicted_transformed_elements.WriteSet(
+ &single_predicted_transformed_element))
+ return C_STREAM_ERROR;
+ if (!corrected_transformed_elements.WriteSet(
+ &single_corrected_transformed_element))
+ return C_STREAM_ERROR;
+ }
+
+ if (!corrected_parameters_source_set.Empty())
+ return C_STREAM_NOT_CONSUMED;
+
+ SinkStream linearized_predicted_transformed_elements;
+ SinkStream linearized_corrected_transformed_elements;
+
+ if (!predicted_transformed_elements.CopyTo(
+ &linearized_predicted_transformed_elements))
+ return C_STREAM_ERROR;
+ if (!corrected_transformed_elements.CopyTo(
+ &linearized_corrected_transformed_elements))
+ return C_STREAM_ERROR;
+
+ SourceStream predicted_transformed_elements_source;
+ SourceStream corrected_transformed_elements_source;
+ predicted_transformed_elements_source
+ .Init(linearized_predicted_transformed_elements);
+ corrected_transformed_elements_source
+ .Init(linearized_corrected_transformed_elements);
+
+ Status delta2_status =
+ GenerateSimpleDelta(&predicted_transformed_elements_source,
+ &corrected_transformed_elements_source,
+ transformed_elements_correction);
+ if (delta2_status != C_OK)
+ return delta2_status;
+
+ //
+ // Generate sub-patch for whole enchilada.
+ //
+ SinkStream predicted_ensemble;
+
+ predicted_ensemble.Write(base->Buffer(), base->Remaining());
+
+ SourceStreamSet corrected_transformed_elements_source_set;
+ corrected_transformed_elements_source
+ .Init(linearized_corrected_transformed_elements);
+ if (!corrected_transformed_elements_source_set
+ .Init(&corrected_transformed_elements_source))
+ return C_STREAM_ERROR;
+
+ for (size_t i = 0; i < number_of_transformations; ++i) {
+ SourceStreamSet single_corrected_transformed_element;
+ if (!corrected_transformed_elements_source_set.ReadSet(
+ &single_corrected_transformed_element))
+ return C_STREAM_ERROR;
+ Status status = generators[i]->Reform(&single_corrected_transformed_element,
+ &predicted_ensemble);
+ if (status != C_OK)
+ return status;
+ if (!single_corrected_transformed_element.Empty())
+ return C_STREAM_NOT_CONSUMED;
+ }
+
+ if (!corrected_transformed_elements_source_set.Empty())
+ return C_STREAM_NOT_CONSUMED;
+
+ FreeGenerators(&generators);
+
+ SourceStream predicted_ensemble_source;
+ predicted_ensemble_source.Init(predicted_ensemble);
+ Status delta3_status = GenerateSimpleDelta(&predicted_ensemble_source,
+ update,
+ ensemble_correction);
+ if (delta3_status != C_OK)
+ return delta3_status;
+
+ //
+ // Final output stream has a header followed by a StreamSet.
+ //
+ final_patch->WriteVarint32(CourgettePatchFile::kMagic);
+ final_patch->WriteVarint32(CourgettePatchFile::kVersion);
+
+ final_patch->WriteVarint32(
+ CalculateCrc(old_region.start(), old_region.length()));
+ final_patch->WriteVarint32(
+ CalculateCrc(new_region.start(), new_region.length()));
+
+ if (!patch_streams.CopyTo(final_patch))
+ return C_STREAM_ERROR;
+
+ return C_OK;
+}
+
+} // namespace
diff --git a/third_party/courgette/image_info.cc b/courgette/image_info.cc
index ca615dd..5651f36 100644
--- a/third_party/courgette/image_info.cc
+++ b/courgette/image_info.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/courgette/image_info.h"
+#include "courgette/image_info.h"
#include <memory.h>
#include <algorithm>
@@ -389,4 +389,3 @@ bool PEInfo::ParseRelocs(std::vector<RVA> *relocs) {
}
} // namespace courgette
-
diff --git a/third_party/courgette/image_info.h b/courgette/image_info.h
index ffdbe97..53a0be7 100644
--- a/third_party/courgette/image_info.h
+++ b/courgette/image_info.h
@@ -197,4 +197,3 @@ class PEInfo {
} // namespace
#endif // COURGETTE_IMAGE_INFO_H_
-
diff --git a/third_party/courgette/image_info_unittest.cc b/courgette/image_info_unittest.cc
index 43ef65f..6d6deb5 100644
--- a/third_party/courgette/image_info_unittest.cc
+++ b/courgette/image_info_unittest.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/courgette/image_info.h"
+#include "courgette/image_info.h"
#include <string>
@@ -20,7 +20,6 @@ class ImageInfoTest : public testing::Test {
private:
void SetUp() {
PathService::Get(base::DIR_SOURCE_ROOT, &test_dir_);
- // file_util::AppendToPath(&test_dir_, L"third_party");
file_util::AppendToPath(&test_dir_, L"courgette");
file_util::AppendToPath(&test_dir_, L"testdata");
}
diff --git a/third_party/courgette/memory_monitor.cc b/courgette/memory_monitor.cc
index 2077f12..51cb0cc 100644
--- a/third_party/courgette/memory_monitor.cc
+++ b/courgette/memory_monitor.cc
@@ -1,122 +1,122 @@
-#include <stdio.h>
-#include <map>
-
-#include "base/logging.h"
-#include "base/string_util.h"
-
-bool inH = true;
-struct H {
- H() { inH = false; tick_ = 0; bw_ = 0; d_bw_ = d_tick_ = 0; m_bw_ = 0; mem_ = high_ = 0;}
- ~H() {
- inH = true;
- int i = 0;
- for (M::iterator p = m_.begin(); p != m_.end(); ++p, ++i) {
- size_t s = p->first;
- LOG(INFO) << StringPrintf("%3d %8u: %8u %8u %8u %8u", i, s,
- m_[s], c_[s], h_[s], h_[s] * s);
- }
- LOG(INFO) << "Peak " << fmt(high_);
- }
-
- std::string fmt(size_t s) {
- if (s > 1000000000) return StringPrintf("%.3gG", s/(1000000000.0));
- if (s > 1000000) return StringPrintf("%.3gM", s/(1000000.));
- if (s > 9999) return StringPrintf("%.3gk", s/(1000.));
- return StringPrintf("%d", (int)s);
- }
-
- void tick(size_t w, char sign) {
- d_tick_ += 1;
- d_bw_ += w;
- const size_t T = 4*4*1024;
- const size_t M = 4*1024*1024;
- bool print = false;
- if (d_tick_ >= T) {
- tick_ += (d_tick_/T)*T;
- d_tick_ %= T;
- print = true;
- }
- if (d_bw_ >= M) {
- bw_ += (d_bw_/M) * M;
- d_bw_ %= M;
- print = true;
- }
- if (!print) return;
- std::string o;
- StringAppendF(&o, "%u:", tick_ + d_tick_);
- StringAppendF(&o, " (%c%s)", sign, fmt(w).c_str());
- size_t sum = 0;
- for (M::iterator p = c_.begin(); p != c_.end(); ++p) {
- size_t s = p->first;
- size_t n = p->second;
- if (n) {
- if (s*n >= 64*1024)
- if (n == 1)
- StringAppendF(&o, " %s", fmt(s).c_str());
- else
- StringAppendF(&o, " %s*%u", fmt(s).c_str(), n);
- sum += s*n;
- }
- }
- StringAppendF(&o, " = %s", fmt(sum).c_str());
- LOG(INFO) << o;
- //printf("%s\n", o.c_str());
- if (sum > 200*1024*1024) {
- // __asm int 3;
- m_bw_ = sum;
- }
- }
- void add(size_t s, void *p) {
- if (!inH) {
- inH = true;
- mem_ += s; if (mem_ > high_) high_ = mem_;
- c_[s] += 1;
- m_[s] += 1;
- if (c_[s] > h_[s]) h_[s] = c_[s];
- allocs_[p] = s;
- inH = false;
- tick(s, '+');
- }
- }
-
- void sub(void *p) {
- if (!inH) {
- inH = true;
- size_t s = allocs_[p];
- if (s) {
- mem_ -= s;
- c_[s] -= 1;
- allocs_[p] = 0;
- tick(s, '-');
- }
- inH = false;
- }
- }
-
- typedef std::map<size_t, size_t> M;
- M m_;
- M c_;
- M h_;
-
- size_t bw_;
- size_t d_bw_;
- size_t tick_;
- size_t d_tick_;
- size_t m_bw_;
- size_t mem_;
- size_t high_;
-
- std::map<void*, size_t> allocs_;
-} _H;
-
-void* operator new(size_t s) {
- //printf("%u\n", s);
- void *p = malloc(s);
- _H.add(s, p);
- return p;
-}
-
-void operator delete(void *p) {
- _H.sub(p);
- free(p);
-}
+#include <stdio.h>
+#include <map>
+
+#include "base/logging.h"
+#include "base/string_util.h"
+
+bool inH = true;
+struct H {
+ H() { inH = false; tick_ = 0; bw_ = 0; d_bw_ = d_tick_ = 0; m_bw_ = 0; mem_ = high_ = 0;}
+ ~H() {
+ inH = true;
+ int i = 0;
+ for (M::iterator p = m_.begin(); p != m_.end(); ++p, ++i) {
+ size_t s = p->first;
+ LOG(INFO) << StringPrintf("%3d %8u: %8u %8u %8u %8u", i, s,
+ m_[s], c_[s], h_[s], h_[s] * s);
+ }
+ LOG(INFO) << "Peak " << fmt(high_);
+ }
+
+ std::string fmt(size_t s) {
+ if (s > 1000000000) return StringPrintf("%.3gG", s/(1000000000.0));
+ if (s > 1000000) return StringPrintf("%.3gM", s/(1000000.));
+ if (s > 9999) return StringPrintf("%.3gk", s/(1000.));
+ return StringPrintf("%d", (int)s);
+ }
+
+ void tick(size_t w, char sign) {
+ d_tick_ += 1;
+ d_bw_ += w;
+ const size_t T = 4*4*1024;
+ const size_t M = 4*1024*1024;
+ bool print = false;
+ if (d_tick_ >= T) {
+ tick_ += (d_tick_/T)*T;
+ d_tick_ %= T;
+ print = true;
+ }
+ if (d_bw_ >= M) {
+ bw_ += (d_bw_/M) * M;
+ d_bw_ %= M;
+ print = true;
+ }
+ if (!print) return;
+ std::string o;
+ StringAppendF(&o, "%u:", tick_ + d_tick_);
+ StringAppendF(&o, " (%c%s)", sign, fmt(w).c_str());
+ size_t sum = 0;
+ for (M::iterator p = c_.begin(); p != c_.end(); ++p) {
+ size_t s = p->first;
+ size_t n = p->second;
+ if (n) {
+ if (s*n >= 64*1024)
+ if (n == 1)
+ StringAppendF(&o, " %s", fmt(s).c_str());
+ else
+ StringAppendF(&o, " %s*%u", fmt(s).c_str(), n);
+ sum += s*n;
+ }
+ }
+ StringAppendF(&o, " = %s", fmt(sum).c_str());
+ LOG(INFO) << o;
+ //printf("%s\n", o.c_str());
+ if (sum > 200*1024*1024) {
+ // __asm int 3;
+ m_bw_ = sum;
+ }
+ }
+ void add(size_t s, void *p) {
+ if (!inH) {
+ inH = true;
+ mem_ += s; if (mem_ > high_) high_ = mem_;
+ c_[s] += 1;
+ m_[s] += 1;
+ if (c_[s] > h_[s]) h_[s] = c_[s];
+ allocs_[p] = s;
+ inH = false;
+ tick(s, '+');
+ }
+ }
+
+ void sub(void *p) {
+ if (!inH) {
+ inH = true;
+ size_t s = allocs_[p];
+ if (s) {
+ mem_ -= s;
+ c_[s] -= 1;
+ allocs_[p] = 0;
+ tick(s, '-');
+ }
+ inH = false;
+ }
+ }
+
+ typedef std::map<size_t, size_t> M;
+ M m_;
+ M c_;
+ M h_;
+
+ size_t bw_;
+ size_t d_bw_;
+ size_t tick_;
+ size_t d_tick_;
+ size_t m_bw_;
+ size_t mem_;
+ size_t high_;
+
+ std::map<void*, size_t> allocs_;
+} _H;
+
+void* operator new(size_t s) {
+ //printf("%u\n", s);
+ void *p = malloc(s);
+ _H.add(s, p);
+ return p;
+}
+
+void operator delete(void *p) {
+ _H.sub(p);
+ free(p);
+}
diff --git a/third_party/courgette/region.h b/courgette/region.h
index 00a130f..4aafbca 100644
--- a/third_party/courgette/region.h
+++ b/courgette/region.h
@@ -1,62 +1,62 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef COURGETTE_REGION_H_
-#define COURGETTE_REGION_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-
-namespace courgette {
-
-// A Region is a descriptor for a region of memory. It has a start address and
-// a length measured in bytes. The Region object does not own the memory.
-//
-class Region {
- public:
- // Default constructor: and empty region.
- Region() : start_(NULL), length_(0) {}
-
- // Usual constructor for regions given a |start| address and |length|.
- Region(const void* start, size_t length)
- : start_(static_cast<const uint8*>(start)),
- length_(length) {
- }
-
- // String constructor. Region is owned by the string, so the string should
- // have a lifetime greater than the region.
- explicit Region(const std::string& string)
- : start_(reinterpret_cast<const uint8*>(string.c_str())),
- length_(string.length()) {
- }
-
- // Copy constructor.
- Region(const Region& other) : start_(other.start_), length_(other.length_) {}
-
- // Assignment 'operator' makes |this| region the same as |other|.
- Region& assign(const Region& other) {
- this->start_ = other.start_;
- this->length_ = other.length_;
- return *this;
- }
-
- // Returns the starting address of the region.
- const uint8* start() const { return start_; }
-
- // Returns the length of the region.
- size_t length() const { return length_; }
-
- // Returns the address after the last byte of the region.
- const uint8* end() const { return start_ + length_; }
-
- private:
- const uint8* start_;
- size_t length_;
-
- void operator=(const Region&); // Disallow assignment operator.
-};
-
-} // namespace
-#endif // COURGETTE_REGION_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COURGETTE_REGION_H_
+#define COURGETTE_REGION_H_
+
+#include <string>
+
+#include "base/basictypes.h"
+
+namespace courgette {
+
+// A Region is a descriptor for a region of memory. It has a start address and
+// a length measured in bytes. The Region object does not own the memory.
+//
+class Region {
+ public:
+ // Default constructor: and empty region.
+ Region() : start_(NULL), length_(0) {}
+
+ // Usual constructor for regions given a |start| address and |length|.
+ Region(const void* start, size_t length)
+ : start_(static_cast<const uint8*>(start)),
+ length_(length) {
+ }
+
+ // String constructor. Region is owned by the string, so the string should
+ // have a lifetime greater than the region.
+ explicit Region(const std::string& string)
+ : start_(reinterpret_cast<const uint8*>(string.c_str())),
+ length_(string.length()) {
+ }
+
+ // Copy constructor.
+ Region(const Region& other) : start_(other.start_), length_(other.length_) {}
+
+ // Assignment 'operator' makes |this| region the same as |other|.
+ Region& assign(const Region& other) {
+ this->start_ = other.start_;
+ this->length_ = other.length_;
+ return *this;
+ }
+
+ // Returns the starting address of the region.
+ const uint8* start() const { return start_; }
+
+ // Returns the length of the region.
+ size_t length() const { return length_; }
+
+ // Returns the address after the last byte of the region.
+ const uint8* end() const { return start_ + length_; }
+
+ private:
+ const uint8* start_;
+ size_t length_;
+
+ void operator=(const Region&); // Disallow assignment operator.
+};
+
+} // namespace
+#endif // COURGETTE_REGION_H_
diff --git a/third_party/courgette/run_all_unittests.cc b/courgette/run_all_unittests.cc
index 5a17ba1..b5fc4a6 100644
--- a/third_party/courgette/run_all_unittests.cc
+++ b/courgette/run_all_unittests.cc
@@ -1,10 +1,9 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/test_suite.h"
-
-int main(int argc, char** argv) {
- return TestSuite(argc, argv).Run();
-}
-
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/test_suite.h"
+
+int main(int argc, char** argv) {
+ return TestSuite(argc, argv).Run();
+}
diff --git a/third_party/courgette/simple_delta.cc b/courgette/simple_delta.cc
index 8f93095..71038fd 100644
--- a/third_party/courgette/simple_delta.cc
+++ b/courgette/simple_delta.cc
@@ -1,41 +1,41 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Implementation of the byte-level differential compression used internally by
-// Courgette.
-
-#include "third_party/courgette/simple_delta.h"
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-
-#include "third_party/courgette/bsdiff.h"
-
-namespace courgette {
-
-namespace {
-
-Status BSDiffStatusToStatus(BSDiffStatus status) {
- switch (status) {
- case OK: return C_OK;
- case CRC_ERROR: return C_BINARY_DIFF_CRC_ERROR;
- default: return C_GENERAL_ERROR;
- }
-}
-
-}
-
-Status ApplySimpleDelta(SourceStream* old, SourceStream* delta,
- SinkStream* target) {
- return BSDiffStatusToStatus(ApplyBinaryPatch(old, delta, target));
-}
-
-Status GenerateSimpleDelta(SourceStream* old, SourceStream* target,
- SinkStream* delta) {
- LOG(INFO) << "GenerateSimpleDelta "
- << old->Remaining() << " " << target->Remaining();
- return BSDiffStatusToStatus(CreateBinaryPatch(old, target, delta));
-}
-
-} // namespace courgette
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Implementation of the byte-level differential compression used internally by
+// Courgette.
+
+#include "courgette/simple_delta.h"
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+
+#include "courgette/third_party/bsdiff.h"
+
+namespace courgette {
+
+namespace {
+
+Status BSDiffStatusToStatus(BSDiffStatus status) {
+ switch (status) {
+ case OK: return C_OK;
+ case CRC_ERROR: return C_BINARY_DIFF_CRC_ERROR;
+ default: return C_GENERAL_ERROR;
+ }
+}
+
+}
+
+Status ApplySimpleDelta(SourceStream* old, SourceStream* delta,
+ SinkStream* target) {
+ return BSDiffStatusToStatus(ApplyBinaryPatch(old, delta, target));
+}
+
+Status GenerateSimpleDelta(SourceStream* old, SourceStream* target,
+ SinkStream* delta) {
+ LOG(INFO) << "GenerateSimpleDelta "
+ << old->Remaining() << " " << target->Remaining();
+ return BSDiffStatusToStatus(CreateBinaryPatch(old, target, delta));
+}
+
+} // namespace courgette
diff --git a/third_party/courgette/simple_delta.h b/courgette/simple_delta.h
index acb2227..d35333a 100644
--- a/third_party/courgette/simple_delta.h
+++ b/courgette/simple_delta.h
@@ -1,23 +1,23 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Byte level differential compression algorithm used by Courgette.
-
-#ifndef COURGETTE_SIMPLE_DELTA_H_
-#define COURGETTE_SIMPLE_DELTA_H_
-
-#include "third_party/courgette/courgette.h"
-#include "third_party/courgette/streams.h"
-
-namespace courgette {
-
-Status ApplySimpleDelta(SourceStream* old, SourceStream* delta,
- SinkStream* target);
-
-Status GenerateSimpleDelta(SourceStream* old, SourceStream* target,
- SinkStream* delta);
-
-} // namespace courgette
-
-#endif // COURGETTE_SIMPLE_DELTA_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Byte level differential compression algorithm used by Courgette.
+
+#ifndef COURGETTE_SIMPLE_DELTA_H_
+#define COURGETTE_SIMPLE_DELTA_H_
+
+#include "courgette/courgette.h"
+#include "courgette/streams.h"
+
+namespace courgette {
+
+Status ApplySimpleDelta(SourceStream* old, SourceStream* delta,
+ SinkStream* target);
+
+Status GenerateSimpleDelta(SourceStream* old, SourceStream* target,
+ SinkStream* delta);
+
+} // namespace courgette
+
+#endif // COURGETTE_SIMPLE_DELTA_H_
diff --git a/third_party/courgette/streams.cc b/courgette/streams.cc
index 9870cd2..365a416 100644
--- a/third_party/courgette/streams.cc
+++ b/courgette/streams.cc
@@ -16,7 +16,7 @@
// we use it to cluster similar kinds of data which helps to generate longer
// common subsequences and repeated sequences.
-#include "third_party/courgette/streams.h"
+#include "courgette/streams.h"
#include <io.h>
#include <memory.h>
@@ -31,7 +31,7 @@ static const unsigned int kStreamsSerializationFormatVersion = 20090218;
//
// This is a cut down Varint implementation, implementing only what we use for
-// streams. The original implementation is at google3/util/coding/varint.h
+// streams.
//
class Varint {
public:
diff --git a/third_party/courgette/streams.h b/courgette/streams.h
index 4985310..2fb824f 100644
--- a/third_party/courgette/streams.h
+++ b/courgette/streams.h
@@ -18,7 +18,7 @@
#include "base/basictypes.h"
-#include "third_party/courgette/region.h"
+#include "courgette/region.h"
namespace courgette {
diff --git a/third_party/courgette/streams_unittest.cc b/courgette/streams_unittest.cc
index 90a6061..dd330ce 100644
--- a/third_party/courgette/streams_unittest.cc
+++ b/courgette/streams_unittest.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/courgette/streams.h"
+#include "courgette/streams.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/third_party/courgette/testdata/en-US.dll b/courgette/testdata/en-US.dll
index f1ad46c..f1ad46c 100644
--- a/third_party/courgette/testdata/en-US.dll
+++ b/courgette/testdata/en-US.dll
Binary files differ
diff --git a/third_party/courgette/testdata/setup1.exe b/courgette/testdata/setup1.exe
index da072f5..da072f5 100644
--- a/third_party/courgette/testdata/setup1.exe
+++ b/courgette/testdata/setup1.exe
Binary files differ
diff --git a/third_party/courgette/testdata/setup2.exe b/courgette/testdata/setup2.exe
index 577a47f..577a47f 100644
--- a/third_party/courgette/testdata/setup2.exe
+++ b/courgette/testdata/setup2.exe
Binary files differ
diff --git a/third_party/courgette/LICENCE.bsdiff b/courgette/third_party/LICENCE
index c146b5b..c146b5b 100644
--- a/third_party/courgette/LICENCE.bsdiff
+++ b/courgette/third_party/LICENCE
diff --git a/courgette/third_party/README.chromium b/courgette/third_party/README.chromium
new file mode 100644
index 0000000..d3037a1
--- /dev/null
+++ b/courgette/third_party/README.chromium
@@ -0,0 +1,23 @@
+This directory contains an extensively modified version of Colin Percival's
+bsdiff, available in its original form from:
+
+ http://www.daemonology.net/bsdiff/
+
+The basic principles of operation are best understood by reading Colin's
+unpublised paper:
+
+Colin Percival, Naive differences of executable code, http://www.daemonology.net/bsdiff/, 200
+
+The copy on this directory so extensively modified that the binary format is
+incompatible with the original and it cannot be compiled outside the Chromium
+source tree or the Courgette project.
+
+List of changes made to original code:
+ - wrapped functions in 'courgette' namespace
+ - renamed .c files to .cc
+ - added bsdiff.h header file
+ - changed the code to use streams.h from courgette
+ - changed the encoding of numbers to use the 'varint' encoding
+ - reformatted code to be closer to Google coding standards
+ - renamed variables
+ - added comments
diff --git a/third_party/courgette/bsdiff.h b/courgette/third_party/bsdiff.h
index bf7fdec..bf7fdec 100644
--- a/third_party/courgette/bsdiff.h
+++ b/courgette/third_party/bsdiff.h
diff --git a/third_party/courgette/bsdiff_apply.cc b/courgette/third_party/bsdiff_apply.cc
index f45ae14..4b6a011 100644
--- a/third_party/courgette/bsdiff_apply.cc
+++ b/courgette/third_party/bsdiff_apply.cc
@@ -32,10 +32,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/courgette/bsdiff.h"
+#include "courgette/third_party/bsdiff.h"
-#include "third_party/courgette/crc.h"
-#include "third_party/courgette/streams.h"
+#include "courgette/crc.h"
+#include "courgette/streams.h"
namespace courgette {
diff --git a/third_party/courgette/bsdiff_create.cc b/courgette/third_party/bsdiff_create.cc
index cdd6cb6..d59dc21 100644
--- a/third_party/courgette/bsdiff_create.cc
+++ b/courgette/third_party/bsdiff_create.cc
@@ -19,7 +19,7 @@
--Stephen Adams <sra@chromium.org>
*/
-#include "third_party/courgette/bsdiff.h"
+#include "courgette/third_party/bsdiff.h"
#include <stdlib.h>
#include <algorithm>
@@ -29,8 +29,8 @@
#include "base/string_util.h"
#include "base/time.h"
-#include "third_party/courgette/crc.h"
-#include "third_party/courgette/streams.h"
+#include "courgette/crc.h"
+#include "courgette/streams.h"
namespace courgette {
diff --git a/third_party/courgette/win32_x86_generator.h b/courgette/win32_x86_generator.h
index 8d3e683..3aabe9f 100644
--- a/third_party/courgette/win32_x86_generator.h
+++ b/courgette/win32_x86_generator.h
@@ -1,126 +1,126 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This is the transformation and adjustment for Windows X86 executables.
-
-#ifndef COURGETTE_WIN32_X86_GENERATOR_H_
-#define COURGETTE_WIN32_X86_GENERATOR_H_
-
-#include "base/scoped_ptr.h"
-
-#include "third_party/courgette/ensemble.h"
-
-namespace courgette {
-
-class CourgetteWin32X86PatchGenerator : public TransformationPatchGenerator {
- public:
- CourgetteWin32X86PatchGenerator(Element* old_element,
- Element* new_element,
- CourgetteWin32X86Patcher* patcher)
- : TransformationPatchGenerator(old_element, new_element, patcher) {
- }
-
- CourgettePatchFile::TransformationMethodId Kind() {
- return CourgettePatchFile::T_COURGETTE_WIN32_X86;
- }
-
- Status WriteInitialParameters(SinkStream* parameter_stream) {
- parameter_stream->WriteVarint32(old_element_->offset_in_ensemble());
- parameter_stream->WriteVarint32(old_element_->region().length());
- return C_OK;
- // TODO(sra): Initialize |patcher_| with these parameters.
- }
-
- Status PredictTransformParameters(SinkStreamSet* prediction) {
- return TransformationPatchGenerator::PredictTransformParameters(prediction);
- }
-
- Status CorrectedTransformParameters(SinkStreamSet* parameters) {
- // No code needed to write an 'empty' parameter set.
- return C_OK;
- }
-
- // The format of a transformed_element is a serialized EncodedProgram. We
- // first disassemble the original old and new Elements into AssemblyPrograms.
- // Then we adjust the new AssemblyProgram to make it as much like the old one
- // as possible, before converting the AssemblyPrograms to EncodedPrograms and
- // serializing them.
- Status Transform(SourceStreamSet* corrected_parameters,
- SinkStreamSet* old_transformed_element,
- SinkStreamSet* new_transformed_element) {
- // Don't expect any corrected parameters.
- if (!corrected_parameters->Empty())
- return C_GENERAL_ERROR;
-
- // Generate old version of program using |corrected_parameters|.
- // TODO(sra): refactor to use same code from patcher_.
- AssemblyProgram* old_program = NULL;
- Status old_parse_status =
- ParseWin32X86PE(old_element_->region().start(),
- old_element_->region().length(),
- &old_program);
- if (old_parse_status != C_OK)
- return old_parse_status;
-
- AssemblyProgram* new_program = NULL;
- Status new_parse_status =
- ParseWin32X86PE(new_element_->region().start(),
- new_element_->region().length(),
- &new_program);
- if (new_parse_status != C_OK) {
- DeleteAssemblyProgram(old_program);
- return new_parse_status;
- }
-
- EncodedProgram* old_encoded = NULL;
- Status old_encode_status = Encode(old_program, &old_encoded);
- if (old_encode_status != C_OK) {
- DeleteAssemblyProgram(old_program);
- return old_encode_status;
- }
-
- Status old_write_status =
- WriteEncodedProgram(old_encoded, old_transformed_element);
- DeleteEncodedProgram(old_encoded);
- if (old_write_status != C_OK) {
- DeleteAssemblyProgram(old_program);
- return old_write_status;
- }
-
- Status adjust_status = Adjust(*old_program, new_program);
- DeleteAssemblyProgram(old_program);
- if (adjust_status != C_OK) {
- DeleteAssemblyProgram(new_program);
- return adjust_status;
- }
-
- EncodedProgram* new_encoded = NULL;
- Status new_encode_status = Encode(new_program, &new_encoded);
- DeleteAssemblyProgram(new_program);
- if (new_encode_status != C_OK)
- return new_encode_status;
-
- Status new_write_status =
- WriteEncodedProgram(new_encoded, new_transformed_element);
- DeleteEncodedProgram(new_encoded);
- if (new_write_status != C_OK)
- return new_write_status;
-
- return C_OK;
- }
-
- Status Reform(SourceStreamSet* transformed_element,
- SinkStream* reformed_element) {
- return TransformationPatchGenerator::Reform(transformed_element,
- reformed_element);
- }
-
- private:
- ~CourgetteWin32X86PatchGenerator() { }
-
- DISALLOW_COPY_AND_ASSIGN(CourgetteWin32X86PatchGenerator);
-};
-
-} // namespace courgette
-#endif // COURGETTE_WIN32_X86_GENERATOR_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This is the transformation and adjustment for Windows X86 executables.
+
+#ifndef COURGETTE_WIN32_X86_GENERATOR_H_
+#define COURGETTE_WIN32_X86_GENERATOR_H_
+
+#include "base/scoped_ptr.h"
+
+#include "courgette/ensemble.h"
+
+namespace courgette {
+
+class CourgetteWin32X86PatchGenerator : public TransformationPatchGenerator {
+ public:
+ CourgetteWin32X86PatchGenerator(Element* old_element,
+ Element* new_element,
+ CourgetteWin32X86Patcher* patcher)
+ : TransformationPatchGenerator(old_element, new_element, patcher) {
+ }
+
+ CourgettePatchFile::TransformationMethodId Kind() {
+ return CourgettePatchFile::T_COURGETTE_WIN32_X86;
+ }
+
+ Status WriteInitialParameters(SinkStream* parameter_stream) {
+ parameter_stream->WriteVarint32(old_element_->offset_in_ensemble());
+ parameter_stream->WriteVarint32(old_element_->region().length());
+ return C_OK;
+ // TODO(sra): Initialize |patcher_| with these parameters.
+ }
+
+ Status PredictTransformParameters(SinkStreamSet* prediction) {
+ return TransformationPatchGenerator::PredictTransformParameters(prediction);
+ }
+
+ Status CorrectedTransformParameters(SinkStreamSet* parameters) {
+ // No code needed to write an 'empty' parameter set.
+ return C_OK;
+ }
+
+ // The format of a transformed_element is a serialized EncodedProgram. We
+ // first disassemble the original old and new Elements into AssemblyPrograms.
+ // Then we adjust the new AssemblyProgram to make it as much like the old one
+ // as possible, before converting the AssemblyPrograms to EncodedPrograms and
+ // serializing them.
+ Status Transform(SourceStreamSet* corrected_parameters,
+ SinkStreamSet* old_transformed_element,
+ SinkStreamSet* new_transformed_element) {
+ // Don't expect any corrected parameters.
+ if (!corrected_parameters->Empty())
+ return C_GENERAL_ERROR;
+
+ // Generate old version of program using |corrected_parameters|.
+ // TODO(sra): refactor to use same code from patcher_.
+ AssemblyProgram* old_program = NULL;
+ Status old_parse_status =
+ ParseWin32X86PE(old_element_->region().start(),
+ old_element_->region().length(),
+ &old_program);
+ if (old_parse_status != C_OK)
+ return old_parse_status;
+
+ AssemblyProgram* new_program = NULL;
+ Status new_parse_status =
+ ParseWin32X86PE(new_element_->region().start(),
+ new_element_->region().length(),
+ &new_program);
+ if (new_parse_status != C_OK) {
+ DeleteAssemblyProgram(old_program);
+ return new_parse_status;
+ }
+
+ EncodedProgram* old_encoded = NULL;
+ Status old_encode_status = Encode(old_program, &old_encoded);
+ if (old_encode_status != C_OK) {
+ DeleteAssemblyProgram(old_program);
+ return old_encode_status;
+ }
+
+ Status old_write_status =
+ WriteEncodedProgram(old_encoded, old_transformed_element);
+ DeleteEncodedProgram(old_encoded);
+ if (old_write_status != C_OK) {
+ DeleteAssemblyProgram(old_program);
+ return old_write_status;
+ }
+
+ Status adjust_status = Adjust(*old_program, new_program);
+ DeleteAssemblyProgram(old_program);
+ if (adjust_status != C_OK) {
+ DeleteAssemblyProgram(new_program);
+ return adjust_status;
+ }
+
+ EncodedProgram* new_encoded = NULL;
+ Status new_encode_status = Encode(new_program, &new_encoded);
+ DeleteAssemblyProgram(new_program);
+ if (new_encode_status != C_OK)
+ return new_encode_status;
+
+ Status new_write_status =
+ WriteEncodedProgram(new_encoded, new_transformed_element);
+ DeleteEncodedProgram(new_encoded);
+ if (new_write_status != C_OK)
+ return new_write_status;
+
+ return C_OK;
+ }
+
+ Status Reform(SourceStreamSet* transformed_element,
+ SinkStream* reformed_element) {
+ return TransformationPatchGenerator::Reform(transformed_element,
+ reformed_element);
+ }
+
+ private:
+ ~CourgetteWin32X86PatchGenerator() { }
+
+ DISALLOW_COPY_AND_ASSIGN(CourgetteWin32X86PatchGenerator);
+};
+
+} // namespace courgette
+#endif // COURGETTE_WIN32_X86_GENERATOR_H_
diff --git a/third_party/courgette/win32_x86_patcher.h b/courgette/win32_x86_patcher.h
index 4febad4..9ab53d9 100644
--- a/third_party/courgette/win32_x86_patcher.h
+++ b/courgette/win32_x86_patcher.h
@@ -1,95 +1,95 @@
-// Copyright (c) 2009 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This is the transformation for Windows X86 executables.
-
-#ifndef COURGETTE_WIN32_X86_PATCHER_H_
-#define COURGETTE_WIN32_X86_PATCHER_H_
-
-#include "third_party/courgette/ensemble.h"
-
-namespace courgette {
-
-// CourgetteWin32X86Patcher is a TransformationPatcher for Windows 32-bit
-// executables.
-//
-class CourgetteWin32X86Patcher : public TransformationPatcher {
- public:
- explicit CourgetteWin32X86Patcher(const Region& region)
- : ensemble_region_(region) {
- }
-
- Status Init(SourceStream* parameter_stream) {
- if (!parameter_stream->ReadVarint32(&base_offset_))
- return C_BAD_TRANSFORM;
- if (!parameter_stream->ReadVarint32(&base_length_))
- return C_BAD_TRANSFORM;
-
- if (base_offset_ > ensemble_region_.length())
- return C_BAD_TRANSFORM;
- if (base_length_ > ensemble_region_.length() - base_offset_)
- return C_BAD_TRANSFORM;
-
- return C_OK;
- }
-
- Status PredictTransformParameters(SinkStreamSet* predicted_parameters) {
- // No code needed to write an 'empty' predicted parameter set.
- return C_OK;
- }
-
- Status Transform(SourceStreamSet* corrected_parameters,
- SinkStreamSet* transformed_element) {
- Status status;
- if (!corrected_parameters->Empty())
- return C_GENERAL_ERROR; // Don't expect any corrected parameters.
-
- AssemblyProgram* program = NULL;
- status = ParseWin32X86PE(ensemble_region_.start() + base_offset_,
- base_length_,
- &program);
- if (status != C_OK)
- return status;
-
- EncodedProgram* encoded = NULL;
- status = Encode(program, &encoded);
- DeleteAssemblyProgram(program);
- if (status != C_OK)
- return status;
-
- status = WriteEncodedProgram(encoded, transformed_element);
- DeleteEncodedProgram(encoded);
- if (status != C_OK)
- return status;
-
- return status;
- }
-
- Status Reform(SourceStreamSet* transformed_element,
- SinkStream* reformed_element) {
- Status status;
- EncodedProgram* encoded_program = NULL;
- status = ReadEncodedProgram(transformed_element, &encoded_program);
- if (status != C_OK)
- return status;
-
- status = Assemble(encoded_program, reformed_element);
- DeleteEncodedProgram(encoded_program);
- if (status != C_OK)
- return status;
-
- return C_OK;
- }
-
- private:
- Region ensemble_region_;
-
- uint32 base_offset_;
- uint32 base_length_;
-
- DISALLOW_COPY_AND_ASSIGN(CourgetteWin32X86Patcher);
-};
-
-} // namespace
-#endif // COURGETTE_WIN32_X86_PATCHER_H_
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This is the transformation for Windows X86 executables.
+
+#ifndef COURGETTE_WIN32_X86_PATCHER_H_
+#define COURGETTE_WIN32_X86_PATCHER_H_
+
+#include "courgette/ensemble.h"
+
+namespace courgette {
+
+// CourgetteWin32X86Patcher is a TransformationPatcher for Windows 32-bit
+// executables.
+//
+class CourgetteWin32X86Patcher : public TransformationPatcher {
+ public:
+ explicit CourgetteWin32X86Patcher(const Region& region)
+ : ensemble_region_(region) {
+ }
+
+ Status Init(SourceStream* parameter_stream) {
+ if (!parameter_stream->ReadVarint32(&base_offset_))
+ return C_BAD_TRANSFORM;
+ if (!parameter_stream->ReadVarint32(&base_length_))
+ return C_BAD_TRANSFORM;
+
+ if (base_offset_ > ensemble_region_.length())
+ return C_BAD_TRANSFORM;
+ if (base_length_ > ensemble_region_.length() - base_offset_)
+ return C_BAD_TRANSFORM;
+
+ return C_OK;
+ }
+
+ Status PredictTransformParameters(SinkStreamSet* predicted_parameters) {
+ // No code needed to write an 'empty' predicted parameter set.
+ return C_OK;
+ }
+
+ Status Transform(SourceStreamSet* corrected_parameters,
+ SinkStreamSet* transformed_element) {
+ Status status;
+ if (!corrected_parameters->Empty())
+ return C_GENERAL_ERROR; // Don't expect any corrected parameters.
+
+ AssemblyProgram* program = NULL;
+ status = ParseWin32X86PE(ensemble_region_.start() + base_offset_,
+ base_length_,
+ &program);
+ if (status != C_OK)
+ return status;
+
+ EncodedProgram* encoded = NULL;
+ status = Encode(program, &encoded);
+ DeleteAssemblyProgram(program);
+ if (status != C_OK)
+ return status;
+
+ status = WriteEncodedProgram(encoded, transformed_element);
+ DeleteEncodedProgram(encoded);
+ if (status != C_OK)
+ return status;
+
+ return status;
+ }
+
+ Status Reform(SourceStreamSet* transformed_element,
+ SinkStream* reformed_element) {
+ Status status;
+ EncodedProgram* encoded_program = NULL;
+ status = ReadEncodedProgram(transformed_element, &encoded_program);
+ if (status != C_OK)
+ return status;
+
+ status = Assemble(encoded_program, reformed_element);
+ DeleteEncodedProgram(encoded_program);
+ if (status != C_OK)
+ return status;
+
+ return C_OK;
+ }
+
+ private:
+ Region ensemble_region_;
+
+ uint32 base_offset_;
+ uint32 base_length_;
+
+ DISALLOW_COPY_AND_ASSIGN(CourgetteWin32X86Patcher);
+};
+
+} // namespace
+#endif // COURGETTE_WIN32_X86_PATCHER_H_