• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_
18 #define ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_
19 
20 #include <sys/stat.h>
21 #include <cstdio>
22 #include <cstdlib>
23 #include <fstream>
24 #include <iterator>
25 #include <regex>
26 
27 #include "android-base/strings.h"
28 
29 #include "base/os.h"
30 #include "base/utils.h"
31 #include "common_runtime_test.h"  // For ScratchDir.
32 #include "elf/elf_builder.h"
33 #include "elf/elf_debug_reader.h"
34 #include "exec_utils.h"
35 #include "stream/file_output_stream.h"
36 
37 namespace art {
38 
39 // If you want to take a look at the differences between the ART assembler and clang,
40 // set this flag to true. The disassembled files will then remain in the tmp directory.
41 static constexpr bool kKeepDisassembledFiles = false;
42 
43 // We put this into a class as gtests are self-contained, so this helper needs to be in an h-file.
44 class AssemblerTestBase : public testing::Test {
45  public:
AssemblerTestBase()46   AssemblerTestBase() {}
47 
SetUp()48   void SetUp() override {
49     // Fake a runtime test for ScratchDir.
50     CommonArtTest::SetUpAndroidRootEnvVars();
51     CommonRuntimeTest::SetUpAndroidDataDir(android_data_);
52     scratch_dir_.emplace(/*keep_files=*/ kKeepDisassembledFiles);
53   }
54 
TearDown()55   void TearDown() override {
56     // We leave temporaries in case this failed so we can debug issues.
57     CommonRuntimeTest::TearDownAndroidDataDir(android_data_, false);
58   }
59 
60   // This is intended to be run as a test.
CheckTools()61   bool CheckTools() {
62     for (auto cmd : { GetAssemblerCommand()[0], GetDisassemblerCommand()[0] }) {
63       if (!OS::FileExists(cmd.c_str())) {
64         LOG(ERROR) << "Could not find " << cmd;
65         return false;
66       }
67     }
68     return true;
69   }
70 
71   // Driver() assembles and compares the results. If the results are not equal and we have a
72   // disassembler, disassemble both and check whether they have the same mnemonics (in which case
73   // we just warn).
Driver(const std::vector<uint8_t> & art_code,const std::string & assembly_text,const std::string & test_name)74   void Driver(const std::vector<uint8_t>& art_code,
75               const std::string& assembly_text,
76               const std::string& test_name) {
77     ASSERT_NE(assembly_text.length(), 0U) << "Empty assembly";
78     InstructionSet isa = GetIsa();
79     auto test_path = [&](const char* ext) { return scratch_dir_->GetPath() + test_name + ext; };
80 
81     // Create file containing the reference source code.
82     std::string ref_asm_file = test_path(".ref.S");
83     WriteFile(ref_asm_file, assembly_text.data(), assembly_text.size());
84 
85     // Assemble reference object file.
86     std::string ref_obj_file = test_path(".ref.o");
87     ASSERT_TRUE(Assemble(ref_asm_file.c_str(), ref_obj_file.c_str()));
88 
89     // Read the code produced by assembler from the ELF file.
90     std::vector<uint8_t> ref_code;
91     if (Is64BitInstructionSet(isa)) {
92       ReadElf</*IsElf64=*/true>(ref_obj_file, &ref_code);
93     } else {
94       ReadElf</*IsElf64=*/false>(ref_obj_file, &ref_code);
95     }
96 
97     // Compare the ART generated code to the expected reference code.
98     if (art_code == ref_code) {
99       return;  // Success!
100     }
101 
102     // Create ELF file containing the ART code.
103     std::string art_obj_file = test_path(".art.o");
104     if (Is64BitInstructionSet(isa)) {
105       WriteElf</*IsElf64=*/true>(art_obj_file, isa, art_code);
106     } else {
107       WriteElf</*IsElf64=*/false>(art_obj_file, isa, art_code);
108     }
109 
110     // Disassemble both object files, and check that the outputs match.
111     std::string art_disassembly;
112     ASSERT_TRUE(Disassemble(art_obj_file, &art_disassembly));
113     art_disassembly = Replace(art_disassembly, art_obj_file, test_path("<extension-redacted>"));
114     art_disassembly = StripComments(art_disassembly);
115     std::string ref_disassembly;
116     ASSERT_TRUE(Disassemble(ref_obj_file, &ref_disassembly));
117     ref_disassembly = Replace(ref_disassembly, ref_obj_file, test_path("<extension-redacted>"));
118     ref_disassembly = StripComments(ref_disassembly);
119     ASSERT_EQ(art_disassembly, ref_disassembly) << "Outputs (and disassembly) not identical.";
120 
121     // ART produced different (but valid) code than the reference assembler, report it.
122     if (art_code.size() > ref_code.size()) {
123       EXPECT_TRUE(false) << "ART code is larger then the reference code, but the disassembly"
124           "of machine code is equal: this means that ART is generating sub-optimal encoding! "
125           "ART code size=" << art_code.size() << ", reference code size=" << ref_code.size();
126     } else if (art_code.size() < ref_code.size()) {
127       EXPECT_TRUE(false) << "ART code is smaller than the reference code. Too good to be true?";
128     } else {
129       LOG(INFO) << "Reference assembler chose a different encoding than ART (of the same size)";
130     }
131   }
132 
133  protected:
134   virtual InstructionSet GetIsa() = 0;
135 
FindTool(const std::string & tool_name)136   std::string FindTool(const std::string& tool_name) {
137     return CommonArtTest::GetAndroidTool(tool_name.c_str(), GetIsa());
138   }
139 
GetAssemblerCommand()140   virtual std::vector<std::string> GetAssemblerCommand() {
141     InstructionSet isa = GetIsa();
142     switch (isa) {
143       case InstructionSet::kX86:
144         return {FindTool("clang"), "--compile", "-target", "i386-linux-gnu"};
145       case InstructionSet::kX86_64:
146         return {FindTool("clang"), "--compile", "-target", "x86_64-linux-gnu"};
147       default:
148         LOG(FATAL) << "Unknown instruction set: " << isa;
149         UNREACHABLE();
150     }
151   }
152 
GetDisassemblerCommand()153   virtual std::vector<std::string> GetDisassemblerCommand() {
154     switch (GetIsa()) {
155       case InstructionSet::kThumb2:
156         return {FindTool("llvm-objdump"), "--disassemble", "--triple", "thumbv7a-linux-gnueabi"};
157       default:
158         return {FindTool("llvm-objdump"), "--disassemble", "--no-show-raw-insn"};
159     }
160   }
161 
Assemble(const std::string & asm_file,const std::string & obj_file)162   bool Assemble(const std::string& asm_file, const std::string& obj_file) {
163     std::vector<std::string> args = GetAssemblerCommand();
164     args.insert(args.end(), {"-o", obj_file, asm_file});
165     std::string output;
166     bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, &output).StandardSuccess();
167     if (!ok) {
168       LOG(ERROR) << "Assembler error:\n" << output;
169     }
170     return ok;
171   }
172 
Disassemble(const std::string & obj_file,std::string * output)173   bool Disassemble(const std::string& obj_file, std::string* output) {
174     std::vector<std::string> args = GetDisassemblerCommand();
175     args.insert(args.end(), {obj_file});
176     bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, output).StandardSuccess();
177     if (!ok) {
178       LOG(ERROR) << "Disassembler error:\n" << *output;
179     }
180     *output = Replace(*output, "\t", " ");
181     return ok;
182   }
183 
ReadFile(const std::string & filename)184   std::vector<uint8_t> ReadFile(const std::string& filename) {
185     std::unique_ptr<File> file(OS::OpenFileForReading(filename.c_str()));
186     CHECK(file.get() != nullptr);
187     std::vector<uint8_t> data(file->GetLength());
188     bool success = file->ReadFully(&data[0], data.size());
189     CHECK(success) << filename;
190     return data;
191   }
192 
WriteFile(const std::string & filename,const void * data,size_t size)193   void WriteFile(const std::string& filename, const void* data, size_t size) {
194     std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
195     CHECK(file.get() != nullptr);
196     bool success = file->WriteFully(data, size);
197     CHECK(success) << filename;
198     CHECK_EQ(file->FlushClose(), 0);
199   }
200 
201   // Helper method which reads the content of .text section from ELF file.
202   template<bool IsElf64>
ReadElf(const std::string & filename,std::vector<uint8_t> * code)203   void ReadElf(const std::string& filename, /*out*/ std::vector<uint8_t>* code) {
204     using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
205     std::vector<uint8_t> data = ReadFile(filename);
206     ElfDebugReader<ElfTypes> reader((ArrayRef<const uint8_t>(data)));
207     const typename ElfTypes::Shdr* text = reader.GetSection(".text");
208     CHECK(text != nullptr);
209     *code = std::vector<uint8_t>(&data[text->sh_offset], &data[text->sh_offset + text->sh_size]);
210   }
211 
212   // Helper method to create an ELF file containing only the given code in the .text section.
213   template<bool IsElf64>
WriteElf(const std::string & filename,InstructionSet isa,const std::vector<uint8_t> & code)214   void WriteElf(const std::string& filename, InstructionSet isa, const std::vector<uint8_t>& code) {
215     using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
216     std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
217     CHECK(file.get() != nullptr);
218     FileOutputStream out(file.get());
219     std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
220     builder->Start(/* write_program_headers= */ false);
221     builder->GetText()->Start();
222     builder->GetText()->WriteFully(code.data(), code.size());
223     builder->GetText()->End();
224     builder->End();
225     CHECK(builder->Good());
226     CHECK_EQ(file->Close(), 0);
227   }
228 
GetRootPath()229   static std::string GetRootPath() {
230     // 1) Check ANDROID_BUILD_TOP
231     char* build_top = getenv("ANDROID_BUILD_TOP");
232     if (build_top != nullptr) {
233       return std::string(build_top) + "/";
234     }
235 
236     // 2) Do cwd
237     char temp[1024];
238     return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string("");
239   }
240 
Replace(const std::string & str,const std::string & from,const std::string & to)241   std::string Replace(const std::string& str, const std::string& from, const std::string& to) {
242     std::string output;
243     size_t pos = 0;
244     for (auto match = str.find(from); match != str.npos; match = str.find(from, pos)) {
245       output += str.substr(pos, match - pos);
246       output += to;
247       pos = match + from.size();
248     }
249     output += str.substr(pos, str.size() - pos);
250     return output;
251   }
252 
253   // Remove comments emitted by objdump.
StripComments(const std::string & str)254   std::string StripComments(const std::string& str) {
255     return std::regex_replace(str, std::regex(" +# .*"), "");
256   }
257 
258   std::optional<ScratchDir> scratch_dir_;
259   std::string android_data_;
260   DISALLOW_COPY_AND_ASSIGN(AssemblerTestBase);
261 };
262 
263 }  // namespace art
264 
265 #endif  // ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_
266