1 : // Copyright 2011 Google Inc.
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/reorder/random_order_generator.h"
16 :
17 : #include <algorithm>
18 :
19 : #include "syzygy/core/random_number_generator.h"
20 : #include "syzygy/pe/pe_utils.h"
21 :
22 : namespace reorder {
23 :
24 : RandomOrderGenerator::RandomOrderGenerator(int seed)
25 : : Reorderer::OrderGenerator("Random Order Generator"),
26 E : seed_(seed) {
27 E : }
28 :
29 E : RandomOrderGenerator::~RandomOrderGenerator() {
30 E : }
31 :
32 : bool RandomOrderGenerator::OnCodeBlockEntry(const BlockGraph::Block* /*block*/,
33 : RelativeAddress /*address*/,
34 : uint32 /*process_id*/,
35 : uint32 /*thread_id*/,
36 i : const UniqueTime& /*time*/) {
37 : // This is a NOP.
38 i : return true;
39 i : }
40 :
41 : bool RandomOrderGenerator::CalculateReordering(const PEFile& pe_file,
42 : const ImageLayout& image,
43 : bool reorder_code,
44 : bool reorder_data,
45 E : Order* order) {
46 E : DCHECK(order != NULL);
47 :
48 E : for (size_t i = 0; i < image.sections.size(); ++i) {
49 E : const ImageLayout::SectionInfo& section = image.sections[i];
50 : if ((!reorder_code && section.characteristics & IMAGE_SCN_CNT_CODE) ||
51 : (!reorder_data &&
52 E : section.characteristics & pe::kReadOnlyDataCharacteristics))
53 E : continue;
54 :
55 E : LOG(INFO) << "Randomizing section " << i << " (" << section.name << ").";
56 :
57 : // Prepare to iterate over all block in the section.
58 E : BlockGraph::AddressSpace::Range section_range(section.addr, section.size);
59 : AddressSpace::RangeMapConstIterPair section_blocks(
60 : image.blocks.GetIntersectingBlocks(
61 E : section_range.start(), section_range.size()));
62 :
63 : // Gather up all blocks within the section.
64 E : AddressSpace::RangeMapConstIter& section_it = section_blocks.first;
65 E : const AddressSpace::RangeMapConstIter& section_end = section_blocks.second;
66 E : Order::BlockList& block_list = order->section_block_lists[i];
67 E : for (; section_it != section_end; ++section_it) {
68 E : const BlockGraph::Block* block = section_it->second;
69 E : block_list.push_back(block);
70 E : }
71 :
72 E : core::RandomNumberGenerator random_number_generator(seed_ + i);
73 : std::random_shuffle(block_list.begin(),
74 : block_list.end(),
75 E : random_number_generator);
76 E : }
77 :
78 E : return true;
79 E : }
80 :
81 : } // namespace reorder
|