1 : // Copyright 2014 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 :
16 : #include "syzygy/pe/transforms/pe_remove_empty_sections_transform.h"
17 :
18 : namespace pe {
19 : namespace transforms {
20 :
21 : namespace {
22 :
23 : using block_graph::BlockGraph;
24 :
25 : } // namespace
26 :
27 : const char PERemoveEmptySectionsTransform::kTransformName[] =
28 : "PERemoveEmptySectionsTransform";
29 :
30 E : PERemoveEmptySectionsTransform::PERemoveEmptySectionsTransform() {
31 E : }
32 :
33 : bool PERemoveEmptySectionsTransform::TransformBlockGraph(
34 : const TransformPolicyInterface* policy,
35 : BlockGraph* block_graph,
36 E : BlockGraph::Block* dos_header_block) {
37 E : DCHECK_NE(reinterpret_cast<TransformPolicyInterface*>(NULL), policy);
38 E : DCHECK_NE(reinterpret_cast<BlockGraph*>(NULL), block_graph);
39 E : DCHECK_NE(reinterpret_cast<BlockGraph::Block*>(NULL), dos_header_block);
40 E : DCHECK_EQ(BlockGraph::PE_IMAGE, block_graph->image_format());
41 :
42 : // Keep track of sections used by at least one block.
43 E : std::set<BlockGraph::SectionId> sections_used;
44 E : BlockGraph::BlockMap::const_iterator block = block_graph->blocks().begin();
45 E : for (; block != block_graph->blocks().end(); ++block)
46 E : sections_used.insert(block->second.section());
47 :
48 : // Remove unused sections.
49 E : std::set<BlockGraph::SectionId> sections_unused;
50 E : BlockGraph::SectionMap& sections = block_graph->sections_mutable();
51 E : BlockGraph::SectionMap::iterator it = sections.begin();
52 E : while (it != sections.end()) {
53 E : BlockGraph::Section& section = it->second;
54 E : ++it;
55 :
56 : // Check whether this section is used and remove it otherwise.
57 E : if (sections_used.find(section.id()) == sections_used.end()) {
58 E : LOG(INFO) << "Removing empty section: " << section.name();
59 E : block_graph->RemoveSectionById(section.id());
60 : }
61 E : }
62 :
63 E : return true;
64 E : }
65 :
66 : } // namespace transforms
67 : } // namespace pe
|