Coverage for /Syzygy/relink/relink_app.cc

CoverageLines executed / instrumented / missingexe / inst / missLanguageGroup
89.7%1131260.C++source

Line-by-line coverage:

   1    :  // Copyright 2012 Google Inc. All Rights Reserved.
   2    :  //
   3    :  // Licensed under the Apache License, Version 2.0 (the "License");
   4    :  // you may not use this file except in compliance with the License.
   5    :  // You may obtain a copy of the License at
   6    :  //
   7    :  //     http://www.apache.org/licenses/LICENSE-2.0
   8    :  //
   9    :  // Unless required by applicable law or agreed to in writing, software
  10    :  // distributed under the License is distributed on an "AS IS" BASIS,
  11    :  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12    :  // See the License for the specific language governing permissions and
  13    :  // limitations under the License.
  14    :  
  15    :  #include "syzygy/relink/relink_app.h"
  16    :  
  17    :  #include "base/strings/string_number_conversions.h"
  18    :  #include "syzygy/block_graph/orderers/original_orderer.h"
  19    :  #include "syzygy/block_graph/orderers/random_orderer.h"
  20    :  #include "syzygy/block_graph/transforms/fuzzing_transform.h"
  21    :  #include "syzygy/pe/pe_relinker.h"
  22    :  #include "syzygy/pe/transforms/explode_basic_blocks_transform.h"
  23    :  #include "syzygy/reorder/orderers/explicit_orderer.h"
  24    :  #include "syzygy/reorder/transforms/basic_block_layout_transform.h"
  25    :  
  26    :  namespace relink {
  27    :  
  28    :  namespace {
  29    :  
  30    :  const char kUsageFormatStr[] =
  31    :      "Usage: %ls [options]\n"
  32    :      "  Required Options:\n"
  33    :      "    --input-image=<path>  The input image file to relink.\n"
  34    :      "    --output-image=<path> Output path for the rewritten image file.\n"
  35    :      "  Options:\n"
  36    :      "    --basic-blocks        Reorder at the basic-block level. At present,\n"
  37    :      "                          this is only supported for random reorderings.\n"
  38    :      "    --code-alignment=<integer>\n"
  39    :      "                          Force a minimal alignment for code blocks.\n"
  40    :      "                          Default value is 1.\n"
  41    :      "    --compress-pdb        If --no-augment-pdb is specified, causes the\n"
  42    :      "                          augmented PDB stream to be compressed.\n"
  43    :      "    --exclude-bb-padding  When randomly reordering basic blocks, exclude\n"
  44    :      "                          padding and unreachable code from the relinked\n"
  45    :      "                          output binary.\n"
  46    :      "    --input-pdb=<path>    The PDB file associated with the input DLL.\n"
  47    :      "                          Default is inferred from input-image.\n"
  48    :      "    --no-augment-pdb      Indicates that the relinker should not augment\n"
  49    :      "                          the PDB with roundtrip decomposition info.\n"
  50    :      "    --no-metadata         Prevents the relinker from adding metadata\n"
  51    :      "                          to the output DLL.\n"
  52    :      "    --no-strip-strings    Causes strings to be output in the augmented\n"
  53    :      "                          PDB stream. The default is to omit these to\n"
  54    :      "                          make smaller PDBs.\n"
  55    :      "    --order-file=<path>   Reorder based on a JSON ordering file.\n"
  56    :      "    --output-pdb=<path>   Output path for the rewritten PDB file.\n"
  57    :      "                          Default is inferred from output-image.\n"
  58    :      "    --overwrite           Allow output files to be overwritten.\n"
  59    :      "    --padding=<integer>   Add bytes of padding between blocks.\n"
  60    :      "    --verbose             Log verbosely.\n"
  61    :      "\n"
  62    :      "  Testing Options:\n"
  63    :      "    --fuzz                Fuzz the binary.\n"
  64    :      "    --seed=<integer>      Randomly reorder based on the given seed.\n"
  65    :      "\n"
  66    :      "  Deprecated Options:\n"
  67    :      "    --input-dll=<path>    Aliased to --input-image.\n"
  68    :      "    --output-dll=<path>   Aliased to --output-image.\n"
  69    :      "\n"
  70    :      "  Notes:\n"
  71    :      "    * The --seed and --order-file options are mutually exclusive\n"
  72    :      "    * If --order-file is specified, --input-image is optional.\n"
  73    :      "    * The --compress-pdb and --no-strip-strings options are only\n"
  74    :      "      effective if --no-augment-pdb is not specified.\n"
  75    :      "    * The --exclude-bb-padding option is only effective if\n"
  76    :      "      --basic-blocks is specified.\n";
  77    :  
  78  E :  bool ParseUInt32(const std::wstring& value_str, uint32* out_value) {
  79  E :    DCHECK(out_value != NULL);
  80    :    unsigned temp;
  81  E :    if (!base::StringToUint(value_str, &temp))
  82  i :      return false;
  83  E :    *out_value = temp;
  84  E :    return true;
  85  E :  }
  86    :  
  87    :  void GuessPdbPath(const base::FilePath& module_path, base::FilePath* pdb_path) {
  88    :    DCHECK(pdb_path != NULL);
  89    :    *pdb_path = module_path.ReplaceExtension(L"pdb");
  90    :  }
  91    :  
  92    :  }  // namespace
  93    :  
  94  E :  bool RelinkApp::ParseCommandLine(const CommandLine* cmd_line) {
  95  E :    if (cmd_line->HasSwitch("help"))
  96  E :      return Usage(cmd_line, "");
  97    :  
  98  E :    input_image_path_ = AbsolutePath(cmd_line->GetSwitchValuePath("input-image"));
  99  E :    if (cmd_line->HasSwitch("input-dll")) {
 100  E :      if (input_image_path_.empty()) {
 101  E :        LOG(WARNING) << "Using deprecated switch --input-dll.";
 102    :        input_image_path_ =
 103  E :            AbsolutePath(cmd_line->GetSwitchValuePath("input-dll"));
 104  E :      } else {
 105    :        return Usage(cmd_line,
 106  E :                     "Can't specify both --input-dll and --input-image.");
 107    :      }
 108    :    }
 109  E :    input_pdb_path_ = AbsolutePath(cmd_line->GetSwitchValuePath("input-pdb"));
 110    :  
 111  E :    output_image_path_ = cmd_line->GetSwitchValuePath("output-image");
 112  E :    if (cmd_line->HasSwitch("output-dll")) {
 113  E :      if (output_image_path_.empty()) {
 114  E :        LOG(WARNING) << "Using deprecated switch --output-dll.";
 115    :        output_image_path_ =
 116  E :            AbsolutePath(cmd_line->GetSwitchValuePath("output-dll"));
 117  E :      } else {
 118    :        return Usage(cmd_line,
 119  E :                     "Can't specify both --output-dll and --output-image.");
 120    :      }
 121    :    }
 122    :  
 123  E :    output_pdb_path_ = cmd_line->GetSwitchValuePath("output-pdb");
 124  E :    order_file_path_ = AbsolutePath(cmd_line->GetSwitchValuePath("order-file"));
 125  E :    no_augment_pdb_ = cmd_line->HasSwitch("no-augment-pdb");
 126  E :    compress_pdb_ = cmd_line->HasSwitch("compress-pdb");
 127  E :    no_strip_strings_ = cmd_line->HasSwitch("no-strip-strings");
 128  E :    output_metadata_ = !cmd_line->HasSwitch("no-metadata");
 129  E :    overwrite_ = cmd_line->HasSwitch("overwrite");
 130  E :    basic_blocks_ = cmd_line->HasSwitch("basic-blocks");
 131  E :    exclude_bb_padding_ = cmd_line->HasSwitch("exclude-bb-padding");
 132  E :    fuzz_ = cmd_line->HasSwitch("fuzz");
 133    :  
 134    :    // The --output-image argument is required.
 135  E :    if (output_image_path_.empty()) {
 136  E :      return Usage(cmd_line, "You must specify --output-image.");
 137    :    }
 138    :  
 139    :    // Ensure that we have an input-image, either explicitly specified, or to be
 140    :    // taken from an order file.
 141  E :    if (input_image_path_.empty() && order_file_path_.empty()) {
 142    :      return Usage(
 143    :          cmd_line,
 144  E :          "You must specify --input-image if --order-file is not given.");
 145    :    }
 146    :  
 147    :    // Parse the random seed, if given. Note that the --seed and --order-file
 148    :    // arguments are mutually exclusive.
 149  E :    if (cmd_line->HasSwitch("seed")) {
 150  E :      if (cmd_line->HasSwitch("order-file")) {
 151    :        return Usage(cmd_line,
 152  i :                     "The seed and order-file arguments are mutually exclusive.");
 153    :      }
 154  E :      std::wstring seed_str(cmd_line->GetSwitchValueNative("seed"));
 155  E :      if (!ParseUInt32(seed_str, &seed_))
 156  i :        return Usage(cmd_line, "Invalid seed value.");
 157  E :    }
 158    :  
 159    :    // Parse the padding argument.
 160  E :    if (cmd_line->HasSwitch("padding")) {
 161  E :      std::wstring padding_str(cmd_line->GetSwitchValueNative("padding"));
 162  E :      if (!ParseUInt32(padding_str, &padding_))
 163  i :        return Usage(cmd_line, "Invalid padding value.");
 164  E :    }
 165    :  
 166    :    // Parse the code alignment argument.
 167  E :    if (cmd_line->HasSwitch("code-alignment")) {
 168  E :      std::wstring align_str(cmd_line->GetSwitchValueNative("code-alignment"));
 169  E :      if (!ParseUInt32(align_str, &code_alignment_))
 170  i :        return Usage(cmd_line, "Invalid code-alignment value.");
 171  E :      if (code_alignment_ == 0)
 172  i :        return Usage(cmd_line, "Code-alignment value cannot be zero.");
 173  E :    }
 174    :  
 175  E :    return true;
 176  E :  }
 177    :  
 178  E :  bool RelinkApp::SetUp() {
 179  E :    if (input_image_path_.empty()) {
 180  E :      DCHECK(!order_file_path_.empty());
 181    :      if (!reorder::Reorderer::Order::GetOriginalModulePath(order_file_path_,
 182  E :                                                            &input_image_path_)) {
 183  E :        LOG(ERROR) << "Unable to infer input-image.";
 184  E :        return false;
 185    :      }
 186    :  
 187  i :      LOG(INFO) << "Inferring input DLL path from order file: "
 188    :                << input_image_path_.value();
 189    :    }
 190    :  
 191  E :    DCHECK(!input_image_path_.empty());
 192  E :    DCHECK(!output_image_path_.empty());
 193  E :    DCHECK(order_file_path_.empty() || seed_ == 0);
 194    :  
 195  E :    return true;
 196  E :  }
 197    :  
 198  E :  int RelinkApp::Run() {
 199  E :    pe::PETransformPolicy policy;
 200  E :    pe::PERelinker relinker(&policy);
 201  E :    relinker.set_input_path(input_image_path_);
 202  E :    relinker.set_input_pdb_path(input_pdb_path_);
 203  E :    relinker.set_output_path(output_image_path_);
 204  E :    relinker.set_output_pdb_path(output_pdb_path_);
 205  E :    relinker.set_padding(padding_);
 206  E :    relinker.set_code_alignment(code_alignment_);
 207  E :    relinker.set_add_metadata(output_metadata_);
 208  E :    relinker.set_allow_overwrite(overwrite_);
 209  E :    relinker.set_augment_pdb(!no_augment_pdb_);
 210  E :    relinker.set_compress_pdb(compress_pdb_);
 211  E :    relinker.set_strip_strings(!no_strip_strings_);
 212    :  
 213    :    // Initialize the relinker. This does the decomposition, etc.
 214  E :    if (!relinker.Init()) {
 215  i :      LOG(ERROR) << "Failed to initialize relinker.";
 216  i :      return 1;
 217    :    }
 218    :  
 219    :    // Transforms that may be used.
 220  E :    scoped_ptr<pe::transforms::ExplodeBasicBlocksTransform> bb_explode;
 221  E :    scoped_ptr<reorder::transforms::BasicBlockLayoutTransform> bb_layout;
 222  E :    scoped_ptr<block_graph::transforms::FuzzingTransform> fuzzing_transform;
 223    :  
 224    :    // Orderers that may be used.
 225  E :    reorder::Reorderer::Order order;
 226  E :    scoped_ptr<block_graph::orderers::OriginalOrderer> orig_orderer;
 227  E :    scoped_ptr<block_graph::BlockGraphOrdererInterface> orderer;
 228    :  
 229    :    // If fuzzing is enabled, add it to the relinker.
 230  E :    if (fuzz_) {
 231  E :      fuzzing_transform.reset(new block_graph::transforms::FuzzingTransform);
 232  E :      CHECK(relinker.AppendTransform(fuzzing_transform.get()));
 233    :    }
 234    :  
 235    :    // If an order file is provided we are performing an explicit ordering.
 236  E :    if (!order_file_path_.empty()) {
 237    :      if (!order.LoadFromJSON(relinker.input_pe_file(),
 238    :                              relinker.input_image_layout(),
 239  E :                              order_file_path_)) {
 240  i :        LOG(ERROR) << "Failed to load order file: " << order_file_path_.value();
 241  i :        return 1;
 242    :      }
 243    :  
 244    :      // Allocate a BB layout transform. This applies the basic block portion of
 245    :      // the order specification. It will modify it in place so that it is ready
 246    :      // to be used by the ExplicitOrderer to finish the job.
 247  E :      bb_layout.reset(new reorder::transforms::BasicBlockLayoutTransform(&order));
 248  E :      CHECK(relinker.AppendTransform(bb_layout.get()));
 249    :  
 250    :      // Append an OriginalOrderer to the relinker. We do this so that the
 251    :      // original order is preserved entirely for sections that are not
 252    :      // fully specified by the order file, and therefore not ordered by the
 253    :      // ExplicitOrderer.
 254  E :      orig_orderer.reset(new block_graph::orderers::OriginalOrderer());
 255  E :      CHECK(relinker.AppendOrderer(orig_orderer.get()));
 256    :  
 257    :      // Allocate an explicit orderer.
 258  E :      orderer.reset(new reorder::orderers::ExplicitOrderer(&order));
 259  E :    } else {
 260    :      // No order file was provided, so we're doing a random ordering.
 261    :  
 262    :      // If we've been asked to go down to the basic block level, then we want to
 263    :      // use an explode basic blocks transform so that we randomize the entire
 264    :      // image at the BB level.
 265  E :      if (basic_blocks_) {
 266  E :        bb_explode.reset(new pe::transforms::ExplodeBasicBlocksTransform());
 267  E :        bb_explode->set_exclude_padding(exclude_bb_padding_);
 268  E :        CHECK(relinker.AppendTransform(bb_explode.get()));
 269    :      }
 270    :  
 271    :      // Allocate the random block orderer.
 272  E :      orderer.reset(new block_graph::orderers::RandomOrderer(true, seed_));
 273    :    }
 274    :  
 275    :    // Append the orderer to the relinker.
 276  E :    CHECK(relinker.AppendOrderer(orderer.get()));
 277    :  
 278    :    // Perform the actual relink.
 279  E :    if (!relinker.Relink()) {
 280  i :      LOG(ERROR) << "Unable to relink input image.";
 281  i :      return 1;
 282    :    }
 283    :  
 284  E :    return 0;
 285  E :  }
 286    :  
 287    :  bool RelinkApp::Usage(const CommandLine* cmd_line,
 288  E :                        const base::StringPiece& message) const {
 289  E :    if (!message.empty()) {
 290  E :      ::fwrite(message.data(), 1, message.length(), err());
 291  E :      ::fprintf(err(), "\n\n");
 292    :    }
 293    :  
 294    :    ::fprintf(err(),
 295    :              kUsageFormatStr,
 296  E :              cmd_line->GetProgram().BaseName().value().c_str());
 297    :  
 298  E :    return false;
 299  E :  }
 300    :  
 301    :  }  // namespace relink

Coverage information generated Thu Mar 26 16:15:41 2015.