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 : // Unittests for the Asan transform.
16 :
17 : #include "syzygy/instrument/transforms/asan_transform.h"
18 :
19 : #include <set>
20 : #include <unordered_set>
21 : #include <vector>
22 :
23 : #include "base/scoped_native_library.h"
24 : #include "base/files/scoped_temp_dir.h"
25 : #include "base/strings/string_util.h"
26 : #include "base/strings/stringprintf.h"
27 : #include "base/win/pe_image.h"
28 : #include "gmock/gmock.h"
29 : #include "gtest/gtest.h"
30 : #include "syzygy/block_graph/basic_block_assembler.h"
31 : #include "syzygy/block_graph/block_hash.h"
32 : #include "syzygy/block_graph/unittest_util.h"
33 : #include "syzygy/common/defs.h"
34 : #include "syzygy/core/unittest_util.h"
35 : #include "syzygy/instrument/transforms/asan_intercepts.h"
36 : #include "syzygy/instrument/transforms/unittest_util.h"
37 : #include "syzygy/pe/coff_relinker.h"
38 : #include "syzygy/pe/coff_utils.h"
39 : #include "syzygy/pe/decomposer.h"
40 : #include "syzygy/pe/pe_file.h"
41 : #include "syzygy/pe/pe_relinker.h"
42 : #include "syzygy/pe/pe_utils.h"
43 : #include "syzygy/pe/unittest_util.h"
44 : #include "syzygy/pe/transforms/pe_add_imports_transform.h"
45 : #include "third_party/distorm/files/include/mnemonics.h"
46 :
47 : namespace instrument {
48 : namespace transforms {
49 :
50 : namespace {
51 :
52 : using block_graph::BasicBlock;
53 : using block_graph::BasicCodeBlock;
54 : using block_graph::BasicBlockSubGraph;
55 : using block_graph::BlockGraph;
56 : using block_graph::Instruction;
57 : using block_graph::RelativeAddressFilter;
58 : using core::RelativeAddress;
59 : using testing::ContainerEq;
60 : typedef AsanBasicBlockTransform::MemoryAccessMode AsanMemoryAccessMode;
61 : typedef AsanBasicBlockTransform::AsanHookMap HookMap;
62 : typedef AsanBasicBlockTransform::AsanHookMapEntryKey HookMapEntryKey;
63 :
64 : // Derived classes to expose protected members for unit-testing.
65 :
66 : class TestAsanBasicBlockTransform : public AsanBasicBlockTransform {
67 : public:
68 : using AsanBasicBlockTransform::InstrumentBasicBlock;
69 :
70 E : explicit TestAsanBasicBlockTransform(AsanHookMap* hooks_check_access)
71 : : AsanBasicBlockTransform(hooks_check_access) {
72 E : }
73 : };
74 :
75 : class TestAsanInterceptorFilter : public AsanInterceptorFilter {
76 : public:
77 : using AsanInterceptorFilter::AddBlockToHashMap;
78 : };
79 :
80 : class TestAsanTransform : public AsanTransform {
81 : public:
82 : using AsanTransform::asan_parameters_block_;
83 : using AsanTransform::heap_init_blocks_;
84 : using AsanTransform::hot_patched_blocks_;
85 : using AsanTransform::static_intercepted_blocks_;
86 : using AsanTransform::use_interceptors_;
87 : using AsanTransform::use_liveness_analysis_;
88 : using AsanTransform::CoffInterceptFunctions;
89 : using AsanTransform::FindHeapInitAndCrtHeapBlocks;
90 : using AsanTransform::ShouldSkipBlock;
91 : using AsanTransform::PeFindStaticallyLinkedFunctionsToIntercept;
92 : using AsanTransform::PeInterceptFunctions;
93 : using AsanTransform::PeInjectAsanParameters;
94 : };
95 :
96 : class AsanTransformTest : public testing::TestDllTransformTest {
97 : public:
98 E : AsanTransformTest() : basic_block_(NULL) {
99 E : basic_block_ = subgraph_.AddBasicCodeBlock("dummy");
100 : bb_asm_.reset(new block_graph::BasicBlockAssembler(
101 : basic_block_->instructions().begin(),
102 E : &basic_block_->instructions()));
103 :
104 : // Insert a block description into the subgraph containing the dummy
105 : // basic block.
106 : BasicBlockSubGraph::BlockDescription* description =
107 : subgraph_.AddBlockDescription("dummy_block", "dummy_compiland",
108 E : BlockGraph::CODE_BLOCK, 0, 1, 0);
109 E : description->basic_block_order.push_back(basic_block_);
110 E : }
111 :
112 E : void ApplyTransformToIntegrationTestDll() {
113 : base::FilePath input_path = ::testing::GetOutputRelativePath(
114 E : testing::kIntegrationTestsDllName);
115 :
116 E : base::FilePath temp_dir;
117 E : CreateTemporaryDir(&temp_dir);
118 E : relinked_path_ = temp_dir.Append(testing::kIntegrationTestsDllName);
119 :
120 E : pe::PERelinker relinker(&pe_policy_);
121 E : relinker.set_input_path(input_path);
122 E : relinker.set_output_path(relinked_path_);
123 :
124 E : asan_transform_.use_interceptors_ = true;
125 E : asan_transform_.use_liveness_analysis_ = true;
126 E : relinker.AppendTransform(&asan_transform_);
127 E : ASSERT_TRUE(relinker.Init());
128 E : ASSERT_TRUE(relinker.Relink());
129 E : }
130 :
131 : void AddHookRef(const std::string& hook_name,
132 : AsanBasicBlockTransform::MemoryAccessMode access_kind,
133 : int access_size,
134 : uint16_t opcode,
135 E : bool save_flags) {
136 : HookMapEntryKey map_key = {
137 : access_kind,
138 : access_size,
139 : opcode,
140 : save_flags
141 E : };
142 : hooks_check_access_[map_key] =
143 E : block_graph_.AddBlock(BlockGraph::CODE_BLOCK, 4, hook_name);
144 : // Set up the references to the hooks needed by SyzyAsan.
145 : hooks_check_access_ref_[map_key] =
146 : BlockGraph::Reference(BlockGraph::ABSOLUTE_REF, 4,
147 E : hooks_check_access_[map_key], 0, 0);
148 E : }
149 :
150 E : void InitHooksRefs() {
151 : // Initialize the read access hooks.
152 E : for (int access_size = 1; access_size <= 8; access_size *= 2) {
153 : std::string name =
154 E : base::StringPrintf("asan_check_%d_byte_read_access", access_size);
155 : AddHookRef(name, AsanBasicBlockTransform::kReadAccess, access_size, 0,
156 E : true);
157 E : name += "_no_flags";
158 : AddHookRef(name, AsanBasicBlockTransform::kReadAccess, access_size, 0,
159 E : false);
160 E : }
161 : // Initialize the write access hooks.
162 E : for (int access_size = 1; access_size <= 8; access_size *= 2) {
163 : std::string name =
164 E : base::StringPrintf("asan_check_%d_byte_write_access", access_size);
165 : AddHookRef(name, AsanBasicBlockTransform::kWriteAccess, access_size, 0,
166 E : true);
167 E : name += "_no_flags";
168 : AddHookRef(name, AsanBasicBlockTransform::kWriteAccess, access_size, 0,
169 E : false);
170 E : }
171 :
172 E : const _InstructionType strings[] = { I_CMPS, I_MOVS, I_STOS };
173 E : int strings_length = arraysize(strings);
174 :
175 E : for (int access_size = 1; access_size <= 4; access_size *= 2) {
176 E : for (int inst = 0; inst < strings_length; ++inst) {
177 E : uint16_t opcode = strings[inst];
178 : const char* opcode_str =
179 E : reinterpret_cast<const char*>(GET_MNEMONIC_NAME(opcode));
180 : std::string name =
181 : base::StringPrintf("asan_check_repz_%d_byte_%s_access",
182 E : access_size, opcode_str);
183 E : name = base::ToLowerASCII(name);
184 : AddHookRef(name, AsanBasicBlockTransform::kRepzAccess, access_size,
185 E : opcode, true);
186 E : }
187 E : }
188 :
189 : // Initialize special instruction hooks.
190 E : for (int access_size = 1; access_size <= 4; access_size *= 2) {
191 E : for (int inst = 0; inst < strings_length; ++inst) {
192 E : uint16_t opcode = strings[inst];
193 : const char* opcode_str =
194 E : reinterpret_cast<const char*>(GET_MNEMONIC_NAME(opcode));
195 :
196 : // Initialize the strings without prefix access hooks.
197 : std::string name =
198 : base::StringPrintf("asan_check_%d_byte_%s_access",
199 E : access_size, opcode_str);
200 E : name = base::ToLowerASCII(name);
201 : AddHookRef(name, AsanBasicBlockTransform::kInstrAccess, access_size,
202 E : opcode, true);
203 :
204 : // Initialize the strings with prefix access hooks.
205 : std::string repz_name = base::StringPrintf(
206 E : "asan_check_repz_%d_byte_%s_access", access_size, opcode_str);
207 E : name = base::ToLowerASCII(repz_name);
208 : AddHookRef(repz_name, AsanBasicBlockTransform::kRepzAccess, access_size,
209 E : opcode, true);
210 E : }
211 E : }
212 E : }
213 :
214 E : bool AddInstructionFromBuffer(const uint8* data, size_t length) {
215 E : EXPECT_NE(static_cast<const uint8*>(NULL), data);
216 E : EXPECT_GE(assm::kMaxInstructionLength, length);
217 :
218 E : block_graph::Instruction temp;
219 E : if (!block_graph::Instruction::FromBuffer(data, length, &temp))
220 i : return false;
221 :
222 : // Append this instruction to the basic block.
223 E : basic_block_->instructions().push_back(temp);
224 :
225 E : return true;
226 E : }
227 :
228 : // Some handy constants we'll use throughout the tests.
229 : // @{
230 : static const BasicBlock::Size kDataSize;
231 : static const uint8 kBlockData[];
232 : // @}
233 :
234 : protected:
235 : TestAsanTransform asan_transform_;
236 : HookMap hooks_check_access_ref_;
237 : std::map<HookMapEntryKey, BlockGraph::Block*> hooks_check_access_;
238 : BasicBlockSubGraph subgraph_;
239 : BasicCodeBlock* basic_block_;
240 : scoped_ptr<block_graph::BasicBlockAssembler> bb_asm_;
241 : base::FilePath relinked_path_;
242 : };
243 :
244 : const BasicBlock::Size AsanTransformTest::kDataSize = 32;
245 : const uint8 AsanTransformTest::kBlockData[AsanTransformTest::kDataSize] = {};
246 :
247 : // Dummy library name to test |set_instrument_dll_name|.
248 : const char kFooDll[] = "foo.dll";
249 :
250 : } // namespace
251 :
252 E : TEST_F(AsanTransformTest, SetAsanParameters) {
253 E : common::InflatedAsanParameters iparams;
254 E : common::InflatedAsanParameters* null = NULL;
255 E : common::InflatedAsanParameters* params = &iparams;
256 :
257 E : EXPECT_EQ(null, asan_transform_.asan_parameters());
258 E : asan_transform_.set_asan_parameters(params);
259 E : EXPECT_EQ(params, asan_transform_.asan_parameters());
260 E : asan_transform_.set_asan_parameters(NULL);
261 E : EXPECT_EQ(null, asan_transform_.asan_parameters());
262 E : }
263 :
264 E : TEST_F(AsanTransformTest, SetDryRunFlag) {
265 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
266 E : EXPECT_FALSE(bb_transform.dry_run());
267 E : bb_transform.set_dry_run(true);
268 E : EXPECT_TRUE(bb_transform.dry_run());
269 E : bb_transform.set_dry_run(false);
270 E : EXPECT_FALSE(bb_transform.dry_run());
271 E : }
272 :
273 E : TEST_F(AsanTransformTest, SetHotPatchingFlag) {
274 E : EXPECT_FALSE(asan_transform_.hot_patching());
275 E : asan_transform_.set_hot_patching(true);
276 E : EXPECT_TRUE(asan_transform_.hot_patching());
277 E : asan_transform_.set_hot_patching(false);
278 E : EXPECT_FALSE(asan_transform_.hot_patching());
279 E : }
280 :
281 E : TEST_F(AsanTransformTest, SetInstrumentDllName) {
282 E : EXPECT_EQ(AsanTransform::kSyzyAsanDll, asan_transform_.instrument_dll_name());
283 E : asan_transform_.set_instrument_dll_name(kFooDll);
284 E : EXPECT_EQ(kFooDll, asan_transform_.instrument_dll_name());
285 E : }
286 :
287 E : TEST_F(AsanTransformTest, SetInstrumentDllNameHotPatchingMode) {
288 : // The default dll name is different in hot patching mode.
289 E : asan_transform_.set_hot_patching(true);
290 : EXPECT_EQ(AsanTransform::kSyzyAsanHpDll,
291 E : asan_transform_.instrument_dll_name());
292 E : asan_transform_.set_instrument_dll_name(kFooDll);
293 E : EXPECT_EQ(kFooDll, asan_transform_.instrument_dll_name());
294 E : }
295 :
296 E : TEST_F(AsanTransformTest, GetInstrumentationHappenedFlag) {
297 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
298 E : EXPECT_FALSE(bb_transform.instrumentation_happened());
299 E : }
300 :
301 E : TEST_F(AsanTransformTest, SetInstrumentationRate) {
302 E : EXPECT_EQ(1.0, asan_transform_.instrumentation_rate());
303 E : asan_transform_.set_instrumentation_rate(1.2);
304 E : EXPECT_EQ(1.0, asan_transform_.instrumentation_rate());
305 E : asan_transform_.set_instrumentation_rate(-0.2);
306 E : EXPECT_EQ(0.0, asan_transform_.instrumentation_rate());
307 E : asan_transform_.set_instrumentation_rate(0.5);
308 E : EXPECT_EQ(0.5, asan_transform_.instrumentation_rate());;
309 :
310 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
311 E : EXPECT_EQ(1.0, bb_transform.instrumentation_rate());
312 E : bb_transform.set_instrumentation_rate(1.2);
313 E : EXPECT_EQ(1.0, bb_transform.instrumentation_rate());
314 E : bb_transform.set_instrumentation_rate(-0.2);
315 E : EXPECT_EQ(0.0, bb_transform.instrumentation_rate());
316 E : bb_transform.set_instrumentation_rate(0.5);
317 E : EXPECT_EQ(0.5, bb_transform.instrumentation_rate());
318 E : }
319 :
320 E : TEST_F(AsanTransformTest, SetInterceptCRTFuntionsFlag) {
321 E : EXPECT_FALSE(asan_transform_.use_interceptors());
322 E : asan_transform_.set_use_interceptors(true);
323 E : EXPECT_TRUE(asan_transform_.use_interceptors());
324 E : asan_transform_.set_use_interceptors(false);
325 E : EXPECT_FALSE(asan_transform_.use_interceptors());
326 E : }
327 :
328 E : TEST_F(AsanTransformTest, SetRemoveRedundantChecksFlag) {
329 E : EXPECT_FALSE(asan_transform_.remove_redundant_checks());
330 E : asan_transform_.set_remove_redundant_checks(true);
331 E : EXPECT_TRUE(asan_transform_.remove_redundant_checks());
332 E : asan_transform_.set_remove_redundant_checks(false);
333 E : EXPECT_FALSE(asan_transform_.remove_redundant_checks());
334 :
335 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
336 E : EXPECT_FALSE(bb_transform.remove_redundant_checks());
337 E : bb_transform.set_remove_redundant_checks(true);
338 E : EXPECT_TRUE(bb_transform.remove_redundant_checks());
339 E : bb_transform.set_remove_redundant_checks(false);
340 E : EXPECT_FALSE(bb_transform.remove_redundant_checks());
341 E : }
342 :
343 E : TEST_F(AsanTransformTest, SetUseLivenessFlag) {
344 E : EXPECT_FALSE(asan_transform_.use_liveness_analysis());
345 E : asan_transform_.set_use_liveness_analysis(true);
346 E : EXPECT_TRUE(asan_transform_.use_liveness_analysis());
347 E : asan_transform_.set_use_liveness_analysis(false);
348 E : EXPECT_FALSE(asan_transform_.use_liveness_analysis());
349 :
350 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
351 E : EXPECT_FALSE(bb_transform.use_liveness_analysis());
352 E : bb_transform.set_use_liveness_analysis(true);
353 E : EXPECT_TRUE(bb_transform.use_liveness_analysis());
354 E : bb_transform.set_use_liveness_analysis(false);
355 E : EXPECT_FALSE(bb_transform.use_liveness_analysis());
356 E : }
357 :
358 E : TEST_F(AsanTransformTest, ApplyAsanTransformPE) {
359 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
360 :
361 E : asan_transform_.use_interceptors_ = true;
362 : ASSERT_TRUE(block_graph::ApplyBlockGraphTransform(
363 E : &asan_transform_, policy_, &block_graph_, header_block_));
364 E : }
365 :
366 E : TEST_F(AsanTransformTest, ApplyAsanTransformCoff) {
367 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDllObj());
368 :
369 E : asan_transform_.use_interceptors_ = true;
370 : ASSERT_TRUE(block_graph::ApplyBlockGraphTransform(
371 E : &asan_transform_, policy_, &block_graph_, header_block_));
372 E : }
373 :
374 E : TEST_F(AsanTransformTest, InjectAsanHooksPe) {
375 : // Add a read access to the memory.
376 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ebx));
377 : // Add a write access to the memory.
378 E : bb_asm_->mov(block_graph::Operand(assm::ecx), assm::edx);
379 :
380 : // Add source ranges to the instruction.
381 E : block_graph::Instruction& i1 = *basic_block_->instructions().begin();
382 : Instruction::SourceRange source_range =
383 E : Instruction::SourceRange(RelativeAddress(1000), i1.size());
384 E : i1.set_source_range(source_range);
385 :
386 : // Instrument this basic block.
387 E : InitHooksRefs();
388 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
389 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
390 : basic_block_,
391 : AsanBasicBlockTransform::kSafeStackAccess,
392 E : BlockGraph::PE_IMAGE));
393 :
394 : // Ensure that the basic block is instrumented.
395 :
396 : // Check what the transform reports at first.
397 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
398 :
399 : // We had 2 instructions initially, and for each of them we add 3
400 : // instructions, so we expect to have 2 + 3 * 2 = 8 instructions.
401 E : ASSERT_EQ(basic_block_->instructions().size(), 8);
402 :
403 : // Walk through the instructions to ensure that the Asan hooks have been
404 : // injected.
405 : BasicBlock::Instructions::const_iterator iter_inst =
406 E : basic_block_->instructions().begin();
407 :
408 E : Instruction::SourceRange empty_source_range;
409 E : ASSERT_NE(empty_source_range, source_range);
410 :
411 : // First we check if the first memory access is instrumented as a 4 byte read
412 : // access. We also validate that the instrumentation has not had source range
413 : // information added.
414 E : ASSERT_EQ(empty_source_range, iter_inst->source_range());
415 E : ASSERT_EQ(I_PUSH, (iter_inst++)->representation().opcode);
416 E : ASSERT_EQ(empty_source_range, iter_inst->source_range());
417 E : ASSERT_EQ(I_LEA, (iter_inst++)->representation().opcode);
418 E : ASSERT_EQ(empty_source_range, iter_inst->source_range());
419 E : ASSERT_EQ(iter_inst->references().size(), 1);
420 : HookMapEntryKey check_4_byte_read_key =
421 E : { AsanBasicBlockTransform::kReadAccess, 4, 0, true };
422 : ASSERT_EQ(hooks_check_access_[check_4_byte_read_key],
423 E : iter_inst->references().begin()->second.block());
424 E : ASSERT_EQ(O_DISP, iter_inst->representation().ops[0].type);
425 E : ASSERT_EQ(I_CALL, (iter_inst++)->representation().opcode);
426 E : ASSERT_EQ(I_MOV, (iter_inst++)->representation().opcode);
427 :
428 : // Then we check if the second memory access is well instrumented as a 4 byte
429 : // write access.
430 E : ASSERT_EQ(I_PUSH, (iter_inst++)->representation().opcode);
431 E : ASSERT_EQ(I_LEA, (iter_inst++)->representation().opcode);
432 E : ASSERT_EQ(iter_inst->references().size(), 1);
433 : HookMapEntryKey check_4_byte_write_key =
434 E : { AsanBasicBlockTransform::kWriteAccess, 4, 0, true };
435 : ASSERT_EQ(hooks_check_access_[check_4_byte_write_key],
436 E : iter_inst->references().begin()->second.block());
437 E : ASSERT_EQ(I_CALL, (iter_inst++)->representation().opcode);
438 E : ASSERT_EQ(I_MOV, (iter_inst++)->representation().opcode);
439 :
440 E : ASSERT_TRUE(iter_inst == basic_block_->instructions().end());
441 E : }
442 :
443 E : TEST_F(AsanTransformTest, InjectAsanHooksWithSourceRangePe) {
444 : // Add a read access to the memory.
445 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ebx));
446 :
447 : // Add a source range to the instruction.
448 E : block_graph::Instruction& i1 = *basic_block_->instructions().begin();
449 : Instruction::SourceRange source_range =
450 E : Instruction::SourceRange(RelativeAddress(1000), i1.size());
451 E : i1.set_source_range(source_range);
452 :
453 : // Keep track of basic block size.
454 E : uint32 before_instructions_count = basic_block_->instructions().size();
455 :
456 : // Instrument this basic block.
457 E : InitHooksRefs();
458 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
459 E : bb_transform.set_debug_friendly(true);
460 :
461 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
462 : basic_block_,
463 : AsanBasicBlockTransform::kSafeStackAccess,
464 E : BlockGraph::PE_IMAGE));
465 :
466 : // Ensure this basic block is instrumented.
467 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
468 E : uint32 after_instructions_count = basic_block_->instructions().size();
469 E : ASSERT_LT(before_instructions_count, after_instructions_count);
470 :
471 : // Walk through the instructions and validate the source range.
472 : BasicBlock::Instructions::const_iterator iter_inst =
473 E : basic_block_->instructions().begin();
474 :
475 E : for ( ; iter_inst != basic_block_->instructions().end(); ++iter_inst)
476 E : EXPECT_EQ(source_range, iter_inst->source_range());
477 E : }
478 :
479 E : TEST_F(AsanTransformTest, InjectAsanHooksCoff) {
480 : // Add a read access to the memory.
481 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ebx));
482 : // Add a write access to the memory.
483 E : bb_asm_->mov(block_graph::Operand(assm::ecx), assm::edx);
484 :
485 : // Add source ranges to the instruction.
486 E : block_graph::Instruction& i1 = *basic_block_->instructions().begin();
487 : Instruction::SourceRange source_range =
488 E : Instruction::SourceRange(RelativeAddress(1000), i1.size());
489 E : i1.set_source_range(source_range);
490 :
491 : // Instrument this basic block.
492 E : InitHooksRefs();
493 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
494 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
495 : basic_block_,
496 : AsanBasicBlockTransform::kSafeStackAccess,
497 E : BlockGraph::COFF_IMAGE));
498 :
499 : // Ensure that the basic block is instrumented.
500 :
501 : // Check what the transform reports at first.
502 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
503 :
504 : // We had 2 instructions initially, and for each of them we add 3
505 : // instructions, so we expect to have 2 + 3 * 2 = 8 instructions.
506 E : ASSERT_EQ(basic_block_->instructions().size(), 8);
507 :
508 : // Walk through the instructions to ensure that the Asan hooks have been
509 : // injected.
510 : BasicBlock::Instructions::const_iterator iter_inst =
511 E : basic_block_->instructions().begin();
512 :
513 E : Instruction::SourceRange empty_source_range;
514 E : ASSERT_NE(empty_source_range, source_range);
515 :
516 : // First we check if the first memory access is instrumented as a 4 byte read
517 : // access. We also validate that the instrumentation has not had source range
518 : // information added.
519 E : ASSERT_EQ(empty_source_range, iter_inst->source_range());
520 E : ASSERT_EQ(I_PUSH, (iter_inst++)->representation().opcode);
521 E : ASSERT_EQ(empty_source_range, iter_inst->source_range());
522 E : ASSERT_EQ(I_LEA, (iter_inst++)->representation().opcode);
523 E : ASSERT_EQ(empty_source_range, iter_inst->source_range());
524 E : ASSERT_EQ(iter_inst->references().size(), 1);
525 : HookMapEntryKey check_4_byte_read_key =
526 E : { AsanBasicBlockTransform::kReadAccess, 4, 0, true };
527 : ASSERT_EQ(hooks_check_access_[check_4_byte_read_key],
528 E : iter_inst->references().begin()->second.block());
529 E : ASSERT_EQ(O_PC, iter_inst->representation().ops[0].type);
530 E : ASSERT_EQ(I_CALL, (iter_inst++)->representation().opcode);
531 E : ASSERT_EQ(I_MOV, (iter_inst++)->representation().opcode);
532 :
533 : // Then we check if the second memory access is well instrumented as a 4 byte
534 : // write access.
535 E : ASSERT_EQ(I_PUSH, (iter_inst++)->representation().opcode);
536 E : ASSERT_EQ(I_LEA, (iter_inst++)->representation().opcode);
537 E : ASSERT_EQ(iter_inst->references().size(), 1);
538 : HookMapEntryKey check_4_byte_write_key =
539 E : { AsanBasicBlockTransform::kWriteAccess, 4, 0, true };
540 : ASSERT_EQ(hooks_check_access_[check_4_byte_write_key],
541 E : iter_inst->references().begin()->second.block());
542 E : ASSERT_EQ(I_CALL, (iter_inst++)->representation().opcode);
543 E : ASSERT_EQ(I_MOV, (iter_inst++)->representation().opcode);
544 :
545 E : ASSERT_TRUE(iter_inst == basic_block_->instructions().end());
546 E : }
547 :
548 E : TEST_F(AsanTransformTest, InstrumentDifferentKindOfInstructions) {
549 E : uint32 instrumentable_instructions = 0;
550 :
551 : // Generate a bunch of instrumentable and non-instrumentable instructions.
552 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ebx));
553 E : instrumentable_instructions++;
554 E : bb_asm_->mov(block_graph::Operand(assm::ecx), assm::edx);
555 E : instrumentable_instructions++;
556 E : bb_asm_->call(block_graph::Operand(assm::ecx));
557 E : instrumentable_instructions++;
558 E : bb_asm_->jmp(block_graph::Operand(assm::ecx));
559 E : instrumentable_instructions++;
560 E : bb_asm_->push(block_graph::Operand(assm::eax));
561 E : instrumentable_instructions++;
562 :
563 : // Non-instrumentable.
564 E : bb_asm_->lea(assm::eax, block_graph::Operand(assm::ecx));
565 :
566 : uint32 expected_instructions_count = basic_block_->instructions().size()
567 E : + 3 * instrumentable_instructions;
568 : // Instrument this basic block.
569 E : InitHooksRefs();
570 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
571 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
572 : basic_block_,
573 : AsanBasicBlockTransform::kSafeStackAccess,
574 E : BlockGraph::PE_IMAGE));
575 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
576 E : ASSERT_EQ(basic_block_->instructions().size(), expected_instructions_count);
577 E : }
578 :
579 E : TEST_F(AsanTransformTest, InstrumentAndRemoveRedundantChecks) {
580 E : uint32 instrumentable_instructions = 0;
581 :
582 : // Generate a bunch of instrumentable and non instrumentable instructions.
583 : // We generate operand [ecx] multiple time as a redundant memory access.
584 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ecx));
585 E : instrumentable_instructions++;
586 E : bb_asm_->mov(block_graph::Operand(assm::ecx), assm::edx);
587 : // Validate that indirect call clear the memory state.
588 E : bb_asm_->call(block_graph::Operand(assm::ecx));
589 E : bb_asm_->push(block_graph::Operand(assm::eax));
590 E : instrumentable_instructions++;
591 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ecx));
592 E : instrumentable_instructions++;
593 E : bb_asm_->jmp(block_graph::Operand(assm::ecx));
594 :
595 : uint32 expected_instructions_count = basic_block_->instructions().size()
596 E : + 3 * instrumentable_instructions;
597 : // Instrument this basic block.
598 E : InitHooksRefs();
599 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
600 E : bb_transform.set_remove_redundant_checks(true);
601 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
602 : basic_block_,
603 : AsanBasicBlockTransform::kSafeStackAccess,
604 E : BlockGraph::PE_IMAGE));
605 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
606 E : ASSERT_EQ(basic_block_->instructions().size(), expected_instructions_count);
607 E : }
608 :
609 E : TEST_F(AsanTransformTest, NonInstrumentableStackBasedInstructions) {
610 : // DEC DWORD [EBP - 0x2830]
611 : static const uint8 kDec1[6] = { 0xff, 0x8d, 0xd0, 0xd7, 0xff, 0xff };
612 : // INC DWORD [EBP - 0x31c]
613 : static const uint8 kInc1[6] = { 0xff, 0x85, 0xe4, 0xfc, 0xff, 0xff };
614 : // INC DWORD [ESP + 0x1c]
615 : static const uint8 kInc2[4] = { 0xff, 0x44, 0x24, 0x1c };
616 : // NEG DWORD [EBP + 0x24]
617 : static const uint8 kNeg1[3] = { 0xf7, 0x5d, 0x24 };
618 : // FILD QWORD [EBP - 0x8]
619 : static const uint8 kFild1[3] = { 0xdf, 0x6d, 0xf8 };
620 : // FISTP QWORD [ESP + 0x28]
621 : static const uint8 kFistp1[4] = { 0xdf, 0x7c, 0x24, 0x28 };
622 : // MOV EDI, [EBP - 0x4]
623 : static const uint8 kMov1[3] = { 0x8b, 0x7d, 0xfc };
624 : // MOV EAX, [EBP - 0x104]
625 : static const uint8 kMov2[6] = { 0x8b, 0x85, 0xfc, 0xfe, 0xff, 0xff };
626 :
627 E : ASSERT_TRUE(AddInstructionFromBuffer(kDec1, sizeof(kDec1)));
628 E : ASSERT_TRUE(AddInstructionFromBuffer(kInc1, sizeof(kInc1)));
629 E : ASSERT_TRUE(AddInstructionFromBuffer(kInc2, sizeof(kInc2)));
630 E : ASSERT_TRUE(AddInstructionFromBuffer(kNeg1, sizeof(kNeg1)));
631 E : ASSERT_TRUE(AddInstructionFromBuffer(kFild1, sizeof(kFild1)));
632 E : ASSERT_TRUE(AddInstructionFromBuffer(kFistp1, sizeof(kFistp1)));
633 E : ASSERT_TRUE(AddInstructionFromBuffer(kMov1, sizeof(kMov1)));
634 E : ASSERT_TRUE(AddInstructionFromBuffer(kMov2, sizeof(kMov2)));
635 :
636 : // Keep track of the basic block size before Asan transform.
637 E : uint32 expected_basic_block_size = basic_block_->instructions().size();
638 :
639 : // Instrument this basic block.
640 E : InitHooksRefs();
641 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
642 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
643 : basic_block_,
644 : AsanBasicBlockTransform::kSafeStackAccess,
645 E : BlockGraph::PE_IMAGE));
646 :
647 : // Non-instrumentable instructions implies no change.
648 E : EXPECT_FALSE(bb_transform.instrumentation_happened());
649 E : EXPECT_EQ(expected_basic_block_size, basic_block_->instructions().size());
650 E : }
651 :
652 E : TEST_F(AsanTransformTest, InstrumentableStackBasedUnsafeInstructions) {
653 : // DEC DWORD [EBP - 0x2830]
654 : static const uint8 kDec1[6] = { 0xff, 0x8d, 0xd0, 0xd7, 0xff, 0xff };
655 :
656 E : ASSERT_TRUE(AddInstructionFromBuffer(kDec1, sizeof(kDec1)));
657 :
658 : // Keep track of the basic block size before Asan transform.
659 E : uint32 previous_basic_block_size = basic_block_->instructions().size();
660 :
661 : // Instrument this basic block considering invalid stack manipulation.
662 E : InitHooksRefs();
663 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
664 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
665 : basic_block_,
666 : AsanBasicBlockTransform::kUnsafeStackAccess,
667 E : BlockGraph::PE_IMAGE));
668 :
669 : // This instruction should have been instrumented, and we must observe
670 : // a increase in size.
671 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
672 E : EXPECT_LT(previous_basic_block_size, basic_block_->instructions().size());
673 E : }
674 :
675 E : TEST_F(AsanTransformTest, NonInstrumentableSegmentBasedInstructions) {
676 : // add eax, fs:[eax]
677 : static const uint8 kAdd1[3] = { 0x64, 0x03, 0x00 };
678 : // inc gs:[eax]
679 : static const uint8 kInc1[3] = { 0x65, 0xFE, 0x00 };
680 :
681 E : ASSERT_TRUE(AddInstructionFromBuffer(kAdd1, sizeof(kAdd1)));
682 E : ASSERT_TRUE(AddInstructionFromBuffer(kInc1, sizeof(kInc1)));
683 :
684 : // Keep track of the basic block size before Asan transform.
685 E : uint32 expected_basic_block_size = basic_block_->instructions().size();
686 :
687 : // Instrument this basic block.
688 E : InitHooksRefs();
689 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
690 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
691 : basic_block_,
692 : AsanBasicBlockTransform::kSafeStackAccess,
693 E : BlockGraph::PE_IMAGE));
694 :
695 : // Non-instrumentable instructions implies no change.
696 E : EXPECT_FALSE(bb_transform.instrumentation_happened());
697 E : EXPECT_EQ(expected_basic_block_size, basic_block_->instructions().size());
698 E : }
699 :
700 E : TEST_F(AsanTransformTest, FilteredInstructionsNotInstrumented) {
701 : // Add a read access to the memory.
702 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ebx));
703 : // Add a write access to the memory.
704 E : bb_asm_->mov(block_graph::Operand(assm::ecx), assm::edx);
705 :
706 : // Add a source range to the first instruction.
707 E : block_graph::Instruction& i1 = *basic_block_->instructions().begin();
708 : i1.set_source_range(Instruction::SourceRange(
709 E : RelativeAddress(1000), i1.size()));
710 :
711 : // Create a filter that blocks out that source range.
712 : RelativeAddressFilter filter(
713 E : RelativeAddressFilter::Range(RelativeAddress(0), 2000));
714 E : filter.Mark(RelativeAddressFilter::Range(RelativeAddress(995), 50));
715 :
716 : // Pass the filter to the BB transform.
717 E : InitHooksRefs();
718 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
719 E : bb_transform.set_filter(&filter);
720 :
721 : // Instrument this basic block.
722 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
723 : basic_block_,
724 : AsanBasicBlockTransform::kSafeStackAccess,
725 E : BlockGraph::PE_IMAGE));
726 :
727 : // Ensure that the basic block is instrumented, but only the second
728 : // instruction.
729 :
730 : // The transform should report changes.
731 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
732 :
733 : // We had 2 instructions initially. For the second one we add 3
734 : // instructions, so we expect to have 1 + (1 + 3) = 5 instructions.
735 E : ASSERT_EQ(basic_block_->instructions().size(), 5);
736 :
737 : // Walk through the instructions to ensure that the Asan hooks have been
738 : // injected.
739 : BasicBlock::Instructions::const_iterator iter_inst =
740 E : basic_block_->instructions().begin();
741 :
742 : // Ensure the first instruction is not instrumented at all.
743 E : ASSERT_TRUE((iter_inst++)->representation().opcode == I_MOV);
744 :
745 : // Then we check if the second memory access is well instrumented as a 4 byte
746 : // write access.
747 E : ASSERT_TRUE((iter_inst++)->representation().opcode == I_PUSH);
748 E : ASSERT_TRUE((iter_inst++)->representation().opcode == I_LEA);
749 E : ASSERT_EQ(iter_inst->references().size(), 1);
750 : HookMapEntryKey check_4_byte_write_key =
751 E : { AsanBasicBlockTransform::kWriteAccess, 4, 0, true };
752 : ASSERT_TRUE(iter_inst->references().begin()->second.block()
753 E : == hooks_check_access_[check_4_byte_write_key]);
754 E : ASSERT_TRUE((iter_inst++)->representation().opcode == I_CALL);
755 E : ASSERT_TRUE((iter_inst++)->representation().opcode == I_MOV);
756 :
757 E : ASSERT_TRUE(iter_inst == basic_block_->instructions().end());
758 E : }
759 :
760 E : TEST_F(AsanTransformTest, InstrumentableStringInstructions) {
761 : static const uint8 movsd[1] = { 0xA5 };
762 : static const uint8 movsw[2] = { 0x66, 0xA5 };
763 : static const uint8 movsb[1] = { 0xA4 };
764 :
765 : static const uint8 cmpsd[1] = { 0xA7 };
766 : static const uint8 cmpsw[2] = { 0x66, 0xA7 };
767 : static const uint8 cmpsb[1] = { 0xA6 };
768 :
769 : static const uint8 stosd[1] = { 0xAB };
770 : static const uint8 stosw[2] = { 0x66, 0xAB };
771 : static const uint8 stosb[1] = { 0xAA };
772 :
773 E : EXPECT_TRUE(AddInstructionFromBuffer(movsd, sizeof(movsd)));
774 E : EXPECT_TRUE(AddInstructionFromBuffer(movsw, sizeof(movsw)));
775 E : EXPECT_TRUE(AddInstructionFromBuffer(movsb, sizeof(movsb)));
776 E : EXPECT_TRUE(AddInstructionFromBuffer(cmpsd, sizeof(cmpsd)));
777 E : EXPECT_TRUE(AddInstructionFromBuffer(cmpsw, sizeof(cmpsw)));
778 E : EXPECT_TRUE(AddInstructionFromBuffer(cmpsb, sizeof(cmpsb)));
779 E : EXPECT_TRUE(AddInstructionFromBuffer(stosd, sizeof(stosd)));
780 E : EXPECT_TRUE(AddInstructionFromBuffer(stosw, sizeof(stosw)));
781 E : EXPECT_TRUE(AddInstructionFromBuffer(stosb, sizeof(stosb)));
782 :
783 : // Keep number of instrumentable instructions.
784 E : uint32 count_instructions = basic_block_->instructions().size();
785 :
786 : // Keep track of the basic block size before Asan transform.
787 E : uint32 basic_block_size = basic_block_->instructions().size();
788 :
789 : // Instrument this basic block.
790 E : InitHooksRefs();
791 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
792 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
793 : basic_block_,
794 : AsanBasicBlockTransform::kSafeStackAccess,
795 E : BlockGraph::PE_IMAGE));
796 :
797 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
798 :
799 : // Each instrumentable instructions implies 1 new instructions.
800 E : uint32 expected_basic_block_size = count_instructions + basic_block_size;
801 :
802 : // Validate basic block size.
803 E : ASSERT_EQ(basic_block_->instructions().size(), expected_basic_block_size);
804 E : }
805 :
806 E : TEST_F(AsanTransformTest, InstrumentableRepzStringInstructions) {
807 : static const uint8 movsd[2] = { 0xF3, 0xA5 };
808 : static const uint8 movsw[3] = { 0xF3, 0x66, 0xA5 };
809 : static const uint8 movsb[2] = { 0xF3, 0xA4 };
810 :
811 : static const uint8 cmpsd[2] = { 0xF3, 0xA7 };
812 : static const uint8 cmpsw[3] = { 0xF3, 0x66, 0xA7 };
813 : static const uint8 cmpsb[2] = { 0xF3, 0xA6 };
814 :
815 : static const uint8 stosd[2] = { 0xF3, 0xAB };
816 : static const uint8 stosw[3] = { 0xF3, 0x66, 0xAB };
817 : static const uint8 stosb[2] = { 0xF3, 0xAA };
818 :
819 E : EXPECT_TRUE(AddInstructionFromBuffer(movsd, sizeof(movsd)));
820 E : EXPECT_TRUE(AddInstructionFromBuffer(movsw, sizeof(movsw)));
821 E : EXPECT_TRUE(AddInstructionFromBuffer(movsb, sizeof(movsb)));
822 E : EXPECT_TRUE(AddInstructionFromBuffer(cmpsd, sizeof(cmpsd)));
823 E : EXPECT_TRUE(AddInstructionFromBuffer(cmpsw, sizeof(cmpsw)));
824 E : EXPECT_TRUE(AddInstructionFromBuffer(cmpsb, sizeof(cmpsb)));
825 E : EXPECT_TRUE(AddInstructionFromBuffer(stosd, sizeof(stosd)));
826 E : EXPECT_TRUE(AddInstructionFromBuffer(stosw, sizeof(stosw)));
827 E : EXPECT_TRUE(AddInstructionFromBuffer(stosb, sizeof(stosb)));
828 :
829 : // Keep number of instrumentable instructions.
830 E : uint32 count_instructions = basic_block_->instructions().size();
831 :
832 : // Keep track of the basic block size before Asan transform.
833 E : uint32 basic_block_size = basic_block_->instructions().size();
834 :
835 : // Instrument this basic block.
836 E : InitHooksRefs();
837 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
838 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
839 : basic_block_,
840 : AsanBasicBlockTransform::kSafeStackAccess,
841 E : BlockGraph::PE_IMAGE));
842 :
843 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
844 :
845 : // Each instrumentable instructions implies 1 new instructions.
846 E : uint32 expected_basic_block_size = count_instructions + basic_block_size;
847 :
848 : // Validate basic block size.
849 E : ASSERT_EQ(basic_block_->instructions().size(), expected_basic_block_size);
850 E : }
851 :
852 E : TEST_F(AsanTransformTest, DryRunInstrumentable) {
853 : // Generate an instrumentable instruction.
854 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ecx));
855 :
856 : // Keep track of the basic block size before Asan transform.
857 E : uint32 basic_block_size = basic_block_->instructions().size();
858 :
859 : // Instrument this basic block.
860 : // Note that InitHooksRefs() is not needed for a dry run.
861 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
862 E : bb_transform.set_dry_run(true);
863 :
864 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
865 : basic_block_,
866 : AsanBasicBlockTransform::kSafeStackAccess,
867 E : BlockGraph::PE_IMAGE));
868 :
869 : // The instructions_happened() function should return true because we
870 : // had an instruction to instrument.
871 E : EXPECT_TRUE(bb_transform.instrumentation_happened());
872 :
873 : // Yet, the basic block should not be touched.
874 E : ASSERT_EQ(basic_block_size, basic_block_->instructions().size());
875 E : }
876 :
877 E : TEST_F(AsanTransformTest, DryRunNonInstrumentable) {
878 : // Generate a non-instrumentable instruction.
879 E : bb_asm_->xchg(assm::eax, assm::ecx);
880 :
881 : // Keep track of the basic block size before Asan transform.
882 E : uint32 basic_block_size = basic_block_->instructions().size();
883 :
884 : // Instrument this basic block.
885 : // Note that InitHooksRefs() is not needed for a dry run.
886 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
887 E : bb_transform.set_dry_run(true);
888 :
889 : ASSERT_TRUE(bb_transform.InstrumentBasicBlock(
890 : basic_block_,
891 : AsanBasicBlockTransform::kSafeStackAccess,
892 E : BlockGraph::PE_IMAGE));
893 :
894 : // The instructions_happened() function should return false because we
895 : // had no instructions to instrument.
896 E : EXPECT_FALSE(bb_transform.instrumentation_happened());
897 :
898 : // The basic block should not be touched either.
899 E : ASSERT_EQ(basic_block_size, basic_block_->instructions().size());
900 E : }
901 :
902 E : TEST_F(AsanTransformTest, HotPatchingBBTransformInstrumentable) {
903 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
904 E : bb_transform.set_dry_run(true);
905 E : HotPatchingAsanBasicBlockTransform hp_bb_transform(&bb_transform);
906 :
907 : // Generate an instrumentable basic block.
908 E : bb_asm_->xchg(assm::eax, assm::ecx);
909 E : bb_asm_->mov(assm::eax, block_graph::Operand(assm::ebx));
910 :
911 : // Check subgraph before transformation.
912 E : EXPECT_EQ(2U, basic_block_->instructions().size());
913 E : ASSERT_EQ(1U, subgraph_.block_descriptions().size());
914 E : EXPECT_EQ(0U, subgraph_.block_descriptions().front().padding_before);
915 E : EXPECT_FALSE(hp_bb_transform.prepared_for_hot_patching());
916 :
917 : // Apply the Asan hot patching basic block transform.
918 : ASSERT_TRUE(hp_bb_transform.TransformBasicBlockSubGraph(
919 E : &pe_policy_, &block_graph_, &subgraph_));
920 :
921 : // Padding should be added in the block description. Also, as the code block
922 : // began with a 1-byte instruction, a 2-byte NOP should be prepended.
923 E : EXPECT_EQ(3U, basic_block_->instructions().size());
924 E : ASSERT_EQ(1U, subgraph_.block_descriptions().size());
925 E : EXPECT_EQ(5U, subgraph_.block_descriptions().front().padding_before);
926 E : EXPECT_TRUE(hp_bb_transform.prepared_for_hot_patching());
927 E : }
928 :
929 E : TEST_F(AsanTransformTest, HotPatchingBBTransformNonInstrumentable) {
930 E : TestAsanBasicBlockTransform bb_transform(&hooks_check_access_ref_);
931 E : bb_transform.set_dry_run(true);
932 E : HotPatchingAsanBasicBlockTransform hp_bb_transform(&bb_transform);
933 :
934 : // Generate a non-instrumentable instruction.
935 E : bb_asm_->xchg(assm::eax, assm::ecx);
936 :
937 : // Check subgraph before transformation.
938 E : EXPECT_EQ(1U, basic_block_->instructions().size());
939 E : ASSERT_EQ(1U, subgraph_.block_descriptions().size());
940 E : EXPECT_EQ(0U, subgraph_.block_descriptions().front().padding_before);
941 E : EXPECT_FALSE(hp_bb_transform.prepared_for_hot_patching());
942 :
943 : // Apply the Asan hot patching basic block transform.
944 : ASSERT_TRUE(hp_bb_transform.TransformBasicBlockSubGraph(
945 E : &pe_policy_, &block_graph_, &subgraph_));
946 :
947 : // The subgraph should stay the same.
948 E : EXPECT_EQ(1U, basic_block_->instructions().size());
949 E : ASSERT_EQ(1U, subgraph_.block_descriptions().size());
950 E : EXPECT_EQ(0U, subgraph_.block_descriptions().front().padding_before);
951 E : EXPECT_FALSE(hp_bb_transform.prepared_for_hot_patching());
952 E : }
953 :
954 : namespace {
955 :
956 : using base::win::PEImage;
957 : typedef std::set<std::string> StringSet;
958 : typedef std::set<void*> FunctionsIATAddressSet;
959 : typedef std::vector<std::string> StringVector;
960 :
961 E : void Intersect(const StringSet& ss1, const StringSet& ss2, StringSet* ss3) {
962 E : ASSERT_TRUE(ss3 != NULL);
963 E : ss3->clear();
964 : std::set_intersection(ss1.begin(), ss1.end(),
965 : ss2.begin(), ss2.end(),
966 E : std::inserter(*ss3, ss3->begin()));
967 E : }
968 :
969 : bool EnumKernel32HeapImports(const PEImage &image,
970 : const char* module,
971 : unsigned long ordinal,
972 : const char* name,
973 : unsigned long hint,
974 : PIMAGE_THUNK_DATA iat,
975 E : void* cookie) {
976 E : EXPECT_NE(static_cast<const char*>(NULL), module);
977 E : EXPECT_NE(static_cast<void*>(NULL), cookie);
978 :
979 E : StringVector* modules = reinterpret_cast<StringVector*>(cookie);
980 :
981 E : if (_stricmp("kernel32.dll", module) == 0 && strncmp("Heap", name, 4) == 0) {
982 E : EXPECT_NE(static_cast<const char*>(NULL), name);
983 E : modules->push_back(name);
984 : }
985 :
986 E : return true;
987 E : }
988 :
989 : bool EnumKernel32InterceptedFunctionsImports(const PEImage &image,
990 : const char* module,
991 : unsigned long ordinal,
992 : const char* name,
993 : unsigned long hint,
994 : PIMAGE_THUNK_DATA iat,
995 E : void* cookie) {
996 E : EXPECT_NE(static_cast<const char*>(NULL), module);
997 E : EXPECT_NE(static_cast<void*>(NULL), cookie);
998 :
999 E : StringVector* modules = reinterpret_cast<StringVector*>(cookie);
1000 : static const char* kInterceptedFunctions[] = {
1001 : "ReadFile",
1002 : "WriteFile",
1003 : };
1004 :
1005 E : if (_stricmp("kernel32.dll", module) == 0) {
1006 E : for (size_t i = 0; i < arraysize(kInterceptedFunctions); ++i) {
1007 : if (base::CompareCaseInsensitiveASCII(kInterceptedFunctions[i], name) ==
1008 E : 0) {
1009 E : EXPECT_NE(static_cast<const char*>(NULL), name);
1010 E : modules->push_back(name);
1011 E : return true;
1012 : }
1013 E : }
1014 : }
1015 :
1016 E : return true;
1017 E : }
1018 :
1019 : // A struct used to pass parameters in the cookie of EnumAsanImports
1020 : struct EnumAsanImportsParams {
1021 : const char* imported_module_name;
1022 : StringSet* imports;
1023 : };
1024 :
1025 : bool EnumAsanImports(const PEImage &image,
1026 : const char* module,
1027 : unsigned long ordinal,
1028 : const char* name,
1029 : unsigned long hint,
1030 : PIMAGE_THUNK_DATA iat,
1031 E : void* cookie) {
1032 E : EXPECT_NE(static_cast<const char*>(NULL), module);
1033 E : EXPECT_NE(static_cast<void*>(NULL), cookie);
1034 :
1035 : EnumAsanImportsParams* params =
1036 E : reinterpret_cast<EnumAsanImportsParams*>(cookie);
1037 :
1038 E : if (strcmp(params->imported_module_name, module) == 0) {
1039 E : EXPECT_NE(static_cast<const char*>(NULL), name);
1040 E : params->imports->insert(name);
1041 : }
1042 :
1043 E : return true;
1044 E : }
1045 :
1046 : bool GetAsanHooksIATEntries(const PEImage &image,
1047 : const char* module,
1048 : unsigned long ordinal,
1049 : const char* name,
1050 : unsigned long hint,
1051 : PIMAGE_THUNK_DATA iat,
1052 E : void* cookie) {
1053 E : EXPECT_NE(static_cast<const char*>(NULL), module);
1054 E : EXPECT_NE(static_cast<void*>(NULL), cookie);
1055 :
1056 : FunctionsIATAddressSet* hooks_iat_entries =
1057 E : reinterpret_cast<FunctionsIATAddressSet*>(cookie);
1058 :
1059 E : if (strcmp(AsanTransform::kSyzyAsanDll, module) != 0)
1060 E : return true;
1061 :
1062 E : EXPECT_NE(static_cast<const char*>(NULL), name);
1063 :
1064 : // Ensures that the function is an asan_check_access hook.
1065 E : if (base::StartsWith(name, "asan_check_", base::CompareCase::SENSITIVE))
1066 E : hooks_iat_entries->insert(reinterpret_cast<PVOID>(iat->u1.Function));
1067 :
1068 E : return true;
1069 E : }
1070 :
1071 : void CheckImportsAreRedirectedPe(
1072 : const base::FilePath::StringType& library_path,
1073 E : bool hot_patching) {
1074 :
1075 : // Load the transformed module without resolving its dependencies.
1076 : base::NativeLibrary lib =
1077 : ::LoadLibraryEx(library_path.c_str(),
1078 : NULL,
1079 E : DONT_RESOLVE_DLL_REFERENCES);
1080 E : ASSERT_TRUE(lib != NULL);
1081 : // Make sure it's unloaded on failure.
1082 E : base::ScopedNativeLibrary lib_keeper(lib);
1083 :
1084 E : PEImage image(lib);
1085 E : ASSERT_TRUE(image.VerifyMagic());
1086 E : StringSet imports;
1087 : EnumAsanImportsParams enum_asan_imports_params;
1088 E : if (!hot_patching) {
1089 E : enum_asan_imports_params.imported_module_name = AsanTransform::kSyzyAsanDll;
1090 E : } else {
1091 : enum_asan_imports_params.imported_module_name =
1092 E : AsanTransform::kSyzyAsanHpDll;
1093 : }
1094 E : enum_asan_imports_params.imports = &imports;
1095 : ASSERT_TRUE(image.EnumAllImports(&EnumAsanImports,
1096 E : &enum_asan_imports_params));
1097 :
1098 E : StringVector heap_imports;
1099 E : ASSERT_TRUE(image.EnumAllImports(&EnumKernel32HeapImports, &heap_imports));
1100 E : StringVector intercepted_functions_imports;
1101 : ASSERT_TRUE(image.EnumAllImports(&EnumKernel32InterceptedFunctionsImports,
1102 E : &intercepted_functions_imports));
1103 :
1104 : // This isn't strictly speaking a full test, as we only check that the new
1105 : // imports have been added. It's however more trouble than it's worth to
1106 : // test this fully for now.
1107 E : StringSet expected;
1108 E : for (size_t i = 0; i < heap_imports.size(); ++i) {
1109 E : std::string asan_import = "asan_";
1110 E : asan_import.append(heap_imports[i]);
1111 E : expected.insert(asan_import);
1112 E : }
1113 E : for (size_t i = 0; i < intercepted_functions_imports.size(); ++i) {
1114 E : std::string asan_import = "asan_";
1115 E : asan_import.append(intercepted_functions_imports[i]);
1116 E : expected.insert(asan_import);
1117 E : }
1118 :
1119 : // Imports that should be redirected should all have matching asan imports.
1120 E : StringSet results;
1121 E : Intersect(imports, expected, &results);
1122 E : if (!hot_patching) {
1123 E : EXPECT_EQ(expected, results);
1124 E : } else {
1125 : // These should not be present in hot patching mode.
1126 E : EXPECT_TRUE(results.empty());
1127 : }
1128 :
1129 : // Some instrumentation functions (but not necessarily all of them) should be
1130 : // found, unless we are in hot patching mode.
1131 E : expected.clear();
1132 E : expected.insert("asan_check_1_byte_read_access");
1133 E : expected.insert("asan_check_2_byte_read_access");
1134 E : expected.insert("asan_check_4_byte_read_access");
1135 E : expected.insert("asan_check_8_byte_read_access");
1136 E : expected.insert("asan_check_10_byte_read_access");
1137 E : expected.insert("asan_check_16_byte_read_access");
1138 E : expected.insert("asan_check_32_byte_read_access");
1139 E : expected.insert("asan_check_1_byte_write_access");
1140 E : expected.insert("asan_check_2_byte_write_access");
1141 E : expected.insert("asan_check_4_byte_write_access");
1142 E : expected.insert("asan_check_8_byte_write_access");
1143 E : expected.insert("asan_check_10_byte_write_access");
1144 E : expected.insert("asan_check_16_byte_write_access");
1145 E : expected.insert("asan_check_32_byte_write_access");
1146 :
1147 E : expected.insert("asan_check_1_byte_read_access_no_flags");
1148 E : expected.insert("asan_check_2_byte_read_access_no_flags");
1149 E : expected.insert("asan_check_4_byte_read_access_no_flags");
1150 E : expected.insert("asan_check_8_byte_read_access_no_flags");
1151 E : expected.insert("asan_check_10_byte_read_access_no_flags");
1152 E : expected.insert("asan_check_16_byte_read_access_no_flags");
1153 E : expected.insert("asan_check_32_byte_read_access_no_flags");
1154 E : expected.insert("asan_check_1_byte_write_access_no_flags");
1155 E : expected.insert("asan_check_2_byte_write_access_no_flags");
1156 E : expected.insert("asan_check_4_byte_write_access_no_flags");
1157 E : expected.insert("asan_check_8_byte_write_access_no_flags");
1158 E : expected.insert("asan_check_10_byte_write_access_no_flags");
1159 E : expected.insert("asan_check_16_byte_write_access_no_flags");
1160 E : expected.insert("asan_check_32_byte_write_access_no_flags");
1161 :
1162 E : expected.insert("asan_check_repz_4_byte_cmps_access");
1163 E : expected.insert("asan_check_repz_4_byte_movs_access");
1164 E : expected.insert("asan_check_repz_4_byte_stos_access");
1165 E : expected.insert("asan_check_repz_2_byte_cmps_access");
1166 E : expected.insert("asan_check_repz_2_byte_movs_access");
1167 E : expected.insert("asan_check_repz_2_byte_stos_access");
1168 E : expected.insert("asan_check_repz_1_byte_cmps_access");
1169 E : expected.insert("asan_check_repz_1_byte_movs_access");
1170 E : expected.insert("asan_check_repz_1_byte_stos_access");
1171 :
1172 E : expected.insert("asan_check_4_byte_cmps_access");
1173 E : expected.insert("asan_check_4_byte_movs_access");
1174 E : expected.insert("asan_check_4_byte_stos_access");
1175 E : expected.insert("asan_check_2_byte_cmps_access");
1176 E : expected.insert("asan_check_2_byte_movs_access");
1177 E : expected.insert("asan_check_2_byte_stos_access");
1178 E : expected.insert("asan_check_1_byte_cmps_access");
1179 E : expected.insert("asan_check_1_byte_movs_access");
1180 E : expected.insert("asan_check_1_byte_stos_access");
1181 :
1182 : // We expect all of the instrumentation functions to have been added.
1183 E : Intersect(imports, expected, &results);
1184 E : if (!hot_patching) {
1185 E : EXPECT_EQ(expected, results);
1186 E : } else {
1187 : // These should not be present in hot patching mode.
1188 E : EXPECT_TRUE(results.empty());
1189 : }
1190 :
1191 : // Hot patching mode uses a different prefix for static CRT intercepts.
1192 E : std::string prefix = !hot_patching ? "asan_" : "hp_asan_";
1193 :
1194 : // We expect all of these statically linked CRT functions to be redirected.
1195 E : expected.clear();
1196 E : expected.insert(prefix + "memcpy");
1197 E : expected.insert(prefix + "memmove");
1198 E : expected.insert(prefix + "memset");
1199 E : expected.insert(prefix + "memchr");
1200 E : expected.insert(prefix + "strlen");
1201 E : expected.insert(prefix + "strrchr");
1202 E : expected.insert(prefix + "strncpy");
1203 E : expected.insert(prefix + "strncat");
1204 E : expected.insert(prefix + "wcsrchr");
1205 E : expected.insert(prefix + "wcschr");
1206 E : expected.insert(prefix + "wcsstr");
1207 E : Intersect(imports, expected, &results);
1208 E : EXPECT_FALSE(results.empty());
1209 E : EXPECT_EQ(results, expected);
1210 :
1211 : // The implementation of the interceptors for these functions isn't available
1212 : // so we don't expect them to be redirected.
1213 E : StringSet not_expected;
1214 E : not_expected.insert(prefix + "strcmp");
1215 E : not_expected.insert(prefix + "strcspn");
1216 E : not_expected.insert(prefix + "strspn");
1217 E : not_expected.insert(prefix + "strstr");
1218 E : not_expected.insert(prefix + "strpbrk");
1219 E : Intersect(imports, not_expected, &results);
1220 E : EXPECT_TRUE(results.empty());
1221 E : }
1222 :
1223 : } // namespace
1224 :
1225 E : TEST_F(AsanTransformTest, ImportsAreRedirectedPe) {
1226 E : ASSERT_NO_FATAL_FAILURE(ApplyTransformToIntegrationTestDll());
1227 :
1228 E : CheckImportsAreRedirectedPe(relinked_path_.value(), false);
1229 E : }
1230 :
1231 E : TEST_F(AsanTransformTest, ImportsAreRedirectedHpPe) {
1232 E : asan_transform_.set_hot_patching(true);
1233 E : ASSERT_NO_FATAL_FAILURE(ApplyTransformToIntegrationTestDll());
1234 :
1235 E : CheckImportsAreRedirectedPe(relinked_path_.value(), true);
1236 E : }
1237 :
1238 : namespace {
1239 :
1240 : // Counts the number of references to the given COFF symbol.
1241 : size_t CountCoffSymbolReferences(const BlockGraph::Block* symbols_block,
1242 : const pe::CoffSymbolNameOffsetMap& symbol_map,
1243 E : const base::StringPiece& name) {
1244 E : EXPECT_NE(reinterpret_cast<BlockGraph::Block*>(NULL), symbols_block);
1245 :
1246 : pe::CoffSymbolNameOffsetMap::const_iterator symbol_it =
1247 E : symbol_map.find(name.as_string());
1248 E : if (symbol_it == symbol_map.end())
1249 i : return 0;
1250 :
1251 E : size_t ref_count = 0;
1252 E : const pe::CoffSymbolOffsets& offsets = symbol_it->second;
1253 : BlockGraph::Block::ReferrerSet::const_iterator ref_it =
1254 E : symbols_block->referrers().begin();
1255 E : for (; ref_it != symbols_block->referrers().end(); ++ref_it) {
1256 E : BlockGraph::Reference ref;
1257 E : CHECK(ref_it->first->GetReference(ref_it->second, &ref));
1258 E : if (offsets.count(ref.offset()) > 0)
1259 E : ++ref_count;
1260 E : }
1261 :
1262 E : return ref_count;
1263 E : }
1264 :
1265 : } // namespace
1266 :
1267 E : TEST_F(AsanTransformTest, ImportsAreRedirectedCoff) {
1268 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDllObj());
1269 :
1270 : // TODO(chrisha): Modify this to use CoffTransformPolicy once it is
1271 : // working as intended.
1272 E : testing::DummyTransformPolicy dummy_policy;
1273 E : asan_transform_.use_interceptors_ = true;
1274 E : asan_transform_.use_liveness_analysis_ = true;
1275 : ASSERT_TRUE(block_graph::ApplyBlockGraphTransform(
1276 E : &asan_transform_, &dummy_policy, &block_graph_, header_block_));
1277 :
1278 E : BlockGraph::Block* symbols_block = NULL;
1279 E : BlockGraph::Block* strings_block = NULL;
1280 : ASSERT_TRUE(pe::FindCoffSpecialBlocks(
1281 E : &block_graph_, NULL, &symbols_block, &strings_block));
1282 E : pe::CoffSymbolNameOffsetMap symbol_map;
1283 : ASSERT_TRUE(pe::BuildCoffSymbolNameOffsetMap(
1284 E : symbols_block, strings_block, &symbol_map));
1285 :
1286 : // Convert the symbol map to a set of symbol names.
1287 E : StringSet symbols;
1288 E : pe::CoffSymbolNameOffsetMap::const_iterator map_it = symbol_map.begin();
1289 E : for (; map_it != symbol_map.end(); ++map_it)
1290 E : symbols.insert(map_it->first);
1291 :
1292 : // We expected the following check-access functions to have been
1293 : // added.
1294 E : StringSet expected;
1295 E : expected.insert("_asan_check_1_byte_read_access");
1296 E : expected.insert("_asan_check_2_byte_read_access");
1297 E : expected.insert("_asan_check_4_byte_read_access");
1298 E : expected.insert("_asan_check_8_byte_read_access");
1299 E : expected.insert("_asan_check_10_byte_read_access");
1300 E : expected.insert("_asan_check_16_byte_read_access");
1301 E : expected.insert("_asan_check_32_byte_read_access");
1302 E : expected.insert("_asan_check_1_byte_write_access");
1303 E : expected.insert("_asan_check_2_byte_write_access");
1304 E : expected.insert("_asan_check_4_byte_write_access");
1305 E : expected.insert("_asan_check_8_byte_write_access");
1306 E : expected.insert("_asan_check_10_byte_write_access");
1307 E : expected.insert("_asan_check_16_byte_write_access");
1308 E : expected.insert("_asan_check_32_byte_write_access");
1309 :
1310 E : expected.insert("_asan_check_1_byte_read_access_no_flags");
1311 E : expected.insert("_asan_check_2_byte_read_access_no_flags");
1312 E : expected.insert("_asan_check_4_byte_read_access_no_flags");
1313 E : expected.insert("_asan_check_8_byte_read_access_no_flags");
1314 E : expected.insert("_asan_check_10_byte_read_access_no_flags");
1315 E : expected.insert("_asan_check_16_byte_read_access_no_flags");
1316 E : expected.insert("_asan_check_32_byte_read_access_no_flags");
1317 E : expected.insert("_asan_check_1_byte_write_access_no_flags");
1318 E : expected.insert("_asan_check_2_byte_write_access_no_flags");
1319 E : expected.insert("_asan_check_4_byte_write_access_no_flags");
1320 E : expected.insert("_asan_check_8_byte_write_access_no_flags");
1321 E : expected.insert("_asan_check_10_byte_write_access_no_flags");
1322 E : expected.insert("_asan_check_16_byte_write_access_no_flags");
1323 E : expected.insert("_asan_check_32_byte_write_access_no_flags");
1324 :
1325 E : expected.insert("_asan_check_repz_4_byte_cmps_access");
1326 E : expected.insert("_asan_check_repz_4_byte_movs_access");
1327 E : expected.insert("_asan_check_repz_4_byte_stos_access");
1328 E : expected.insert("_asan_check_repz_2_byte_cmps_access");
1329 E : expected.insert("_asan_check_repz_2_byte_movs_access");
1330 E : expected.insert("_asan_check_repz_2_byte_stos_access");
1331 E : expected.insert("_asan_check_repz_1_byte_cmps_access");
1332 E : expected.insert("_asan_check_repz_1_byte_movs_access");
1333 E : expected.insert("_asan_check_repz_1_byte_stos_access");
1334 :
1335 E : expected.insert("_asan_check_4_byte_cmps_access");
1336 E : expected.insert("_asan_check_4_byte_movs_access");
1337 E : expected.insert("_asan_check_4_byte_stos_access");
1338 E : expected.insert("_asan_check_2_byte_cmps_access");
1339 E : expected.insert("_asan_check_2_byte_movs_access");
1340 E : expected.insert("_asan_check_2_byte_stos_access");
1341 E : expected.insert("_asan_check_1_byte_cmps_access");
1342 E : expected.insert("_asan_check_1_byte_movs_access");
1343 E : expected.insert("_asan_check_1_byte_stos_access");
1344 :
1345 E : StringSet results;
1346 E : Intersect(symbols, expected, &results);
1347 E : EXPECT_THAT(results, ContainerEq(expected));
1348 :
1349 : // Expect at least some of the Asan instrumentation symbols to be referenced.
1350 E : size_t instrumentation_references = 0;
1351 E : StringSet::const_iterator str_it = expected.begin();
1352 E : for (; str_it != expected.end(); ++str_it) {
1353 : instrumentation_references += CountCoffSymbolReferences(
1354 E : symbols_block, symbol_map, *str_it);
1355 E : }
1356 E : EXPECT_LT(0u, instrumentation_references);
1357 :
1358 : // Expect any intercepted symbols to have no references to them if they
1359 : // are present, and expect an equivalent Asan instrumented symbol to exist
1360 : // and be referenced.
1361 E : const AsanIntercept* intercept = kAsanIntercepts;
1362 E : for (; intercept->undecorated_name != NULL; ++intercept) {
1363 E : if (intercept->decorated_name == NULL)
1364 E : continue;
1365 :
1366 E : std::string name(intercept->decorated_name);
1367 :
1368 : // Build the name of the imported version of this symbol.
1369 E : std::string imp_name(kDecoratedImportPrefix);
1370 E : imp_name += name;
1371 :
1372 : // Build the name of the Asan instrumented version of this symbol.
1373 E : std::string asan_name(kDecoratedAsanInterceptPrefix);
1374 E : asan_name += name;
1375 :
1376 : // Build the name of the Asan instrumented imported version of this symbol.
1377 E : std::string imp_asan_name(kDecoratedImportPrefix);
1378 E : imp_asan_name += name;
1379 :
1380 E : bool has_name = symbols.count(name) > 0;
1381 E : bool has_imp_name = symbols.count(imp_name) > 0;
1382 E : bool has_asan_name = symbols.count(asan_name) > 0;
1383 E : bool has_imp_asan_name = symbols.count(imp_asan_name) > 0;
1384 :
1385 E : size_t name_refs = 0;
1386 E : if (has_name) {
1387 : name_refs = CountCoffSymbolReferences(
1388 E : symbols_block, symbol_map, name);
1389 : }
1390 :
1391 E : size_t imp_name_refs = 0;
1392 E : if (has_imp_name) {
1393 : imp_name_refs = CountCoffSymbolReferences(
1394 i : symbols_block, symbol_map, imp_name);
1395 : }
1396 :
1397 E : size_t asan_name_refs = 0;
1398 E : if (has_asan_name) {
1399 : asan_name_refs = CountCoffSymbolReferences(
1400 E : symbols_block, symbol_map, asan_name);
1401 : }
1402 :
1403 E : size_t imp_asan_name_refs = 0;
1404 E : if (has_imp_asan_name) {
1405 : imp_asan_name_refs = CountCoffSymbolReferences(
1406 i : symbols_block, symbol_map, imp_asan_name);
1407 : }
1408 :
1409 : // If the original symbol is present we expect the Asan version to be
1410 : // present as well. The converse it not necessarily true, as the symbol
1411 : // can be reused in place by the transform in some cases. We also expect
1412 : // them to have no references (having been redirected to the Asan
1413 : // equivalents).
1414 E : if (has_name) {
1415 E : EXPECT_TRUE(has_asan_name);
1416 E : EXPECT_EQ(0u, name_refs);
1417 : }
1418 E : if (has_imp_name) {
1419 i : EXPECT_TRUE(has_imp_asan_name);
1420 i : EXPECT_EQ(0u, imp_name_refs);
1421 : }
1422 :
1423 : // If the Asan versions of the symbols are present we expect them to
1424 : // have references.
1425 E : if (has_asan_name) {
1426 E : EXPECT_LT(0u, asan_name_refs);
1427 : }
1428 E : if (has_imp_asan_name) {
1429 i : EXPECT_LT(0u, imp_asan_name_refs);
1430 : }
1431 E : }
1432 E : }
1433 :
1434 E : TEST_F(AsanTransformTest, AsanHooksAreStubbed) {
1435 E : ASSERT_NO_FATAL_FAILURE(ApplyTransformToIntegrationTestDll());
1436 :
1437 : // Load the transformed module without resolving its dependencies.
1438 : base::NativeLibrary lib =
1439 : ::LoadLibraryEx(relinked_path_.value().c_str(),
1440 : NULL,
1441 E : DONT_RESOLVE_DLL_REFERENCES);
1442 E : ASSERT_TRUE(lib != NULL);
1443 : // Make sure it's unloaded on failure.
1444 E : base::ScopedNativeLibrary lib_keeper(lib);
1445 :
1446 E : PEImage image(lib);
1447 E : ASSERT_TRUE(image.VerifyMagic());
1448 :
1449 : // Iterate over the image import descriptors. We want to make sure the
1450 : // one for syzyasan_rtl.dll is bound.
1451 E : DWORD size = image.GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_IMPORT);
1452 E : PIMAGE_IMPORT_DESCRIPTOR iid = image.GetFirstImportChunk();
1453 E : ASSERT_TRUE(iid != NULL);
1454 E : ASSERT_GE(size, sizeof(IMAGE_IMPORT_DESCRIPTOR));
1455 E : for (; iid->FirstThunk; ++iid) {
1456 : std::string module_name(reinterpret_cast<LPCSTR>(
1457 E : image.RVAToAddr(iid->Name)));
1458 E : if (module_name == AsanTransform::kSyzyAsanDll)
1459 E : ASSERT_NE(0u, iid->TimeDateStamp);
1460 E : }
1461 :
1462 : // As all the hooks may refer to only two kinds of stubs, we expect to have
1463 : // exactly two entries in the set.
1464 E : FunctionsIATAddressSet hooks_iat_set;
1465 E : ASSERT_TRUE(image.EnumAllImports(&GetAsanHooksIATEntries, &hooks_iat_set));
1466 E : ASSERT_EQ(hooks_iat_set.size(), 2U);
1467 :
1468 : // Ensures that all stubs are in the thunks section.
1469 E : FunctionsIATAddressSet::iterator hook = hooks_iat_set.begin();
1470 E : for (; hook != hooks_iat_set.end(); ++hook) {
1471 E : PVOID stub_address = *hook;
1472 : PIMAGE_SECTION_HEADER stub_sec =
1473 E : image.GetImageSectionFromAddr(stub_address);
1474 : ASSERT_STREQ(common::kThunkSectionName,
1475 E : reinterpret_cast<const char*>(stub_sec->Name));
1476 E : }
1477 E : }
1478 :
1479 E : TEST_F(AsanTransformTest, PeInterceptFunctions) {
1480 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
1481 :
1482 : BlockGraph::Block* b1 =
1483 E : block_graph_.AddBlock(BlockGraph::CODE_BLOCK, 0x20, "testAsan_b1");
1484 : BlockGraph::Block* b2 =
1485 E : block_graph_.AddBlock(BlockGraph::CODE_BLOCK, 0x20, "testAsan_b2");
1486 : BlockGraph::Block* b3 =
1487 E : block_graph_.AddBlock(BlockGraph::CODE_BLOCK, 0x20, "testAsan_b3");
1488 E : ASSERT_TRUE(b1 != NULL);
1489 E : ASSERT_TRUE(b2 != NULL);
1490 E : ASSERT_TRUE(b3 != NULL);
1491 :
1492 E : ASSERT_TRUE(b1->references().empty());
1493 E : ASSERT_TRUE(b1->referrers().empty());
1494 E : ASSERT_TRUE(b2->references().empty());
1495 E : ASSERT_TRUE(b2->referrers().empty());
1496 E : ASSERT_TRUE(b3->references().empty());
1497 E : ASSERT_TRUE(b3->referrers().empty());
1498 :
1499 : // Add a reference from b2 to b1 and from b3 to b1.
1500 E : BlockGraph::Reference ref_b2_b1(BlockGraph::PC_RELATIVE_REF, 1, b1, 0, 0);
1501 E : BlockGraph::Reference ref_b3_b1(BlockGraph::PC_RELATIVE_REF, 1, b1, 1, 1);
1502 E : ASSERT_TRUE(b2->SetReference(0, ref_b2_b1));
1503 E : ASSERT_TRUE(b3->SetReference(1, ref_b3_b1));
1504 :
1505 E : EXPECT_EQ(2U, b1->referrers().size());
1506 :
1507 E : size_t num_blocks_pre_transform = block_graph_.blocks().size();
1508 E : size_t num_sections_pre_transform = block_graph_.sections().size();
1509 :
1510 : // Get the block hash.
1511 E : block_graph::BlockHash b1_hash(b1);
1512 E : std::string b1_hash_str = base::MD5DigestToBase16(b1_hash.md5_digest);
1513 E : MD5Hash b1_hashes[2] = {};
1514 E : strncpy(b1_hashes[0].hash, b1_hash_str.c_str(), sizeof(b1_hashes[0].hash));
1515 :
1516 : AsanIntercept b1_intercepts[] = {
1517 : { "testAsan_b1", "_testAsan_b1", "foo.dll", b1_hashes, true },
1518 : { NULL },
1519 E : };
1520 :
1521 : // Find statically linked functions.
1522 E : asan_transform_.use_interceptors_ = true;
1523 : asan_transform_.PeFindStaticallyLinkedFunctionsToIntercept(b1_intercepts,
1524 E : &block_graph_);
1525 :
1526 E : ASSERT_EQ(1U, asan_transform_.static_intercepted_blocks_.size());
1527 E : EXPECT_EQ(b1, *(asan_transform_.static_intercepted_blocks_.begin()));
1528 :
1529 : // Intercept all calls to b1.
1530 : EXPECT_TRUE(asan_transform_.PeInterceptFunctions(b1_intercepts,
1531 : policy_,
1532 : &block_graph_,
1533 E : header_block_));
1534 :
1535 : // The block graph should have grown by 3 blocks:
1536 : // - the Import Address Table (IAT),
1537 : // - the Import Name Table (INT),
1538 : // - the thunk.
1539 E : EXPECT_EQ(num_blocks_pre_transform + 3, block_graph_.blocks().size());
1540 :
1541 : // The .thunks section should have been added.
1542 E : EXPECT_EQ(num_sections_pre_transform + 1, block_graph_.sections().size());
1543 :
1544 : BlockGraph::Section* thunk_section = block_graph_.FindSection(
1545 E : common::kThunkSectionName);
1546 E : ASSERT_TRUE(thunk_section != NULL);
1547 :
1548 E : const BlockGraph::Block* block_in_thunk_section = NULL;
1549 : BlockGraph::BlockMap::const_iterator iter_blocks =
1550 E : block_graph_.blocks().begin();
1551 E : for (; iter_blocks != block_graph_.blocks().end(); ++iter_blocks) {
1552 E : if (iter_blocks->second.section() == thunk_section->id()) {
1553 : // There should be only one block in the thunk section.
1554 E : EXPECT_TRUE(block_in_thunk_section == NULL);
1555 E : block_in_thunk_section = &iter_blocks->second;
1556 : }
1557 E : }
1558 :
1559 : // Only the entry in the IAT should refer to b1.
1560 E : EXPECT_EQ(1U, b1->referrers().size());
1561 E : }
1562 :
1563 E : TEST_F(AsanTransformTest, CoffInterceptFunctions) {
1564 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDllObj());
1565 :
1566 E : size_t num_blocks_pre_transform = block_graph_.blocks().size();
1567 E : size_t num_sections_pre_transform = block_graph_.sections().size();
1568 :
1569 : AsanIntercept intercepts[] = {
1570 : { "function2", "?function2@@YAHXZ", "", NULL, true },
1571 : { NULL },
1572 E : };
1573 :
1574 : // Intercept all calls to b1.
1575 E : asan_transform_.use_interceptors_ = true;
1576 : EXPECT_TRUE(asan_transform_.CoffInterceptFunctions(intercepts,
1577 : policy_,
1578 : &block_graph_,
1579 E : header_block_));
1580 :
1581 : // The block graph should not have grown at all, as no thunks are necessary
1582 : // in the COFF instrumentation mode.
1583 E : EXPECT_EQ(num_blocks_pre_transform, block_graph_.blocks().size());
1584 :
1585 : // No sections should have been added.
1586 E : EXPECT_EQ(num_sections_pre_transform, block_graph_.sections().size());
1587 E : }
1588 :
1589 : namespace {
1590 :
1591 E : void GetImageSizeSubsampledInstrumentation(double rate, size_t* size) {
1592 E : ASSERT_LE(0.0, rate);
1593 E : ASSERT_GE(1.0, rate);
1594 E : ASSERT_TRUE(size != NULL);
1595 :
1596 : base::FilePath test_dll_path = ::testing::GetOutputRelativePath(
1597 E : testing::kTestDllName);
1598 :
1599 E : pe::PEFile pe_file;
1600 E : ASSERT_TRUE(pe_file.Init(test_dll_path));
1601 :
1602 E : BlockGraph block_graph;
1603 E : pe::ImageLayout layout(&block_graph);
1604 E : pe::Decomposer decomposer(pe_file);
1605 E : ASSERT_TRUE(decomposer.Decompose(&layout));
1606 :
1607 : BlockGraph::Block* header_block = layout.blocks.GetBlockByAddress(
1608 E : core::RelativeAddress(0));
1609 E : ASSERT_TRUE(header_block != NULL);
1610 :
1611 E : AsanTransform tx;
1612 E : tx.set_instrumentation_rate(rate);
1613 :
1614 E : pe::PETransformPolicy policy;
1615 E : ASSERT_TRUE(tx.TransformBlockGraph(&policy, &block_graph, header_block));
1616 :
1617 E : *size = 0;
1618 E : BlockGraph::BlockMap::const_iterator block_it = block_graph.blocks().begin();
1619 E : for (; block_it != block_graph.blocks().end(); ++block_it) {
1620 E : *size += block_it->second.size();
1621 E : }
1622 E : }
1623 :
1624 : } // namespace
1625 :
1626 E : TEST_F(AsanTransformTest, SubsampledInstrumentationTestDll) {
1627 E : size_t rate0 = 0;
1628 E : ASSERT_NO_FATAL_FAILURE(GetImageSizeSubsampledInstrumentation(0.0, &rate0));
1629 :
1630 E : size_t rate50 = 0;
1631 E : ASSERT_NO_FATAL_FAILURE(GetImageSizeSubsampledInstrumentation(0.5, &rate50));
1632 :
1633 E : size_t rate100 = 0;
1634 E : ASSERT_NO_FATAL_FAILURE(GetImageSizeSubsampledInstrumentation(1.0, &rate100));
1635 :
1636 E : size_t size100 = rate100 - rate0;
1637 E : size_t size50 = rate50 - rate0;
1638 :
1639 : // This could theoretically fail, but that would imply an extremely bad
1640 : // implementation of the underlying random number generator. There are about
1641 : // 1850 instructions being instrumented. Since this is effectively a fair
1642 : // coin toss we expect a standard deviation of 0.5 * sqrt(1850) = 22
1643 : // instructions. A 10% margin is 185 / 22 = 8.4 standard deviations. For
1644 : // |z| > 8.4, the p-value is 4.5e-17, or 17 nines of confidence. That should
1645 : // keep any flake largely at bay. Thus, if this fails it's pretty much certain
1646 : // the implementation is at fault.
1647 E : EXPECT_LE(40 * size100 / 100, size50);
1648 E : EXPECT_GE(60 * size100 / 100, size50);
1649 E : }
1650 :
1651 E : TEST_F(AsanTransformTest, PeInjectAsanParametersNoStackIds) {
1652 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
1653 :
1654 E : common::InflatedAsanParameters params;
1655 E : asan_transform_.set_asan_parameters(¶ms);
1656 : EXPECT_TRUE(asan_transform_.PeInjectAsanParameters(
1657 E : policy_, &block_graph_, header_block_));
1658 :
1659 : // There should be a block containing parameters with the appropriate size.
1660 E : ASSERT_TRUE(asan_transform_.asan_parameters_block_ != NULL);
1661 : EXPECT_EQ(sizeof(common::AsanParameters),
1662 E : asan_transform_.asan_parameters_block_->size());
1663 :
1664 : // The block should contain no references.
1665 E : EXPECT_TRUE(asan_transform_.asan_parameters_block_->references().empty());
1666 :
1667 : // The block should not be referred to at all.
1668 E : EXPECT_TRUE(asan_transform_.asan_parameters_block_->referrers().empty());
1669 E : }
1670 :
1671 E : TEST_F(AsanTransformTest, PeInjectAsanParametersStackIds) {
1672 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
1673 :
1674 E : common::InflatedAsanParameters params;
1675 E : params.ignored_stack_ids_set.insert(0xDEADBEEF);
1676 :
1677 E : asan_transform_.set_asan_parameters(¶ms);
1678 : EXPECT_TRUE(asan_transform_.PeInjectAsanParameters(
1679 E : policy_, &block_graph_, header_block_));
1680 :
1681 : // There should be a block containing parameters with the appropriate size.
1682 E : ASSERT_TRUE(asan_transform_.asan_parameters_block_ != NULL);
1683 : EXPECT_EQ(sizeof(common::AsanParameters) + 2 * sizeof(common::AsanStackId),
1684 E : asan_transform_.asan_parameters_block_->size());
1685 :
1686 : // The block should contain one reference to itself, from and to the
1687 : // appropriate place.
1688 E : EXPECT_EQ(1u, asan_transform_.asan_parameters_block_->references().size());
1689 : BlockGraph::Reference ignored_stack_ids_ref(
1690 : BlockGraph::ABSOLUTE_REF,
1691 : BlockGraph::Reference::kMaximumSize,
1692 : asan_transform_.asan_parameters_block_,
1693 : sizeof(common::AsanParameters),
1694 E : sizeof(common::AsanParameters));
1695 : BlockGraph::Block::ReferenceMap::const_iterator ignored_stack_ids_ref_it =
1696 E : asan_transform_.asan_parameters_block_->references().begin();
1697 : EXPECT_EQ(offsetof(common::AsanParameters, ignored_stack_ids),
1698 E : ignored_stack_ids_ref_it->first);
1699 E : EXPECT_EQ(ignored_stack_ids_ref, ignored_stack_ids_ref_it->second);
1700 :
1701 : // The block should only be referred to by itself.
1702 E : EXPECT_EQ(1u, asan_transform_.asan_parameters_block_->referrers().size());
1703 E : }
1704 :
1705 E : TEST_F(AsanTransformTest, FindHeapInitAndCrtHeapBlocks) {
1706 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
1707 :
1708 E : asan_transform_.FindHeapInitAndCrtHeapBlocks(&block_graph_);
1709 :
1710 E : ASSERT_FALSE(asan_transform_.heap_init_blocks_.empty());
1711 E : for (const auto& iter : asan_transform_.heap_init_blocks_)
1712 E : EXPECT_NE(std::string::npos, iter->name().find("_heap_init"));
1713 E : }
1714 :
1715 E : TEST_F(AsanTransformTest, ShouldSkipBlock) {
1716 E : testing::DummyTransformPolicy policy;
1717 :
1718 : BlockGraph::Block* b1 =
1719 E : block_graph_.AddBlock(BlockGraph::CODE_BLOCK, 0x20, "testAsan_b1");
1720 : BlockGraph::Block* b2 =
1721 E : block_graph_.AddBlock(BlockGraph::DATA_BLOCK, 0x20, "testAsan_b2");
1722 E : ASSERT_TRUE(b1 != NULL);
1723 E : ASSERT_TRUE(b2 != NULL);
1724 :
1725 : // A code block should not be skipped according to the dummy policy.
1726 E : EXPECT_FALSE(asan_transform_.ShouldSkipBlock(&policy, b1));
1727 :
1728 : // _heap_init block should be skipped.
1729 E : asan_transform_.heap_init_blocks_.push_back(b1);
1730 E : EXPECT_TRUE(asan_transform_.ShouldSkipBlock(&policy, b1));
1731 E : asan_transform_.heap_init_blocks_.clear();
1732 E : EXPECT_FALSE(asan_transform_.ShouldSkipBlock(&policy, b1));
1733 :
1734 : // A block in static_intercepted_blocks_ should be skipped.
1735 E : asan_transform_.static_intercepted_blocks_.insert(b1);
1736 E : EXPECT_TRUE(asan_transform_.ShouldSkipBlock(&policy, b1));
1737 E : asan_transform_.static_intercepted_blocks_.erase(b1);
1738 E : EXPECT_FALSE(asan_transform_.ShouldSkipBlock(&policy, b1));
1739 :
1740 : // A data block should be skipped according to the dummy policy.
1741 E : EXPECT_TRUE(asan_transform_.ShouldSkipBlock(&policy, b2));
1742 E : }
1743 :
1744 E : TEST_F(AsanTransformTest, PatchCRTHeapInitialization) {
1745 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
1746 :
1747 : // Keep a reference to all the heap initialization blocks that should be
1748 : // patched.
1749 :
1750 : std::map<const BlockGraph::Block*,
1751 : std::pair<BlockGraph::Offset, BlockGraph::Reference>>
1752 E : heap_init_blocks;
1753 :
1754 E : pe::transforms::ImportedModule kernel32("kernel32.dll");
1755 E : pe::transforms::PEAddImportsTransform kernel32_transform;
1756 :
1757 : size_t get_process_heap_idx = kernel32.AddSymbol(
1758 E : "GetProcessHeap", pe::transforms::ImportedModule::kFindOnly);
1759 E : kernel32_transform.AddModule(&kernel32);
1760 :
1761 : EXPECT_TRUE(block_graph::ApplyBlockGraphTransform(&kernel32_transform,
1762 : policy_,
1763 : &block_graph_,
1764 E : header_block_));
1765 E : BlockGraph::Reference get_process_heap_ref;
1766 : EXPECT_TRUE(kernel32.GetSymbolReference(get_process_heap_idx,
1767 E : &get_process_heap_ref));
1768 :
1769 E : for (const auto& iter : block_graph_.blocks()) {
1770 E : if (iter.second.name().find("_heap_init") == std::string::npos)
1771 E : continue;
1772 E : for (const auto& ref : iter.second.references()) {
1773 E : if (ref.second == get_process_heap_ref)
1774 E : heap_init_blocks[&iter.second] = ref;
1775 : }
1776 E : }
1777 E : EXPECT_FALSE(heap_init_blocks.empty());
1778 :
1779 : // Apply the Asan transform.
1780 E : asan_transform_.use_interceptors_ = true;
1781 E : asan_transform_.use_liveness_analysis_ = true;
1782 : ASSERT_TRUE(block_graph::ApplyBlockGraphTransform(
1783 E : &asan_transform_, &pe_policy_, &block_graph_, header_block_));
1784 :
1785 : // Get a referenece to the heap create function that has been used to patch
1786 : // these blocks.
1787 : pe::transforms::ImportedModule asan_module(
1788 E : AsanTransform::kSyzyAsanDll);
1789 E : pe::transforms::PEAddImportsTransform asan_import_transform;
1790 : size_t asan_heap_create_idx = asan_module.AddSymbol(
1791 E : "asan_HeapCreate", pe::transforms::ImportedModule::kFindOnly);
1792 E : asan_import_transform.AddModule(&asan_module);
1793 : EXPECT_TRUE(block_graph::ApplyBlockGraphTransform(&asan_import_transform,
1794 : policy_,
1795 : &block_graph_,
1796 E : header_block_));
1797 E : BlockGraph::Reference asan_heap_create_ref;
1798 : EXPECT_TRUE(asan_module.GetSymbolReference(asan_heap_create_idx,
1799 E : &asan_heap_create_ref));
1800 :
1801 : // Verify that the patched blocks contains a reference to this heap create
1802 : // function.
1803 E : for (const auto& iter : heap_init_blocks) {
1804 E : const BlockGraph::Block* block = iter.first;
1805 E : BlockGraph::Offset offset = iter.second.first;
1806 :
1807 : // The blocks should contain a reference to a data block in the Syzygy thunk
1808 : // section.
1809 E : BlockGraph::Reference thunk_data_ref;
1810 E : EXPECT_TRUE(block->GetReference(offset, &thunk_data_ref));
1811 : BlockGraph::SectionId syzygy_section =
1812 E : block_graph_.FindSection(common::kThunkSectionName)->id();
1813 E : EXPECT_EQ(syzygy_section, thunk_data_ref.referenced()->section());
1814 E : EXPECT_EQ(BlockGraph::DATA_BLOCK, thunk_data_ref.referenced()->type());
1815 E : EXPECT_EQ(1, thunk_data_ref.referenced()->references().size());
1816 :
1817 : // This data block should refer to a code block also in the Syzygy thunk
1818 : // section.
1819 E : BlockGraph::Reference thunk_code_ref;
1820 E : EXPECT_TRUE(thunk_data_ref.referenced()->GetReference(0,
1821 : &thunk_code_ref));
1822 E : EXPECT_EQ(syzygy_section, thunk_code_ref.referenced()->section());
1823 E : EXPECT_EQ(BlockGraph::CODE_BLOCK, thunk_code_ref.referenced()->type());
1824 E : EXPECT_EQ(1, thunk_code_ref.referenced()->references().size());
1825 :
1826 : // And lastly, this code block should refer to the HeapCreate function.
1827 E : BlockGraph::Reference thunk_heap_create_ref;
1828 : BlockGraph::Offset ref_idx =
1829 E : thunk_code_ref.referenced()->references().begin()->first;
1830 E : EXPECT_TRUE(thunk_code_ref.referenced()->GetReference(ref_idx,
1831 : &thunk_heap_create_ref));
1832 E : EXPECT_EQ(asan_heap_create_ref, thunk_heap_create_ref);
1833 E : }
1834 E : }
1835 :
1836 E : TEST_F(AsanTransformTest, HotPatchingSection) {
1837 E : ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());
1838 :
1839 E : asan_transform_.set_hot_patching(true);
1840 : ASSERT_TRUE(block_graph::ApplyBlockGraphTransform(
1841 E : &asan_transform_, policy_, &block_graph_, header_block_));
1842 :
1843 : // Look for the presence of the hot patching section.
1844 E : const BlockGraph::Section* hp_section = nullptr;
1845 E : for (const auto& entry : block_graph_.sections()) {
1846 E : const BlockGraph::Section* sect = &entry.second;
1847 E : if (sect->name() == common::kHotPatchingMetadataSectionName) {
1848 E : hp_section = sect;
1849 : }
1850 E : }
1851 E : ASSERT_NE(nullptr, hp_section);
1852 :
1853 : // We iterate over the blocks and check that a block is in the list of hot
1854 : // patched blocks iff it has been prepared for hot patching.
1855 : std::unordered_set<const BlockGraph::Block*> hot_patched_set_(
1856 : asan_transform_.hot_patched_blocks_.begin(),
1857 E : asan_transform_.hot_patched_blocks_.end());
1858 E : for (const auto& entry : block_graph_.blocks()) {
1859 E : const BlockGraph::Block* block = &entry.second;
1860 :
1861 : // We check |padding_before| to see if the block has been prepared for hot
1862 : // patching.
1863 E : size_t expected_padding = hot_patched_set_.count(block) ? 5U : 0U;
1864 E : EXPECT_EQ(expected_padding, block->padding_before());
1865 E : }
1866 E : }
1867 :
1868 : } // namespace transforms
1869 : } // namespace instrument
|